http://stackoverflow.com/q/48976845
tagged with: python
has title: Matplotlib's inset_locator with inverted axes
type: AnsweredQuestion
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/48987903
accepted answer: http://stackoverflow.com/a/48987903
score: 5
tagged with: matplotlib
has body: I want to make a standard inset into my plot. But I don't get how to use the inset_locator. Here is my code: import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.axes_grid1.inset_locator import inset_axes, mark_inset x = np.linspace(0, 2) plt.plot(x, np.sin(x)) ax = plt.gca() ax.invert_yaxis() axins = inset_axes(ax, width='40%', height='30%', loc='lower left') x_in = np.linspace(1.25, 1.75) axins.plot(x_in, np.sin(x_in)) axins.invert_yaxis() mark_inset(ax, axins, loc1=2, loc2=4) plt.show() And the result is: Apparently it the edges connect the wrong corners. How do I get them right, when my axis goes from maximum to minimum?
answer count: 1
tagged with: insets
favorite count: 0
upvote count: 5

http://stackoverflow.com/q/48993754
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48994573
has answer: http://stackoverflow.com/a/48994573
has answer: http://stackoverflow.com/a/49017975
favorite count: 0
upvote count: 2
tagged with: flask-wtforms
has comment: http://stackoverflow.com/comment/84992833
tagged with: python
tagged with: jinja2
has body: I am trying to create a jinaj2 template with a dynamic number of input fields. The form is generating successfully in Flask, however I am having issues with the Jinja/HTML. As an example of my "non-dynamic" working example I have one standard form field "forID" and and four hard coded field forms field+(field number). {{ form.csrf_token }} {{ wtf.form_field(form.formID) }} {{ wtf.form_field(form.field1) }} {{ wtf.form_field(form.field2) }} {{ wtf.form_field(form.field3) }} {{ wtf.form_field(form.field4) }} What method can I use to make the Jinja/HTML dynamic. I have tried EVAL and EVEC, but these Python commands are not supported in Jinja. #&lt;form method="POST" action = "{{url_for('myHtmlTemplate')}}"&gt; {{ form.csrf_token }} {{ wtf.form_field(form.formID) }} {% for i in form.myDynamicFields.keys() %}: {{ eval(' wtf.form_field(form.'+'i')') }} {% endfor %} &lt;input class="btn btn-success" type="submit" value="Submit"&gt; #&lt;/form&gt; My current myForm. class myform(FlaskForm): connection = removed result = connection.execute("SELECT * FROM sqltable") result = result.fetchall() scenarioList = [] fieldList = [] fieldLabel = [] for scen in result: scenarioList.append("Scenario: " + scen[0]) fieldList.append("field: " + scen[0]) for i in range(len(result)): fieldLabel.append("My Field" + str(i + 1)) myDynamicFields = dict(zip(fieldLabel, fieldList)) formID = StringField('Form ID') for key, val in myDynamicFields.items(): exec(key + '=StringField(val)')
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84994251
accepted answer: http://stackoverflow.com/a/49017975
has title: Flask/Jinja2 dynamic WTF form template
type: Question

http://stackoverflow.com/a/48979560
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48979223
answers question: http://stackoverflow.com/q/48979223
downvote count: 0
has body: You're trying to int() the string 'n' in your assertion. To get the same error: int('n') ValueError Traceback (most recent call last) &lt;ipython-input-18-35fea8808c96&gt; in &lt;module&gt;() ----&gt; 1 int('n') ValueError: invalid literal for int() with base 10: 'n' What exactly are you trying to pull out in that list comprehension? It looks like sort of a tuple of date information, but a bit more information about what you're trying to pull out, or comments in the code explaining the logic more clearly would help us get you to the solution. EDIT: If you use pandas.Timestamp it may do all that conversion for you - now that I look at the code it looks like you're just trying to pull out the day of the week, and the month. It may not work if it can't cnovert the timestamp for you, but it's pretty likely that it would. A small sample of the CSV data you're using would confirm easily enough. days = numpy.array(pandas.Timestamp(date).weekday() for date in dates]) months = numpy.array(pandas.Timestamp(date).month() for date in dates])
has comment: http://stackoverflow.com/comment/84965825
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84967213
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84964853

http://stackoverflow.com/a/49019296
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49019230
type: Answer
upvote count: 3
has body: You need to use axis=1, also, youll have to use pd.isnull(row['a']): In [6]: df.apply(lambda row: row['b'] if pd.isnull(row['a']) else row['a'], axis=1) Out[6]: 0 1.0 1 2.0 2 3.0 3 4.0 4 8.0 5 9.0 6 5.0 dtype: float64 Although, you shouldn't be using .apply in the first place, use fillna: In [9]: df.a.fillna(df.b) Out[9]: 0 1.0 1 2.0 2 3.0 3 4.0 4 8.0 5 9.0 6 5.0 Name: a, dtype: float64 More generally, for any predicate, use pd.Series.where: In [32]: df.a.where(pd.notnull, df.b) Out[32]: 0 1.0 1 2.0 2 3.0 3 4.0 4 8.0 5 9.0 6 5.0 Name: a, dtype: float64
accepted answer of: http://stackoverflow.com/q/49019230
score: 3

http://stackoverflow.com/q/48997385
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: machine-learning
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85006869
has comment: http://stackoverflow.com/comment/85000933
tagged with: neural-network
has comment: http://stackoverflow.com/comment/85001358
has comment: http://stackoverflow.com/comment/85001182
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85001383
tagged with: keras
accepted answer: http://stackoverflow.com/a/49196209
favorite count: 0
has comment: http://stackoverflow.com/comment/85001326
has comment: http://stackoverflow.com/comment/85034414
has comment: http://stackoverflow.com/comment/85001349
tagged with: python
has body: While trying to train a GAN for image generation I ran into a problem which I cannot explain. When training the generator, the loss which is returned by train_on_batch after just 2 or 3 iterations directly drops to zero. After investigating I realized some strange behavior of the train_on_batch method: When I check the following: noise = np.random.uniform(-1.0, 1.0, size=[batch_size, gen_noise_length]) predictions = GAN.stackedModel.predict(noise) This returns values all close to zero as I would expect since the generator is not trained yet. However: y = np.ones([batch_size, 1]) noise = np.random.uniform(-1.0, 1.0, size=[batch_size, gen_noise_length]) loss = GAN.stackedModel.train_on_batch(noise, y) here the loss is almost zero even though my expected targets are obvious ones. When I run: y = np.ones([batch_size, 1]) noise = np.random.uniform(-1.0, 1.0, size=[batch_size, gen_noise_length]) loss = GAN.stackedModel.test_on_batch(noise, y) the returned loss is high as I would expect. What is going on with the train_on_batch method? I'm really clueless here... edit My loss is binary-crossentropy and I build the model like: def createStackedModel(self): # Build stacked GAN model gan_in = Input([self.noise_length]) H = self.genModel(gan_in) gan_V = self.disModel(H) GAN = Model(gan_in, gan_V) opt = RMSprop(lr=0.0001, decay=3e-8) GAN.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy']) return GAN edit 2 The generator is constructed by stacking some of those blocks each containing a BatchNormalization: self.G.add(UpSampling2D()) self.G.add(Conv2DTranspose(int(depth/8), 5, padding='same')) self.G.add(BatchNormalization(momentum=0.5)) self.G.add(Activation('relu')) edit 3 I loaded my code to https://gitlab.com/benjamingraf24/DCGAN/ Apparently the problem results from the way how I build the GAN network. So in GANBuilder.py there must be something wrong. However, I cant find it...
has title: Different loss values for test_on_batch and train_on_batch
has answer: http://stackoverflow.com/a/49196209

python
tags question: http://stackoverflow.com/q/48977032
tags question: http://stackoverflow.com/q/49011601
tags question: http://stackoverflow.com/q/49014660
tags question: http://stackoverflow.com/q/49015736
tags question: http://stackoverflow.com/q/49031333
tags question: http://stackoverflow.com/q/49010361
tags question: http://stackoverflow.com/q/49109500
tags question: http://stackoverflow.com/q/48973742
tags question: http://stackoverflow.com/q/49022363
tags question: http://stackoverflow.com/q/49085694
tags question: http://stackoverflow.com/q/49090272
tags question: http://stackoverflow.com/q/48970643
tags question: http://stackoverflow.com/q/49062928
tags question: http://stackoverflow.com/q/48972154
tags question: http://stackoverflow.com/q/48966912
tags question: http://stackoverflow.com/q/49031454
tags question: http://stackoverflow.com/q/49091163
tags question: http://stackoverflow.com/q/49120765
tags question: http://stackoverflow.com/q/49047279
tags question: http://stackoverflow.com/q/48967092
tags question: http://stackoverflow.com/q/49113243
tags question: http://stackoverflow.com/q/48996653
tags question: http://stackoverflow.com/q/48990886
tags question: http://stackoverflow.com/q/49017509
tags question: http://stackoverflow.com/q/48972470
tags question: http://stackoverflow.com/q/49036237
tags question: http://stackoverflow.com/q/49010871
tags question: http://stackoverflow.com/q/49033335
tags question: http://stackoverflow.com/q/49042917
tags question: http://stackoverflow.com/q/48976415
tags question: http://stackoverflow.com/q/49018486
tags question: http://stackoverflow.com/q/49105343
tags question: http://stackoverflow.com/q/48970059
tags question: http://stackoverflow.com/q/49094060
tags question: http://stackoverflow.com/q/49049044
tags question: http://stackoverflow.com/q/48965221
tags question: http://stackoverflow.com/q/49060528
tags question: http://stackoverflow.com/q/48972044
tags question: http://stackoverflow.com/q/49011430
tags question: http://stackoverflow.com/q/49089984
tags question: http://stackoverflow.com/q/49083532
tags question: http://stackoverflow.com/q/49060163
tags question: http://stackoverflow.com/q/49083499
tags question: http://stackoverflow.com/q/49102864
tags question: http://stackoverflow.com/q/49119896
tags question: http://stackoverflow.com/q/49013181
tags question: http://stackoverflow.com/q/49079081
tags question: http://stackoverflow.com/q/49110702
tags question: http://stackoverflow.com/q/49103217
tags question: http://stackoverflow.com/q/49087841
tags question: http://stackoverflow.com/q/48981967
tags question: http://stackoverflow.com/q/49084713
tags question: http://stackoverflow.com/q/49054198
tags question: http://stackoverflow.com/q/49086866
tags question: http://stackoverflow.com/q/49034066
tags question: http://stackoverflow.com/q/49000036
tags question: http://stackoverflow.com/q/49007295
tags question: http://stackoverflow.com/q/49011260
tags question: http://stackoverflow.com/q/49092695
tags question: http://stackoverflow.com/q/49014754
tags question: http://stackoverflow.com/q/49008075
tags question: http://stackoverflow.com/q/49072822
tags question: http://stackoverflow.com/q/49037669
tags question: http://stackoverflow.com/q/49082933
tags question: http://stackoverflow.com/q/48980425
tags question: http://stackoverflow.com/q/49054977
tags question: http://stackoverflow.com/q/48965731
tags question: http://stackoverflow.com/q/49048059
tags question: http://stackoverflow.com/q/49071558
tags question: http://stackoverflow.com/q/49004255
tags question: http://stackoverflow.com/q/48997279
tags question: http://stackoverflow.com/q/49100244
tags question: http://stackoverflow.com/q/49023286
tags question: http://stackoverflow.com/q/49071221
tags question: http://stackoverflow.com/q/49014697
tags question: http://stackoverflow.com/q/49018135
tags question: http://stackoverflow.com/q/49079714
tags question: http://stackoverflow.com/q/48973678
tags question: http://stackoverflow.com/q/48987143
tags question: http://stackoverflow.com/q/49055680

http://stackoverflow.com/q/48982715
tagged with: python
has body: I am trying to load a saved model in order to use it for predictions after I restart the kernel. While saving the model seems to work, loading does not seem to work without issues. Heres what I have done: I have retrained a VGG16 model using Keras: vgg16_model = keras.applications.vgg16.VGG16() model = Sequential() for layer in vgg16_model.layers[:-1]: model.add(layer) model.layers.pop() for layer in model.layers: layer.trainable = False model.add(Dense(26, activation='softmax')) model.summary() model.compile(Adam(lr=.0000025), loss='categorical_crossentropy', metrics=['accuracy']) Next I have trained the model: model.fit_generator(train_batches,validation_data=validation_batches, epochs=85, verbose=1,callbacks=[tbCallBack,earlystopCallback]) and finally I am saving my model like so: model.save("model.h5") Now when I restart the kernel and load the model again using: from keras.models import load_model new_model = load_model("model.h5") While the model does load, I get a warning telling me: C:\Users...\Anaconda2\envs\tensorflow-gpu\lib\site-packages\keras\models.py:291: UserWarning: Error in loading the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer. warnings.warn('Error in loading the saved optimizer ' Furthermore, when I use the loaded model for predictions, I get wrong values (very different values from the one I trained) and it appears that the model has not been trained at all. However, when I check .get_weights I see that weights have been loaded. I have also tried to save and load the model via json and weights only like so: # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model_weights.h5") and loading: #load json and create model json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() load_model = model_from_json(loaded_model_json) # load weights into …
has comment: http://stackoverflow.com/comment/84972760
has title: Keras VGG16 - model.save and load giving different result
has comment: http://stackoverflow.com/comment/84985624
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
favorite count: 0
score: 3
answer count: 0
upvote count: 3
type: UnansweredQuestion

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

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

http://stackoverflow.com/q/49039491
tagged with: python
has comment: http://stackoverflow.com/comment/85084746
has title: Python: How can I stop my function values from changing after my first call (time series)
has answer: http://stackoverflow.com/a/49039966
has body: I have: np.random.seed(123) def v_t(var_v, T): v_t_ = np.zeros([T,1]) v_t_[1:T] = (var_v ** 0.5) * np.random.randn(len(v_t_) - 1, 1) return v_t_ def s_t(rho, T): v_t_ = v_t(var_v, T) s_t_ = np.zeros([T,1]) s_t_[0] = 0 for t in range(1,T): s_t_[t] = rho *s_t_[t-1] + v_t_[t] return s_t_ However every time I call one of the values, i.e. s_t(rho, T) "or" v_t(var_v, T) the right value is shown. But directly afterwards, when I call the other value, the value is wrong. (Probably due to some time series effect.) After I clear my namespace, when I call the functions in the mirrored sequence, the same holds true. How do I get the right values displayed for every call without resetting the namespace??? Would be great to hear from you! Cheers, Tobias
has comment: http://stackoverflow.com/comment/85084477
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85084807
type: Question
has comment: http://stackoverflow.com/comment/85084479
tagged with: call
tagged with: time-series
tagged with: function
has comment: http://stackoverflow.com/comment/85084428
answer count: 1
has comment: http://stackoverflow.com/comment/85084458
has comment: http://stackoverflow.com/comment/85084712
has comment: http://stackoverflow.com/comment/85084487

http://stackoverflow.com/q/49058353
has title: less common words in a python list
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/4743035
has answer: http://stackoverflow.com/a/49058439
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/85121567
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49058457
downvote count: 0
tagged with: counter
has body: I have done the counter of most common words to keep only the 128 most common words in my list in order: words = my_list mcommon_words = [word for word, word_count in Counter(words).most_common(128)] my_list = [x for x in my_list if x in mcommon_words] my_list = OrderedDict.fromkeys(my_list) my_list = list(my_list.keys()) But now I want to count the 128 less common words in the same way. A faster solution would help me a lot too
favorite count: 0

http://stackoverflow.com/q/49070382
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85146024
tagged with: string.format
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49070458
has body: I want to use the str.format() method like this: my_str = "Username: {username}, User data: {user_data.attribute}".format(**items) And apply it to items as shown below: items = { "username" : "Peter", "user_data" : { "attribute" : "foo" }} Is this feasible, and if so, then how? If not, I'm interested in your recommended approach.
type: Question
has comment: http://stackoverflow.com/comment/85146032
upvote count: 12
has comment: http://stackoverflow.com/comment/85145960
score: 12
linked to: http://stackoverflow.com/q/34442448
has comment: http://stackoverflow.com/comment/85146043
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85146232
has title: str.format() with nested dictionary
has comment: http://stackoverflow.com/comment/85146159
tagged with: python
has answer: http://stackoverflow.com/a/49070458

http://stackoverflow.com/q/49059046
has title: Make Jython JFrame that cannot be closed
type: UnansweredQuestion
has body: I'm writing a little script for TopSpin, a program to acquire and process NMR data. While the script is running the user should not select a different dataset in TopSpin. Therefore I wanted to open a Popup screen displaying a message. The script we are talking about, will take some time to finish it's task, so if a user closes the popup, the message will not be visible anymore and another staff member could - unknowingly - cause some problems by selecting different datasets. That's the reason why I had the idea of implementing a popup window that cannot be closed by the user. When the script starts it's task it will run popup.show() and after having finished it will run popup.hide(). How could I do this in Jython? from javax.swing import * def test(): frame = JFrame("Hello StackOverflow") frame.setSize(300, 300) frame.setLocationRelativeTo(None) frame.show() # Do some work frame.hide() test()
score: 1
favorite count: 0
type: Question
tagged with: jframe
upvote count: 1
tagged with: python
tagged with: jython
answer count: 0
downvote count: 0

http://stackoverflow.com/q/49092807
has title: When conda install django, PermissionError(13, 'Permission denied')
downvote count: 0
tagged with: ubuntu
has answer: http://stackoverflow.com/a/49093252
tagged with: permissions
favorite count: 0
upvote count: 8
possible better answer: http://stackoverflow.com/a/50565891
answer count: 5
has answer: http://stackoverflow.com/a/57693590
accepted answer: http://stackoverflow.com/a/49093252
has answer: http://stackoverflow.com/a/50565891
tagged with: django
has answer: http://stackoverflow.com/a/49092991
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
has answer: http://stackoverflow.com/a/50382293
has body: When I run conda install django, I get the following error: Solving environment: done ==> WARNING: A newer version of conda exists. &lt;== current version: 4.4.10 latest version: 4.4.11 Please update conda by running $ conda update -n base conda ## Package Plan ## environment location: /opt/anaconda/anaconda3 added / updated specs: - django The following NEW packages will be INSTALLED: django: 2.0.2-py36hd476221_0 Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_execute(481): An error occurred while installing package 'defaults::django-2.0.2-py36hd476221_0'. PermissionError(13, 'Permission denied') Attempting to roll back. Rolling back transaction: done PermissionError(13, 'Permission denied') What should I do?
type: Question
score: 8

http://stackoverflow.com/q/49105143
score: 0
answer count: 1
tagged with: python
type: AnsweredQuestion
has body: in tools directory in tensorflow, we have freeze graph python file, that we can use directly, so why do we need bazel, also I tried using that script, and got the following error : 226 elif input_graph: --&gt; 227 input_graph_def = _parse_input_graph_proto(input_graph, input_binary) 228 input_meta_graph_def = None 229 if input_meta_graph: /usr/local/lib/python3.5/dist-packages/tensorflow/python/tools/freeze_graph.py in _parse_input_graph_proto(input_graph, input_binary) 167 with gfile.FastGFile(input_graph, mode) as f: 168 if input_binary: --&gt; 169 input_graph_def.ParseFromString(f.read()) 170 else: 171 text_format.Merge(f.read(), input_graph_def) DecodeError: Error parsing message
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49107649
has title: How to freeze graph in tensorflow 1.5 without using bazel?
accepted answer: http://stackoverflow.com/a/49107649

http://stackoverflow.com/q/49017330
upvote count: 2
tagged with: machine-learning
type: Question
tagged with: rasa-nlu
has title: Rasa core restaurantbot demo example not working as expected
downvote count: 0
favorite count: 0
has body: I am learning rasa-core bot development.For understanding purpose, i have downloaded rasa restaurant bot example from https://github.com/RasaHQ/rasa_core/tree/master/examples and run that example locally as per steps are given in the document.Below are steps python3 -m rasa_nlu.train -c nlu_model_config.json --fixed_model_name current python3 bot.py train-dialogue python3 bot.py run After that it prompt Bot loaded. Type a message and press enter : Me-Hello Bot-if you'd like to modify anything else, please tell me what Me-moderately priced restaurant that serves creative food Bot-if you'd like to modify anything else, please tell me what For almost every message, bot is replying "if you'd like to modify anything else, please tell me what " and this message is picked from training dataset only.I am not typing anything from myself.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87710747
tagged with: python
score: 2
tagged with: bots
answer count: 0

http://stackoverflow.com/comment/85185015
type: Comment
comment on: http://stackoverflow.com/q/49089721
has text: @jhpratt all what I want is a couple of steps. Like where should I start or how? I didn't find anything on the internet. Or couple of steps on how to do that using PyCharm! Thanks!
score: 0
type: QuestionComment

http://stackoverflow.com/a/48978345
has body: Providing you have your JSON stringified: import json def find_name(player_key, data): matches = [player['name'] for player in data if player.get('key') == player_key] return matches[0] if matches else None json_response = '....' data = json.loads(json_response) player_name = find_name(266, data)
score: 0
answers question: http://stackoverflow.com/q/48978272
type: Answer

http://stackoverflow.com/q/49004159
linked to: http://stackoverflow.com/q/251464
possible better answer: http://stackoverflow.com/a/49004202
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/85012888
has answer: http://stackoverflow.com/a/49004369
has answer: http://stackoverflow.com/a/49004178
accepted answer: http://stackoverflow.com/a/49004178
has title: Python: How to print dictionary value?
upvote count: 4
has answer: http://stackoverflow.com/a/49004202
duplicate of: http://stackoverflow.com/q/251464
favorite count: 0
has comment: http://stackoverflow.com/comment/85012719
tagged with: python
tagged with: dictionary
answer count: 4
has body: When I execute the code, it print" function aa in 0x0000... "and all. I want it to print aa,a,b,c,d,. Is it possible? Sorry for the stupid question, thanks a lot. def main(): lunch = { 0: aa, 1: a, 2: b, 3: c, 4: d, } for i in range(len(lunch)): print(lunch[i]) def aa(): print("aa") def a(): pass def b(): pass def c(): pass def d(): pass if __name__ == "__main__": main()
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49004317

http://stackoverflow.com/comment/85035020
type: Comment
comment on: http://stackoverflow.com/q/49014947
score: 2
has text: No you don't understand. Stopping the mainloop will cause your OS to pop up the "this program has become unresponsive" box and stop your whole program. What you want is to use the `threading` module to run your functions simultaneously with the mainloop.
type: QuestionComment

http://stackoverflow.com/comment/85088191
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49041310
has text: What do you mean by ASN ratio? You want to find all the malicious ASNs, and divide that by all the ASNs?

http://stackoverflow.com/q/48990001
favorite count: 0
has title: UserWarning when adding descriptive information to a dataframe that is an attribute
has body: I have multiindex dataframe that is actually an attribute and I am looking to store the index names using the following command: getattr(self, attrdfname).__idxnames__ = getattr(self, attrdfname).index.names It raises the following error: UserWarning: Pandas doesn't allow columns to be created via a new attribute name Found some answers around but it's not very clear how I could avoid the warning. I could obviously call the below command whenever I need it but as I have several dataframes stored as attributes, I would like to store these dataframes 'attributes' to my dataframe. getattr(self, attrdfname).index.names Anyone knows how to work around it?
type: UnansweredQuestion
tagged with: python
tagged with: getattr
answer count: 0
upvote count: 1
type: Question
tagged with: class
linked to: http://stackoverflow.com/q/5626193
tagged with: pandas
downvote count: 0
score: 1

http://stackoverflow.com/comment/84976152
score: 1
has text: Your _any_ code is not the problem, I tried it : `word = ["http://", "https://", "www.", ".com", ".co.uk"]` with `plain_text = 'google.com'`. And the result of `any(word in plain_text for word in word)` was `True`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48985722

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

http://stackoverflow.com/q/49090847
accepted answer: http://stackoverflow.com/a/49090967
upvote count: 1
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/49090913
has answer: http://stackoverflow.com/a/49090913
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85187293
has answer: http://stackoverflow.com/a/49090967
favorite count: 0
has body: So I'm writing this code for my class and I encountered one error that with it which im not sure why it is returning an error. This is the section of code that returns this error: numValues = int(input("Input number of inputs (between 1 and 15): ")) newList = [] def input_nums(): inputs = float(input("Enter a float value: ")) newList.append(inputs) return newList while numValues: input_nums() numValues -= 1 def in_order(): for i in newList: print(i) def rev_order(): for j in newList[::-1]: print(j) def abo_bel_equ(): avg = sum(newList) / numValues ## This line gives the error ## print("The average is: ", avg) for x in range(numValues): above_avg = below_avg = equal_avg = 0 if newList[x] &gt; avg: above_avg += 1 if newList[x] &lt; avg: below_avg += 1 if newList[x] == avg: equal_avg += 1 print("The values of the list in order are: ") in_order() print("The values of the list in reverse order are: ") rev_order() print(abo_bel_equ()) The 'numValues' variable should be whatever integer the user entered, but instead returns 0. Why is this function saying the numValues variable is zero when it should be the users input integer?
has comment: http://stackoverflow.com/comment/85187247
has comment: http://stackoverflow.com/comment/85187406
tagged with: python
has comment: http://stackoverflow.com/comment/85187292
type: AnsweredQuestion
has title: Python - Float Division by Zero?
has comment: http://stackoverflow.com/comment/85187284

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48975046
tags question: http://stackoverflow.com/q/48989331
tags question: http://stackoverflow.com/q/49051017
tags question: http://stackoverflow.com/q/49054950
tags question: http://stackoverflow.com/q/49003144
tags question: http://stackoverflow.com/q/48994545
tags question: http://stackoverflow.com/q/49100427
tags question: http://stackoverflow.com/q/49012844
tags question: http://stackoverflow.com/q/49015994
tags question: http://stackoverflow.com/q/48968097
tags question: http://stackoverflow.com/q/49082196
tags question: http://stackoverflow.com/q/49099308
tags question: http://stackoverflow.com/q/49115507
type: Tag
tags question: http://stackoverflow.com/q/49004046
tags question: http://stackoverflow.com/q/49049972
tags question: http://stackoverflow.com/q/49093286
tags question: http://stackoverflow.com/q/49105821
tags question: http://stackoverflow.com/q/49119011
tags question: http://stackoverflow.com/q/49000591
tags question: http://stackoverflow.com/q/49010361
tags question: http://stackoverflow.com/q/49009264
tags question: http://stackoverflow.com/q/49059258
tags question: http://stackoverflow.com/q/49027382
tags question: http://stackoverflow.com/q/48972307
tags question: http://stackoverflow.com/q/49066463
tags question: http://stackoverflow.com/q/49071849
tags question: http://stackoverflow.com/q/49047386
tags question: http://stackoverflow.com/q/49104836
tags question: http://stackoverflow.com/q/49032297
tags question: http://stackoverflow.com/q/49010871
tags question: http://stackoverflow.com/q/49105056
tags question: http://stackoverflow.com/q/48990153
tags question: http://stackoverflow.com/q/49008632

http://stackoverflow.com/a/49036996
score: 1
has comment: http://stackoverflow.com/comment/85081792
has comment: http://stackoverflow.com/comment/85082168
has comment: http://stackoverflow.com/comment/85082905
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85080517
has comment: http://stackoverflow.com/comment/85079125
has comment: http://stackoverflow.com/comment/85083018
has comment: http://stackoverflow.com/comment/85079338
accepted answer of: http://stackoverflow.com/q/49036714
answers question: http://stackoverflow.com/q/49036714
has body: I modify little bit of your function def expand_onerow(df, ndaysback = 2, nhdaysfwd = 2): new_index = pd.date_range(pd.to_datetime(df.index[0]) - pd.Timedelta(days=ndaysback), pd.to_datetime(df.index[0]) + pd.Timedelta(days=nhdaysfwd), freq='D') newdf = df.reindex(index=new_index, method='nearest') #New df with expanded index return newdf pd.concat([expand_onerow(data.loc[[x],:], ndaysback = 2, nhdaysfwd = 2) for x ,_ in data.iterrows()]) Out[455]: value 2016-05-31 2 2016-06-01 2 2016-06-02 2 2016-06-03 2 2016-06-04 2 2016-06-04 1 2016-06-05 1 2016-06-06 1 2016-06-07 1 2016-06-08 1 More info Basically that one line equal to l=[] for x ,_ in data.iterrows(): l.append(expand_onerow(data.loc[[x],:], ndaysback = 2, nhdaysfwd = 2))# query out each row by using their index(x is the index for each row) and append then into a empty list pd.concat(l)# concat the list to one df at the end
has comment: http://stackoverflow.com/comment/85081729
has comment: http://stackoverflow.com/comment/85082116
has comment: http://stackoverflow.com/comment/85082246
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85081844

http://stackoverflow.com/comment/85184365
type: Comment
comment on: http://stackoverflow.com/a/49089338
score: 1
has text: Yes, I know you did not claim it but it is misleading especially when OP said his/her dataset is large.
type: AnswerComment

http://stackoverflow.com/q/48975787
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-views
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48976454
has body: So I was trying to set up a DeleteView for my Lecture model. Each course from my Course model has its own slug page. And on that page lectures for a course appear. Thing is that I tried to add a delete button for lectures, but it was unsuccessful. Here is what what I did: #courses.html {% regroup lectures by get_lecture_category_display as category_list %} Lectures {% for category in category_list %} {{ category.grouper }} {% for c in category.list %} ............. {{ c.lecture_title }} {{ c.content }} {% for file in c.files.all %} {% if file.files %} download {% endif %} {% endfor %} Delete {% endfor %} {% endfor %} #lecture_confirm_delete.html {% csrf_token %} Are you sure you want to delete? #urls.py path('<slug:slug>/', views.courses, name='courses'), path('<slug:slug>/delete/', views.LectureDelete.as_view(), name='lecture_delete'), #models.py class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', ) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', ) lecture_title = models.CharField(max_length=100, blank=True, null=True) content = models.TextField(blank=False, default=No class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, verbose_name="Course Teacher", related_name='%(class)s_course_teacher') teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True, verbose_name="Seminar Teacher", …
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48976454
favorite count: 0
has title: I can't make Django DeleteView to work

http://stackoverflow.com/comment/85018024
score: 0
type: Comment
type: QuestionComment
has text: @georgexsh could you shouw me a quick example of passing a httplib connection object over a socket georgexsh? That would actually answer the question. I have carved out a solution with ZMQ but there is a lot of work in it...hecne if I could just send the connection that would be better.
comment on: http://stackoverflow.com/q/48974176

http://stackoverflow.com/a/49094332
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49093971
upvote count: 3
answers question: http://stackoverflow.com/q/49093971
type: Answer
has body: As noted by @jonrsharpe, you'd be far better off cleaning the source. That said, if you do not have control over where the extra quote is coming from, you could use (*SKIP)(*FAIL) using the newer regex module and neg. lookarounds like so: "[^"]+":\s*"[^"]+"[,}]\s*(*SKIP)(*FAIL)|(?&lt;![,:])"(?![:,]\s*["}]) See a demo on regex101.com. In Python: import json, regex as re json_str = '''{"id":"9","ctime":"2018-02-13","content":"abcd: "efg.","hots":"103b","date_sms":"2017-11-22"}''' # clean the json rx = re.compile('''"[^"]+":\s*"[^"]+"[,}]\s*(*SKIP)(*FAIL)|(?&lt;![,:])"(?![:,]\s*["}])''') json_str = rx.sub('', json_str) # load it json = json.loads(json_str) print(json['id']) # 9

http://stackoverflow.com/q/49040437
type: UnansweredQuestion
tagged with: python
has title: Using Tkinter in Python Label does not recognize anchor=CENTER
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85086801
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85086257
tagged with: justify
tagged with: label
has answer: http://stackoverflow.com/a/49057634
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49040492
has body: I am new to tkinter and have been using: from tkinter import * but have read this is bad practice. I rewrote a very small bit of code to start using the following: import tkinter as tk However when I run the rest of the code. I get the error: label.place(relx=0.4, rely=0.35, anchor=CENTER) NameError: name 'CENTER' is not defined root = tk.Tk() label = tk.Label(root, text="I am a label widget") label.place(relx=0.4, rely=0.35, anchor=CENTER) button = tk.Button(root, text="I am a button") label.pack() button.pack() root.mainloop() Is this a namespace issue? How can I solve the problem?
favorite count: 0

http://stackoverflow.com/comment/84942400
comment on: http://stackoverflow.com/q/48968374
score: 0
type: Comment
type: QuestionComment
has text: The accepted answer in that question uses a lot of old stuff, like `dict.has_key`. A more modern approach: `import collections; counts = collections.Counter(examList) # get a dict of counts` then, `[x fo x in examList if counts[x] <= 1]`, although, to mimic that approach: `d = {}; for x in myList: d[x] = x in d;`

http://stackoverflow.com/comment/85340362
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49030065
has text: @N.Mittal - What is different in new DataFrame?
score: 0

http://stackoverflow.com/a/49014257
answers question: http://stackoverflow.com/q/49013948
has comment: http://stackoverflow.com/comment/85033477
score: 0
has body: This might help. import pandas as pd p = "PATH_TO.csv" df = pd.read_csv(p, delimiter='(,(?=\S)|:)') #print(df.head(5)) print "-----" print df["name"] print "-----" print df["day"] Output: ----- 0 Chicken Sandwich 1 Pesto Pasta 2 Lettuce, Tomato &amp; Onion Sandwich 3 Lettuce, Tomato &amp; Onion Pita 4 Soup Name: name, dtype: object ----- 0 Wednesday 1 Thursday 2 Friday 3 Friday 4 Saturday Name: day, dtype: object
has comment: http://stackoverflow.com/comment/85033504
type: Answer
has comment: http://stackoverflow.com/comment/85033344

http://stackoverflow.com/a/49054800
score: 0
answers question: http://stackoverflow.com/q/49054681
type: Answer
has body: this is a typical case of async programming for which Python is not very well equipped. Luckily there is the asyncio library. If you install that, you can call your function with async await pattern. That way you will be able to await server results before calling new one. Here is a good explanation: https://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/

sql
tags question: http://stackoverflow.com/q/49042895
tags question: http://stackoverflow.com/q/49007276
tags question: http://stackoverflow.com/q/48968818
tags question: http://stackoverflow.com/q/49064851
tags question: http://stackoverflow.com/q/48997213
tags question: http://stackoverflow.com/q/49077172
tags question: http://stackoverflow.com/q/49120123
tags question: http://stackoverflow.com/q/49034403
tags question: http://stackoverflow.com/q/49051507
tags question: http://stackoverflow.com/q/49119128
tags question: http://stackoverflow.com/q/49102080
tags question: http://stackoverflow.com/q/48965052
tags question: http://stackoverflow.com/q/48966135
tags question: http://stackoverflow.com/q/49038928
tag name: sql
tags question: http://stackoverflow.com/q/49113341
type: Tag
tags question: http://stackoverflow.com/q/49033913
tags question: http://stackoverflow.com/q/49075522
tags question: http://stackoverflow.com/q/49055187
tags question: http://stackoverflow.com/q/49111696
tags question: http://stackoverflow.com/q/49115494
tags question: http://stackoverflow.com/q/49067236
tags question: http://stackoverflow.com/q/49000535
tags question: http://stackoverflow.com/q/48977607
tags question: http://stackoverflow.com/q/49102662
tags question: http://stackoverflow.com/q/49121234
tags question: http://stackoverflow.com/q/49116726
tags question: http://stackoverflow.com/q/49043373
tags question: http://stackoverflow.com/q/49000036
tags question: http://stackoverflow.com/q/49061103
tags question: http://stackoverflow.com/q/49049246

http://stackoverflow.com/q/48978740
answer count: 1
downvote count: 0
tagged with: time-complexity
has comment: http://stackoverflow.com/comment/84964428
favorite count: 0
has title: How is this equation O(n) time complexity?
tagged with: complexity-theory
has answer: http://stackoverflow.com/a/48978842
has body: def myFunction(mylist): n = len(mylist) p = [] sum = 0 for x in mylist: if n &gt; 100: sum = sum + x else: for y in mylist: p.append(y) My thought process was that if the else statement were to be executed, the operations within are O(n) because the number of times through depends on the length of the list. Similarly, I understood the first loop to be O(n) as well thus making the entire worst-case complexity O(n^2). Apparently the correct answer is O(n). Any explanation would be greatly appreciated :)
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/48978842

http://stackoverflow.com/comment/103745145
type: AnswerComment
score: 4
type: Comment
comment on: http://stackoverflow.com/a/49038764
has text: This throws the error `AttributeError: 'Namespace' object has no attribute 'func'` at the line `args.func(args)` if the program is run without any arguments.

pyqt
type: Tag
tags question: http://stackoverflow.com/q/49078002
tags question: http://stackoverflow.com/q/49011491
tags question: http://stackoverflow.com/q/49117383
tags question: http://stackoverflow.com/q/49007811
tags question: http://stackoverflow.com/q/49096416
tags question: http://stackoverflow.com/q/49118384
tags question: http://stackoverflow.com/q/49102471
tags question: http://stackoverflow.com/q/49119611
tags question: http://stackoverflow.com/q/49048136
tags question: http://stackoverflow.com/q/49056306
tags question: http://stackoverflow.com/q/48998470
tags question: http://stackoverflow.com/q/49087539
tags question: http://stackoverflow.com/q/49012141
tags question: http://stackoverflow.com/q/49055790
tags question: http://stackoverflow.com/q/49012565
tags question: http://stackoverflow.com/q/49104588
tags question: http://stackoverflow.com/q/49108148
tags question: http://stackoverflow.com/q/49077083
tags question: http://stackoverflow.com/q/49043570
tags question: http://stackoverflow.com/q/49019527
tags question: http://stackoverflow.com/q/49100389
tags question: http://stackoverflow.com/q/49063687
tags question: http://stackoverflow.com/q/49109326
tags question: http://stackoverflow.com/q/49055933
tags question: http://stackoverflow.com/q/49064463
tags question: http://stackoverflow.com/q/49022442
tags question: http://stackoverflow.com/q/49068100
tags question: http://stackoverflow.com/q/49030036
tags question: http://stackoverflow.com/q/49107722
tags question: http://stackoverflow.com/q/48978106
tags question: http://stackoverflow.com/q/48989949
tags question: http://stackoverflow.com/q/49005963
tags question: http://stackoverflow.com/q/48978661
tags question: http://stackoverflow.com/q/49013010
tags question: http://stackoverflow.com/q/48980344
tags question: http://stackoverflow.com/q/49102849
tags question: http://stackoverflow.com/q/48971448
tags question: http://stackoverflow.com/q/48997764
tags question: http://stackoverflow.com/q/49065371
tag name: pyqt
tags question: http://stackoverflow.com/q/49034697
tags question: http://stackoverflow.com/q/48986753
tags question: http://stackoverflow.com/q/49114502
tags question: http://stackoverflow.com/q/49087309
tags question: http://stackoverflow.com/q/49078973
tags question: http://stackoverflow.com/q/49085620

http://stackoverflow.com/a/49016885
answers question: http://stackoverflow.com/q/49016596
type: AcceptedAnswer
downvote count: 0
has body: I believe your problem is similar to that in AttributeError: 'DiGraph' object has no attribute '_node' The issue there is that the graph being investigated was created in networkx 1.x and then pickled. The graph then has the attributes that a networkx 1.x object has. I believe this happened for you as well. You've now opened it and you're applying tools from networkx 2.x to that graph. But those tools assume that it's a networkx 2.x DiGraph, with all the attributes expected in a 2.x DiGraph. In particular it expects _succ to be defined for a node, which a 1.x DiGraph does not have. So here are two approaches that I believe will work: Short term solution Remove networkx 2.x and replace with networkx 1.11. This is not optimal because networkx 2.x is more powerful. Also code that has been written to work in both 2.x and 1.x (following the migration guide you mentioned) will be less efficient in 1.x (for example there will be places where the 1.x code is using lists and the 2.x code is using generators). Long term solution Convert the 1.x graph into a 2.x graph (I can't test easily as I don't have 1.x on my computer at the moment - If anyone tries this, please leave a comment saying whether this works and whether your network was weighted): #you need commands here to load the 1.x graph G # import networkx as nx #networkx 2.0 H = nx.DiGraph() #if it's a DiGraph() #H=nx.Graph() #if it's a typical networkx Graph(). H.add_nodes_from(G.nodes(data=True)) H.add_edges_from(G.edges(data=True)) The data=True is used to make sure that any edge/node weights are preserved. H is now a networkx 2.x DiGraph, with the edges and nodes having whatever attributes G had. The networkx 2.x commands should work on it. Bonus longer term solution Contact the other researcher and warn him/her that the code example is now out of date.
score: 7
type: Answer
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49016596
has comment: http://stackoverflow.com/comment/85151602

http://stackoverflow.com/q/49096915
has body: As far as I know 1-D arrays are those arrays which either have just 1 column and any number of rows or vice versa. If I run this code: import numpy as np a = np.arange(10).reshape(1,10) b = np.arange(10).reshape(10,1) print(a.ndim, b.ndim) It returns that both are 2-D arrays. Why? I know the computer is working fine. But can you please tell me what is a 1-D array.
tagged with: numpy
answer count: 3
has comment: http://stackoverflow.com/comment/85200701
has comment: http://stackoverflow.com/comment/85199148
upvote count: 1
has title: 1-D arrays in NumPy
tagged with: arrays
favorite count: 0
has answer: http://stackoverflow.com/a/49096962
has comment: http://stackoverflow.com/comment/85204553
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49096973
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/49096981
type: Question

http://stackoverflow.com/comment/84973111
has text: no,it doesn't work, there are some latin words in my file, if i use utf-8,it produce 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
comment on: http://stackoverflow.com/q/48984180
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85038296
comment on: http://stackoverflow.com/a/49016606
type: AnswerComment
has text: I'm fairly new to python. Can you explain a bit more? It *seems* like your solution would need to loop through the dataset twice instead of just once. Yes, this is a toy example. The real data has 10 sets of 7 columns, so I need to add tot1, tot2, . . ., tot10.
score: 0
type: Comment

http://stackoverflow.com/comment/85079500
type: Comment
has text: @JayShankarGupta: This answer is getting flagged as low quality in the review queues; could you add some explanation to go with the code?
type: AnswerComment
comment on: http://stackoverflow.com/a/49036155
score: 0

http://stackoverflow.com/comment/85086408
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49040154
has text: Or put it all in a loop where a successful run breaks the loop and unsuccessful run continues the loop
type: Comment

http://stackoverflow.com/q/49015773
type: AnsweredQuestion
score: 3
tagged with: docker-compose
upvote count: 3
possible better answer: http://stackoverflow.com/a/49016866
has answer: http://stackoverflow.com/a/49045243
has answer: http://stackoverflow.com/a/49016866
type: Question
has comment: http://stackoverflow.com/comment/85087444
answer count: 2
tagged with: django-migrations
accepted answer: http://stackoverflow.com/a/49045243
downvote count: 0
tagged with: docker
has title: Missing Environment Vars in docker python:3 with docker-compose
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85037689
has body: Though my configuration looks good, my python:3 image does not seem to have the expected DJANGO_SECRET_KEY set, at least at the point that the Dockerfile attempts to run migrations $ docker-compose config services: api: build: context: /Users/ben/Projects/falcon/falcon-backend dockerfile: Dockerfile depends_on: - db - redis environment: DJANGO_SECRET_KEY: 'some-secret-that-works-elsewhere' $ $ docker-compose up --build api [...] Step 6/7 : RUN echo `$DJANGO_SECRET_KEY` ---&gt; Running in fbfb569c0191 [...] django.core.exceptions.ImproperlyConfigured: Set the DJANGO_SECRET_KEY env variable ERROR: Service 'api' failed to build: The command '/bin/sh -c python manage.py migrate' returned a non-zero code: 1 however, the final line, CMD python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice does start up as desired, with the necessary env vars set. # Dockerfile -- api FROM python:3 RUN pip3 -q install -r requirements.txt RUN echo `$DJANGO_SECRET_KEY` RUN python manage.py migrate --settings=falcon.settings.dev-microservice # &lt;-- why does this not work CMD python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice Why does the penultimate line of the Dockerfile fail due to an unset environment variable while the final one works as expected?
tagged with: django

http://stackoverflow.com/q/49076072
favorite count: 0
score: 8
has body: My computer environment: Windows 10 : 1709 PyCharm 2017.3.3 *64 The default python environment: D:\softEnvDown\Anaconda2\Scripts\python.exe When I use PyCharm to open the project, here is what happens: querying generate skeletons or something related is shown. When I see these words, I know my computer will crash. When the indexing is finished, PyCharm will launch many Python processes. The picture shows the 47 process, but I can't interrupt them. I tried: rename .PyCharm2017.3 and open PyCharm, choose not import settings (failed) uninstall, install, then import the old settings (failed) uninstall, install, choose not import settings (pass) But I don't want to uninstall install so frequently.
has comment: http://stackoverflow.com/comment/85158982
tagged with: pycharm
upvote count: 8
has comment: http://stackoverflow.com/comment/85265610
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85161350
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85385488
has title: PyCharm starts so many python process and consumes CPU and memory resources
has comment: http://stackoverflow.com/comment/85157987
tagged with: windows
downvote count: 0
tagged with: progress

http://stackoverflow.com/q/49042628
type: AnsweredQuestion
score: 1
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/49047800
accepted answer: http://stackoverflow.com/a/49047800
has comment: http://stackoverflow.com/comment/85092219
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85090468
has comment: http://stackoverflow.com/comment/85091390
upvote count: 1
tagged with: python
has body: I am trying to download a pdf file with below Python function. I was able to open that URL(redirect to another URL) in the browser. But the code is getting 404 error. import requests def downloadFile(url, fileName): r = requests.get(url, allow_redirects=True, stream=True) with open(fileName, "wb") as pdf: for chunk in r.iter_content(chunk_size=1024): if chunk: pdf.write(chunk) downloadFile("http://pubs.vmware.com/vsphere-55/topic/com.vmware.ICbase/PDF/vsphere-esxi-vcenter-server-552-storage-guide.pdf", "vsphere-esxi-vcenter-server-552-storage-guide.pdf")
has title: Error in Downloading live pdf file from URL in python

matplotlib
tags question: http://stackoverflow.com/q/49092490
tags question: http://stackoverflow.com/q/49027061
tags question: http://stackoverflow.com/q/49057890
tags question: http://stackoverflow.com/q/48995278
tags question: http://stackoverflow.com/q/49052142
tags question: http://stackoverflow.com/q/49007536
tags question: http://stackoverflow.com/q/48967026
tags question: http://stackoverflow.com/q/48984312
tags question: http://stackoverflow.com/q/49099765
tags question: http://stackoverflow.com/q/48994844
tags question: http://stackoverflow.com/q/49016760
tags question: http://stackoverflow.com/q/49069712
tags question: http://stackoverflow.com/q/48966920
tags question: http://stackoverflow.com/q/49109466
tags question: http://stackoverflow.com/q/49024654
tags question: http://stackoverflow.com/q/48991374
tags question: http://stackoverflow.com/q/48981870
tags question: http://stackoverflow.com/q/49017002
tags question: http://stackoverflow.com/q/49095323
tags question: http://stackoverflow.com/q/49014052
tags question: http://stackoverflow.com/q/49012323
tags question: http://stackoverflow.com/q/49061906
tags question: http://stackoverflow.com/q/49071229
tags question: http://stackoverflow.com/q/49035079
tags question: http://stackoverflow.com/q/48973471
tags question: http://stackoverflow.com/q/49036539
tags question: http://stackoverflow.com/q/49080911
tags question: http://stackoverflow.com/q/48992153
tags question: http://stackoverflow.com/q/48996575
tags question: http://stackoverflow.com/q/49104677
tags question: http://stackoverflow.com/q/49039581
tags question: http://stackoverflow.com/q/48987662
tags question: http://stackoverflow.com/q/49070420
tag name: matplotlib
tags question: http://stackoverflow.com/q/48969243
tags question: http://stackoverflow.com/q/48978839
tags question: http://stackoverflow.com/q/49043622
tags question: http://stackoverflow.com/q/48995221
tags question: http://stackoverflow.com/q/49006287
tags question: http://stackoverflow.com/q/49087864
tags question: http://stackoverflow.com/q/48975146
tags question: http://stackoverflow.com/q/48999869
tags question: http://stackoverflow.com/q/49098333
tags question: http://stackoverflow.com/q/49012419
tags question: http://stackoverflow.com/q/48999368
tags question: http://stackoverflow.com/q/49042433
tags question: http://stackoverflow.com/q/49096370
tags question: http://stackoverflow.com/q/49093981
tags question: http://stackoverflow.com/q/49083571
tags question: http://stackoverflow.com/q/49000141
tags question: http://stackoverflow.com/q/49016939
tags question: http://stackoverflow.com/q/49019073
tags question: http://stackoverflow.com/q/49074563
tags question: http://stackoverflow.com/q/49054631
tags question: http://stackoverflow.com/q/49034829
tags question: http://stackoverflow.com/q/49093272
tags question: http://stackoverflow.com/q/49051164
tags question: http://stackoverflow.com/q/48966117
tags question: http://stackoverflow.com/q/49078124
tags question: http://stackoverflow.com/q/48990594
tags question: http://stackoverflow.com/q/49071153
tags question: http://stackoverflow.com/q/49020709
tags question: http://stackoverflow.com/q/48986956
tags question: http://stackoverflow.com/q/48990111
tags question: http://stackoverflow.com/q/49078309
tags question: http://stackoverflow.com/q/49021071
tags question: http://stackoverflow.com/q/48982158
tags question: http://stackoverflow.com/q/49054415
tags question: http://stackoverflow.com/q/49100090
tags question: http://stackoverflow.com/q/49100622
tags question: http://stackoverflow.com/q/49101935
tags question: http://stackoverflow.com/q/49059956
tags question: http://stackoverflow.com/q/49084864
tags question: http://stackoverflow.com/q/49057999
tags question: http://stackoverflow.com/q/48989751
tags question: http://stackoverflow.com/q/49101704
tags question: http://stackoverflow.com/q/48998246
tags question: http://stackoverflow.com/q/48970702
tags question: http://stackoverflow.com/q/49006699
tags question: http://stackoverflow.com/q/49097973

http://stackoverflow.com/comment/85115438
has text: yes but in the case of repeat=2, i want it to return l = ['00' '01' '02' '03'...]
type: AnswerComment
comment on: http://stackoverflow.com/a/49055327
score: 0
type: Comment

http://stackoverflow.com/comment/85201333
comment on: http://stackoverflow.com/q/49097182
score: 0
type: Comment
type: QuestionComment
has text: 10 probably ensures that something coming out of a 9-element board is always nonzero.

http://stackoverflow.com/a/49061269
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49061027
accepted answer of: http://stackoverflow.com/q/49061027
type: Answer
has body: You can easily solve your problem by calling the nextTurn directly in the automatic action function: def val1(self): print("Automatic action") self.index.set(self.index.get() +1) self.nextTurn() # call nextTurn after this action So if it was an automatic action, you step into the next row position, and call nextTurn again. However this may become a problem if your row becomes too large because it uses recursion. In that case you will want another approach with the while you mentioned. For this second option you would only need to change nextTurn: def nextTurn(self, *args): i = self.index.get() # while it is an automatic action and it has row values, keep calling val1 while i &lt; len(row) and row[i] == 1: self.val1() # call automatic action i = self.index.get() #update the row position else: if i &gt;= len(row): self.master.destroy() return
upvote count: 1
has comment: http://stackoverflow.com/comment/85151315
has comment: http://stackoverflow.com/comment/85151259

http://stackoverflow.com/q/48980425
has answer: http://stackoverflow.com/a/48980448
tagged with: dataframe
has title: Append values in dataframe column to string
score: 0
tagged with: pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48980461
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84965988
has comment: http://stackoverflow.com/comment/84966001
has answer: http://stackoverflow.com/a/48982453
has body: Suppose I have a dataframe col1 col2 0 1 John Constantine 1 2 ML Engineer 2 3 Colorado I want to append all values in col2 to a list and each row should become a string value in the list. ex output = ['John Constantine', 'ML Engineer' , 'Colorado'] The issue is when I use output = df.col2 The output becomes a dataframe again. Even when I use tolist() I get list of list
type: Question
has answer: http://stackoverflow.com/a/48980460

http://stackoverflow.com/a/48980325
answers question: http://stackoverflow.com/q/48980285
downvote count: 0
has body: Dictionaries are unordered. In fact, if you run your program on a different computer, you might get a different key ordering. This is an intentional feature of the built-in dictionary in python. To understand why, take a look at this stackoverflow question.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/84987762
type: QuestionComment
comment on: http://stackoverflow.com/q/48963808
has text: @AlexAndDraw Just the one instance of the PlotBox on the root widget. I originally had another instance of PlotBox with another widget but not anymore. The widget I add is actually a "FigureCanvasKivyAgg" (from matplotlib garden module) which I don't think can be added through kv, but I used a Button in my example because it's clearer and the end result is the same.
score: 0
type: Comment

http://stackoverflow.com/a/49004020
downvote count: 1
type: Answer
score: 1
upvote count: 2
has body: You can use sum and list: map(str, list(sum(s, ())))
answers question: http://stackoverflow.com/q/49003983

http://stackoverflow.com/comment/85249076
type: Comment
has text: we're using Cordio on the class so what i need to do to correct this program on cordio?
comment on: http://stackoverflow.com/q/49119417
type: QuestionComment
score: 0

python-requests
tags question: http://stackoverflow.com/q/49035081
tags question: http://stackoverflow.com/q/49015037
tags question: http://stackoverflow.com/q/48993596
tags question: http://stackoverflow.com/q/49075355
tags question: http://stackoverflow.com/q/49030413
tags question: http://stackoverflow.com/q/49039241
type: Tag
tags question: http://stackoverflow.com/q/48973612
tags question: http://stackoverflow.com/q/49029473
tags question: http://stackoverflow.com/q/49117640
tags question: http://stackoverflow.com/q/49096283
tags question: http://stackoverflow.com/q/49117411
tags question: http://stackoverflow.com/q/49090882
tags question: http://stackoverflow.com/q/49111500
tags question: http://stackoverflow.com/q/49091315
tags question: http://stackoverflow.com/q/49042628
tags question: http://stackoverflow.com/q/49115192
tags question: http://stackoverflow.com/q/49000162
tags question: http://stackoverflow.com/q/49023861
tags question: http://stackoverflow.com/q/49009287
tags question: http://stackoverflow.com/q/49028418
tags question: http://stackoverflow.com/q/49007907
tags question: http://stackoverflow.com/q/48969332
tags question: http://stackoverflow.com/q/48985154
tags question: http://stackoverflow.com/q/49047497
tags question: http://stackoverflow.com/q/49081632
tags question: http://stackoverflow.com/q/48978724
tags question: http://stackoverflow.com/q/48999187
tags question: http://stackoverflow.com/q/49073571
tags question: http://stackoverflow.com/q/49082081
tags question: http://stackoverflow.com/q/49042064
tags question: http://stackoverflow.com/q/49006224
tags question: http://stackoverflow.com/q/49021566
tags question: http://stackoverflow.com/q/48973021
tags question: http://stackoverflow.com/q/49096813
tags question: http://stackoverflow.com/q/49005177
tags question: http://stackoverflow.com/q/48981784
tags question: http://stackoverflow.com/q/49118854
tags question: http://stackoverflow.com/q/49059182
tags question: http://stackoverflow.com/q/49040347
tags question: http://stackoverflow.com/q/49101649
tags question: http://stackoverflow.com/q/49121286
tags question: http://stackoverflow.com/q/49090561
tags question: http://stackoverflow.com/q/48980029
tags question: http://stackoverflow.com/q/48976562
tags question: http://stackoverflow.com/q/49041914
tags question: http://stackoverflow.com/q/48996494
tags question: http://stackoverflow.com/q/49030627
tags question: http://stackoverflow.com/q/48964310
tags question: http://stackoverflow.com/q/48981383
tags question: http://stackoverflow.com/q/48997007
tag name: python-requests
tags question: http://stackoverflow.com/q/49010813
tags question: http://stackoverflow.com/q/49087040
tags question: http://stackoverflow.com/q/48992650
tags question: http://stackoverflow.com/q/49121365
tags question: http://stackoverflow.com/q/48998664
tags question: http://stackoverflow.com/q/49099313
tags question: http://stackoverflow.com/q/49097915
tags question: http://stackoverflow.com/q/49071377
tags question: http://stackoverflow.com/q/49099392
tags question: http://stackoverflow.com/q/49120390
tags question: http://stackoverflow.com/q/49027471

http://stackoverflow.com/comment/84942715
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48968551
score: 0
has text: What's the point of `try: open(...) except: pass` Firstly, that is a seriously janky way of clearing a file, but why do it in the first place if you go on to open the same exact file anyway?

http://stackoverflow.com/comment/85060739
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Starting a process in Java?](https://stackoverflow.com/questions/3774432/starting-a-process-in-java)
comment on: http://stackoverflow.com/q/49028221

http://stackoverflow.com/comment/85104012
has text: `line.rsplit(1)` would be better there, as it would allow species names to have spaces.
comment on: http://stackoverflow.com/a/49049565
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85186916
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49089266
score: 0
has text: @Ravi, do you have repeated datetime values in your index?

http://stackoverflow.com/a/49118886
upvote count: 2
has comment: http://stackoverflow.com/comment/138861631
answers question: http://stackoverflow.com/q/49117806
downvote count: 0
type: Answer
score: 2
has body: As a work around a simple caching of the result of colors() works for the session scope: @pytest.fixture(scope='session') def colors(): try: return colors._res except AttributeError: # Expensive operation print() print('expensive') colors._res = ['red', 'yellow', 'blue'] return colors._res @pytest.mark.parametrize('color', colors()) def test_colors(color): assert color != 'mauve' def test_colors_list(colors): assert len(colors) == 3 While the function colors() is called twice in it, the expensive calculation is done only once for all tests: $ pytest -sv test_colors.py ================================================= test session starts ================================================== platform darwin -- Python 3.6.4, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /Users/mike/miniconda3/envs/py36/bin/python cachedir: .cache rootdir: /Users/mike/tmp, inifile: plugins: click-0.1, cov-2.4.0, mock-1.6.0, pylint-0.7.1, xdist-1.15.0, xonsh-0.5.8 collecting 0 items expensive collected 4 items test_colors.py::test_colors[red] PASSED test_colors.py::test_colors[yellow] PASSED test_colors.py::test_colors[blue] PASSED test_colors.py::test_colors_list PASSED

http://stackoverflow.com/q/49059108
has body: I'm creating a simple addition and subtraction game in Tkinter. import random import Tkinter as tkinter window = tkinter.Tk() window.geometry("250x150") window.title("Maths Game Login") window.iconbitmap("mathsgame_1_16x16.icns") window.configure(background="firebrick") username = "" password = "" def login(): if entusername.get() == username and entpassword.get() == password: game_window = tkinter.Toplevel(window) game_window.title("Maths Game") game_window.configure(background="firebrick") game_window.geometry("500x250") number1 = random.randint(0, 9) number2 = random.randint(0, 9) addorsubtract = random.randint(1,2) lblno1 = tkinter.Label(game_window, text="{0}".format(number1), bg="firebrick", fg="yellow", font=("Courier", 100)) lblno1.place(x=50, y=60) lblno2 = tkinter.Label(game_window, text="{0}".format(number2), bg="firebrick", fg="yellow", font=("Courier", 100)) lblno2.place(x=200, y=60) if addorsubtract == 1: additionsign = tkinter.Label(game_window, text="+", bg="firebrick", fg="yellow", font=("Courier", 100)) additionsign.place(x=125, y=60) elif addorsubtract == 2: subtractsign = tkinter.Label(game_window, text="-", bg="firebrick", fg="yellow", font=("Courier", 100)) subtractsign.place(x=125, y=60) equalssign = tkinter.Label(game_window, text="=", bg="firebrick", fg="yellow", font=("Courier", 100)) equalssign.place(x=275, y=60) entanswer = tkinter.Entry(game_window, bg="yellow", fg="firebrick", width=2, font=("Courier", 100)) entanswer.place(x=350, y=60) if addorsubtract == 1: global sum1 sum1 = int(number1) + int(number2) print("{0}".format(sum1)) elif addorsubtract == 2: global sum2 sum2 = int(number1) - int(number2) print("{0}".format(sum2)) def submitanswer(): if int(entanswer.get()) == int(sum2) or int(entanswer.get()) == int(sum1): print("Correct") else print("Try Again") submitbtn = tkinter.Button(game_window, text="Check Answer", highlightbackground="firebrick", cursor="gumby", command=submitanswer) submitbtn.place(x=360, y=200) else: exit() lbl …
favorite count: 0
has title: Tkinter - NameError: Name Is Not Defined
tagged with: python
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/85123296
upvote count: 2
has comment: http://stackoverflow.com/comment/85123368
score: 0
type: UnansweredQuestion
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/85124052

http://stackoverflow.com/q/49025765
accepted answer: http://stackoverflow.com/a/49026203
linked to: http://stackoverflow.com/q/48715552
has comment: http://stackoverflow.com/comment/85056536
answer count: 6
upvote count: 3
has comment: http://stackoverflow.com/comment/85056880
has answer: http://stackoverflow.com/a/49026458
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49026267
has answer: http://stackoverflow.com/a/49026267
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85056507
has answer: http://stackoverflow.com/a/49026087
type: AnsweredQuestion
score: 3
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/49025850
has title: python check to see if dictionary is in a list
type: Question
has answer: http://stackoverflow.com/a/49026322
has comment: http://stackoverflow.com/comment/85056969
has body: I have a list called clients_list full of dictionaries such as this: clients_list = [ {'John Guy': [28, '03171992', 'Student']}, {'Bobby Jones': [22, '02181982', 'Student']}, {'Claire Eubanks': [18, '06291998', 'Student']}, ] How would I check to see if someone was in this list using the input answer? I have tried the code elif answer in clients_list: print(f'{answer} is in our database.') But it does not seem to work properly.
has answer: http://stackoverflow.com/a/49026203

http://stackoverflow.com/q/49032009
has comment: http://stackoverflow.com/comment/85068641
score: 0
has comment: http://stackoverflow.com/comment/85069193
has answer: http://stackoverflow.com/a/49032054
tagged with: pandas
answer count: 1
has body: I am using python (jupyter notebook) for some analysis. I would like to sort my values in my panda data frame by the function sort_values(). First it looked like it was working correctly, however it is only working for sorting digits with 2 characters (see figure). What could I do to sort the values correctly for countries > 99?
has title: Sort values in python
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49032054
type: AnsweredQuestion
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85068692
type: Question
tagged with: sorting

http://stackoverflow.com/q/48981746
tagged with: javascript
tagged with: jquery
has comment: http://stackoverflow.com/comment/84968670
has comment: http://stackoverflow.com/comment/84968560
tagged with: http://stackoverflow.com/tag/html
has title: Using ajax to pass post data to python
has comment: http://stackoverflow.com/comment/84968532
has comment: http://stackoverflow.com/comment/84969494
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84968718
tagged with: python
has body: HTML {% if todo_array %} &lt;ul&gt; {% for TodoList in todo_array %} &lt;li class="listItems" name="listItem" id="item{{ forloop.counter }}" onClick = "myFunction({{ forloop.counter }})" &gt; {{ TodoList.todo_text }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} &lt;p&gt; Add some Todo's !! &lt;/p&gt; {% endif %} Javascript var csrftoken = getCookie('csrftoken'); function myFunction(value){ console.log("clicked") $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") }, type:"POST", {% load static %} url:"{%url 'home'%}", data: { id : value }, success: function(data) { console.log('success',data); }, }); } Python def home(request): if request.method == 'POST': todelete = request.POST.get('id') print(todelete) return render(request, 'home/mainList.html', context) I'm trying to send the ID from html using javascript into python by making an ajax call. However the post data isn't working. How can I fix my code? Edit. Getting a server internal error 500 now. Urls.py urlpatterns = [ path('', views.home, name='home'), path('logout', views.logout_attempt, name='logout') ]
has comment: http://stackoverflow.com/comment/84968578
has comment: http://stackoverflow.com/comment/84968637
tagged with: post
type: Question
has comment: http://stackoverflow.com/comment/84968606
has comment: http://stackoverflow.com/comment/84968860

http://stackoverflow.com/a/71817138
score: 4
upvote count: 4
has body: Just use the %%time cell magic instead (or the %time line magic) %time var = 5 * 6 # CPU times: user 2 µs, sys: 0 ns, total: 2 µs # Wall time: 3.81 µs var # Out: 30 I guess the reason why variables are not remembered by %timeit is that it's a series of experiments--when experimenting one should always assume that something might go wrong, so it's not clear what the valid variable instantiation should be. To see what kind of repeated runs %%timeit performs, check also my other answer.
answers question: http://stackoverflow.com/q/48972470
downvote count: 0
type: Answer

http://stackoverflow.com/q/48976415
downvote count: 0
linked to: http://stackoverflow.com/q/41588034
has comment: http://stackoverflow.com/comment/84957836
favorite count: 0
has answer: http://stackoverflow.com/a/48976591
accepted answer: http://stackoverflow.com/a/48976915
tagged with: pandas
has answer: http://stackoverflow.com/a/71243378
tagged with: python
possible better answer: http://stackoverflow.com/a/48976591
type: AnsweredQuestion
has title: Faster Python implementation from bag of words data frame to array
upvote count: 3
type: Question
score: 3
tagged with: performance
has answer: http://stackoverflow.com/a/48976915
has body: I have a pandas data frame that defines my bag of word indices and counts like this. id word_count word_idx 15213 1 1192 15213 1 1215 15213 1 1674 15213 1 80 15213 1 179 307 2 103 307 1 80 307 3 1976 I need a fast way to return a matrix of bag of words array. Let's say my vocabulary length is 2000: VOCAB_LEN = 2000 My current solution is TOO SLOW. But here it is: Function def to_bow_array(word_idx_list, word_count_list): zeros = np.zeros(VOCAB_LEN, dtype = np.uint8) zeros[np.array(word_idx_list)] = np.array(word_count_list) return zeros Groupby and apply function df.groupby('id').apply(lambda row: to_bow_array(list(row['word_idx']), list(row['word_count']))) This will return my expected output. For every row, something like array([0, 0, 1, ..., 0, 2, 0], dtype=uint8) I need a faster implementation. I know that apply should be avoided for fast implementations. How can I achieve this? Thanks
tagged with: apply
tagged with: numpy
answer count: 3

http://stackoverflow.com/comment/84965814
comment on: http://stackoverflow.com/q/48980348
score: 0
type: Comment
type: QuestionComment
has text: Is this using pandas?

http://stackoverflow.com/q/49039750
upvote count: 36
has comment: http://stackoverflow.com/comment/126796176
downvote count: 0
possible better answer: http://stackoverflow.com/a/78571670
score: 36
has answer: http://stackoverflow.com/a/78571670
answer count: 3
has answer: http://stackoverflow.com/a/69447517
tagged with: distributed-computing
tagged with: jupyter-notebook
favorite count: 0
has answer: http://stackoverflow.com/a/49039812
tagged with: dask
linked to: http://stackoverflow.com/q/44483950
has body: I would like to see a progress bar on Jupyter notebook while I'm running a compute task using Dask, I'm counting all values of id column from a large csv file +4GB, so any ideas? import dask.dataframe as dd df = dd.read_csv('data/train.csv') df.id.count().compute()
tagged with: python
has comment: http://stackoverflow.com/comment/85084840
type: AnsweredQuestion
has title: How to see progress of Dask compute task?
accepted answer: http://stackoverflow.com/a/49039812
type: Question

http://stackoverflow.com/q/48963808
has answer: http://stackoverflow.com/a/48969204
answer count: 3
has answer: http://stackoverflow.com/a/48965095
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84943742
has answer: http://stackoverflow.com/a/48965049
has comment: http://stackoverflow.com/comment/84987762
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: kivy-language
score: 1
upvote count: 1
type: Question
has body: Trying to follow this guide : https://kivy.org/docs/guide/lang.html#accessing-widgets-defined-inside-kv-lang-in-your-python-code I am attempting to access a widget using an id definition. This works well inside the root widget but it doesn't seem to work outside of it. As an example here's a bare minimum code representing my issue : GUI.kv file : &lt;PlotBox@BoxLayout&gt;: graph2:graph2_id BoxLayout: id:graph2_id &lt;RootWidget@BoxLayout&gt;: graph:graph_id BoxLayout: id:graph_id PlotBox: python file : #kivy imports from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.properties import ObjectProperty class PlotBox(BoxLayout): graph2 = ObjectProperty(None) def __init__(self,**kwargs): super(PlotBox,self).__init__(**kwargs) self.graph2.add_widget(Button(text="This doesn't work")) class RootWidget(BoxLayout): graph = ObjectProperty(None) def __init__(self,**kwargs): super(RootWidget,self).__init__(**kwargs) self.graph.add_widget(Button(text='This works')) class GUIApp(App): def build(self): self.root = RootWidget() return self.root if __name__ == "__main__": GUIApp().run() I get the error : AttributeError: 'NoneType' object has no attribute 'add_widget' On the RootWidget, it works even if I don't use graph = ObjectProperty(None). On my other widget, it's like the id doesn't get created.
accepted answer: http://stackoverflow.com/a/48965049
has title: Binding Kivy ObjectProperty to a child widget doesn't seem to work outside of root widget
possible better answer: http://stackoverflow.com/a/48965095

http://stackoverflow.com/a/49076485
answers question: http://stackoverflow.com/q/49059042
type: Answer
accepted answer of: http://stackoverflow.com/q/49059042
score: 3
upvote count: 3
has body: OK, figured it out. folium can't parse object names with -s in them. Probably a javascript translation thing? fun test works m = folium.Map([0, 0], zoom_start=7) folium.TopoJson( { "type":"Topology", "transform":{ "scale": [1,1], "translate": [0,0] }, "objects":{ "two_squares":{ "type": "GeometryCollection", "geometries":[ {"type": "Polygon", "arcs":[[0,1]],"properties": {"name": "Left_Polygon" }}, {"type": "Polygon", "arcs":[[2,-1]],"properties": {"name": "Right_Polygon" }} ] } }, "arcs": [ [[1,2],[0,-2]], [[1,0],[-1,0],[0,2],[1,0]], [[1,2],[1,0],[0,-2],[-1,0]] ] }, object_path='objects.two_squares' ).add_to(m) m does not work m = folium.Map([0, 0], zoom_start=7) folium.TopoJson( { "type":"Topology", "transform":{ "scale": [1,1], "translate": [0,0] }, "objects":{ "two-squares":{ "type": "GeometryCollection", "geometries":[ {"type": "Polygon", "arcs":[[0,1]],"properties": {"name": "Left_Polygon" }}, {"type": "Polygon", "arcs":[[2,-1]],"properties": {"name": "Right_Polygon" }} ] } }, "arcs": [ [[1,2],[0,-2]], [[1,0],[-1,0],[0,2],[1,0]], [[1,2],[1,0],[0,-2],[-1,0]] ] }, object_path='objects.two-squares' ).add_to(m) m
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84990819
score: 0
type: Comment
type: QuestionComment
has text: I'm using find!
comment on: http://stackoverflow.com/q/48987006

http://stackoverflow.com/comment/84951379
type: AnswerComment
comment on: http://stackoverflow.com/a/48973023
type: Comment
has text: Hi Jean, I am afraid I couldnt understand your last comment, can you tell me what changes do I need to do in my code so that my main python program is launched in 3 different cores with those individual arguments independently?
score: 0

http://stackoverflow.com/comment/85124378
has text: Is there a more general solution, to handle something like `today's y = 2*(previous day's y) + (today's x)`. Updated the question.
comment on: http://stackoverflow.com/a/49059644
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48969397
has comment: http://stackoverflow.com/comment/84946135
tagged with: python
has title: ADODB unable to store DATETIME value with sub-second precision
has comment: http://stackoverflow.com/comment/84951964
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84965649
downvote count: 0
linked to: http://stackoverflow.com/q/9920448
has comment: http://stackoverflow.com/comment/84944494
type: Question
linked to: http://stackoverflow.com/q/45511013
score: 3
has comment: http://stackoverflow.com/comment/84951342
has comment: http://stackoverflow.com/comment/84945842
accepted answer: http://stackoverflow.com/a/66738080
tagged with: adodb
upvote count: 3
tagged with: sql-server
has body: According to the Microsoft documentation for the DATETIME column type, values of that type can store "accuracy rounded to increments of .000, .003, or .007 seconds." According to their documentation for the data types used by ADODB, the adDBTimeStamp (code 135), which ADODB uses for DATETIME column parameters, "indicates a date/time stamp (yyyymmddhhmmss plus a fraction in billionths)." However, all attempts (tested using multiple versions of SQL Server, and both the SQLOLEDB provider and the newer SQLNCLI11 provider) fail when a parameter is passed with sub-second precision. Here's a repro case demonstrating the failure: import win32com.client # Connect to the database conn_string = "Provider=...." # sensitive information redacted conn = win32com.client.Dispatch("ADODB.Connection") conn.Open(conn_string) # Create the temporary test table cmd = win32com.client.Dispatch("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = "CREATE TABLE #t (dt DATETIME NOT NULL)" cmd.CommandType = 1 # adCmdText cmd.Execute() # Insert a row into the table (with whole second precision) cmd = win32com.client.Dispatch("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = "INSERT INTO #t VALUES (?)" cmd.CommandType = 1 # adCmdText params = cmd.Parameters param = params.Item(0) print("param type is {:d}".format(param.Type)) # 135 (adDBTimeStamp) param.Value = "2018-01-01 12:34:56" cmd.Execute() # this invocation succeeds # Show the result cmd = win32com.client.Dispatch("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = "SELECT * FROM #t" cmd.CommandType = 1 # adCmdText rs, rowcount = cmd.Execute() data = rs.GetRows(1) print(data[0][0]) # displays the datetime value stored above # Insert a second row into the table (with sub-second precision) cmd = win32com.client.Dispatch("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = "INSERT INTO #t VALUES (?)" cmd.CommandType = 1 # adCmdText params = cmd.Parameters param = params.Item(0) print("param type is …
answer count: 1
linked to: http://stackoverflow.com/q/38798174
has answer: http://stackoverflow.com/a/66738080
favorite count: 0

machine-learning
tags question: http://stackoverflow.com/q/48975402
tags question: http://stackoverflow.com/q/48969217
tags question: http://stackoverflow.com/q/49006083
tags question: http://stackoverflow.com/q/49084636
tags question: http://stackoverflow.com/q/49027781
tags question: http://stackoverflow.com/q/49051610
tags question: http://stackoverflow.com/q/49016933
tags question: http://stackoverflow.com/q/49112031
tags question: http://stackoverflow.com/q/48997385
tags question: http://stackoverflow.com/q/49101544
tags question: http://stackoverflow.com/q/49024226
tags question: http://stackoverflow.com/q/49095096
tags question: http://stackoverflow.com/q/49006722
tags question: http://stackoverflow.com/q/48966101
tags question: http://stackoverflow.com/q/48993004
tags question: http://stackoverflow.com/q/48977277
tags question: http://stackoverflow.com/q/49093292
tags question: http://stackoverflow.com/q/49052420
tags question: http://stackoverflow.com/q/48981687
tags question: http://stackoverflow.com/q/49082085
tags question: http://stackoverflow.com/q/49006013
tags question: http://stackoverflow.com/q/49067869
tags question: http://stackoverflow.com/q/49004835
tags question: http://stackoverflow.com/q/49042221
tags question: http://stackoverflow.com/q/49068574
tags question: http://stackoverflow.com/q/48966446
tags question: http://stackoverflow.com/q/49029142
tags question: http://stackoverflow.com/q/49083198
tags question: http://stackoverflow.com/q/49008074
tags question: http://stackoverflow.com/q/49018652
tags question: http://stackoverflow.com/q/49110865
tags question: http://stackoverflow.com/q/48977513
tag name: machine-learning
tags question: http://stackoverflow.com/q/49100615
tags question: http://stackoverflow.com/q/49079122
tags question: http://stackoverflow.com/q/48971852
tags question: http://stackoverflow.com/q/49020819
tags question: http://stackoverflow.com/q/49094854
tags question: http://stackoverflow.com/q/49025680
tags question: http://stackoverflow.com/q/49008320
tags question: http://stackoverflow.com/q/49001885
tags question: http://stackoverflow.com/q/48993412
tags question: http://stackoverflow.com/q/49066695
tags question: http://stackoverflow.com/q/49103737
tags question: http://stackoverflow.com/q/49093704
tags question: http://stackoverflow.com/q/49098779
tags question: http://stackoverflow.com/q/48997718
tags question: http://stackoverflow.com/q/49048622
tags question: http://stackoverflow.com/q/48978609
tags question: http://stackoverflow.com/q/49118388
tags question: http://stackoverflow.com/q/48998659
tags question: http://stackoverflow.com/q/48986606
type: Tag
tags question: http://stackoverflow.com/q/49017084
tags question: http://stackoverflow.com/q/49078266
tags question: http://stackoverflow.com/q/48996429
tags question: http://stackoverflow.com/q/49099687
tags question: http://stackoverflow.com/q/49115416
tags question: http://stackoverflow.com/q/49007163
tags question: http://stackoverflow.com/q/49097669
tags question: http://stackoverflow.com/q/49033055
tags question: http://stackoverflow.com/q/49075305
tags question: http://stackoverflow.com/q/49035107
tags question: http://stackoverflow.com/q/49004303
tags question: http://stackoverflow.com/q/49093207
tags question: http://stackoverflow.com/q/48988182
tags question: http://stackoverflow.com/q/48975461
tags question: http://stackoverflow.com/q/49104624
tags question: http://stackoverflow.com/q/49076125
tags question: http://stackoverflow.com/q/49028416
tags question: http://stackoverflow.com/q/48979658
tags question: http://stackoverflow.com/q/49092527
tags question: http://stackoverflow.com/q/49100959
tags question: http://stackoverflow.com/q/49081195
tags question: http://stackoverflow.com/q/49088365
tags question: http://stackoverflow.com/q/49011306
tags question: http://stackoverflow.com/q/49050974
tags question: http://stackoverflow.com/q/49098155
tags question: http://stackoverflow.com/q/49016723
tags question: http://stackoverflow.com/q/48990935

http://stackoverflow.com/comment/85073468
comment on: http://stackoverflow.com/q/49034291
has text: This code doesn't make sense. Can be simplified to `sum = a * b`
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/49095101
type: Question
tagged with: python
tagged with: abaqus
answer count: 2
has answer: http://stackoverflow.com/a/49106394
upvote count: 1
has answer: http://stackoverflow.com/a/49095193
possible better answer: http://stackoverflow.com/a/49095193
has body: I'm new to python scripting in Abaqus. I'm trying to make sense of the documentation but I don't get it. So far I found the following documentation: This abaqus scripting user guide: http://abaqus.software.polimi.it/v6.13/books/cmd/default.htm?startat=pt02ch06s01.html This abaqus scripting reference document: http://abaqus.software.polimi.it/v6.13/books/ker/default.htm Now let's say that I want to know more about the OdbMeshElementArray class. How do I do this? If I use the search function on the site than it just gives 0 hits. If I download the pdf of the reference guide and I use ctrl+F then I do get hits, but there's no direct way to go to the page explaining specifically more about this class. E.g. I get a lot of hits of this search term in which I'm not interested. I just want to know the attributes and methods of this class. Any advice?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49106394
downvote count: 0
score: 1
favorite count: 0
has title: Abaqus python scripting documentation, how to work with it?

http://stackoverflow.com/q/49111583
has title: How to fix CERTIFICATE_VERIFY_FAILED error in websocket-client Python module?
favorite count: 0
has body: Code: import websocket ws = websocket.WebSocket() ws.connect('wss://stream2.binance.com:9443/ws/!miniTicker@arr@3000ms') record = ws.recv() print(record) I was trying to get realtime data from Binance Websocket API. while trying to fetch data with this sample url wss://stream.binance.com:9443/ws/bnbbtc@depth I am getting this error which says the SSL Verification is failed. ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) Traceback : pastebin.com/RiHn025Z What I've already tried: So I found this question on SO How to create Python secure websocket client request? and followed the steps with this code ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) ws.connect("wss://stream2.binance.com:9443/ws/!miniTicker@arr@3000ms") But then a NameError occured: NameError: name 'ssl' is not defined I tried to add an Exception (which is ridiculous but still...) which resulted in SyntaxError. Other Scopes I tried with different websocket API which uses wss:// but worked just fine in the first code itself. wss://ws.blockchain.info/inv {"op":"ping"} Conditions: I tried an Echo Test on websockets.org and the wss url is fully functional. Any help will be appreciated. there are other modules available specifically for binance but I'd like to have the raw data so I am using this api. Thanks for reading my Question. GitHub URL for websocket-client : https://github.com/websocket-client/websocket-client
has answer: http://stackoverflow.com/a/49834998
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85228644
tagged with: python
tagged with: client
has answer: http://stackoverflow.com/a/52097983
downvote count: 0
has comment: http://stackoverflow.com/comment/85228516
score: 7
type: Question
has answer: http://stackoverflow.com/a/75469529
tagged with: ssl
has comment: http://stackoverflow.com/comment/85228627
has comment: http://stackoverflow.com/comment/85228709
upvote count: 7
tagged with: websocket
has answer: http://stackoverflow.com/a/49112178
has answer: http://stackoverflow.com/a/61332272
linked to: http://stackoverflow.com/q/46852066

http://stackoverflow.com/a/52441960
has comment: http://stackoverflow.com/comment/98936941
upvote count: 5
answers question: http://stackoverflow.com/q/48969145
has body: You have already solved the problem, but I found the other way to do this. import socket socket.setdefaulttimeout(150) If call discovery.build without http, http client is instantiated by build_http in build method. https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http-pysrc.html#build_http As you can see here, build_http create a http client instance with timeout if it is set before creating http client. So all you have to do is setting this value by socket.setdefaulttimeout :)
score: 4
type: Answer
downvote count: 1

http://stackoverflow.com/q/49037391
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/12141150
has comment: http://stackoverflow.com/comment/85080612
has comment: http://stackoverflow.com/comment/85198830
score: 12
has comment: http://stackoverflow.com/comment/85244843
answer count: 3
has comment: http://stackoverflow.com/comment/85082319
upvote count: 12
tagged with: algorithm
has answer: http://stackoverflow.com/a/49039949
has title: Sort a list of two-sided items based on the similarity of consecutive items
tagged with: sorting
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22342854
has comment: http://stackoverflow.com/comment/85086228
has answer: http://stackoverflow.com/a/49903556
has answer: http://stackoverflow.com/a/49038613
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85198763
has body: I'm looking for some kind of "Domino sort" algorithm that sorts a list of two-sided items based on the similarity of "tangent" sides of subsequent items. Suppose the following list where items are represented by 2-tuples: &gt;&gt;&gt; items [(0.72, 0.12), (0.11, 0.67), (0.74, 0.65), (0.32, 0.52), (0.82, 0.43), (0.94, 0.64), (0.39, 0.95), (0.01, 0.72), (0.49, 0.41), (0.27, 0.60)] The goal is to sort that list such that the sum of squared differences of the tangent ends of each two subsequent items (the loss) is minimal: &gt;&gt;&gt; loss = sum( ... (items[i][1] - items[i+1][0])**2 ... for i in range(len(items)-1) ... ) For the above example this can be computed by just working through all possible permutations but for lists with more items this becomes quickly unfeasible (O(n!)). The approach of selecting the best match step-by-step as sketched here def compute_loss(items): return sum((items[i][1] - items[i+1][0])**2 for i in range(len(items)-1)) def domino_sort(items): best_attempt = items best_score = compute_loss(best_attempt) for i in range(len(items)): copy = [x for x in items] attempt = [copy.pop(i)] for j in range(len(copy)): copy = sorted(copy, key=lambda x: abs(x[0] - attempt[-1][1])) attempt.append(copy.pop(0)) score = compute_loss(attempt) if score &lt; best_score: best_attempt = attempt best_score = score return best_attempt, best_score gives the following result with a loss of 0.1381: [(0.01, 0.72), (0.72, 0.12), (0.11, 0.67), (0.74, 0.65), (0.49, 0.41), (0.39, 0.95), (0.94, 0.64), (0.82, 0.43), (0.32, 0.52), (0.27, 0.6)] This is however not the best solution which would be [(0.01, 0.72), (0.82, 0.43), (0.27, 0.6), (0.49, 0.41), (0.32, 0.52), (0.39, 0.95), (0.94, 0.64), (0.72, 0.12), (0.11, 0.67), (0.74, 0.65)] with a loss of 0.0842. Obviously the above algorithm performs well for the first few items however the differences for the last ones grow so large that they dominate the loss. Is there any algorithm that can perform this kind of sort in acceptable…

http://stackoverflow.com/a/48985994
score: 1
accepted answer of: http://stackoverflow.com/q/48984869
has comment: http://stackoverflow.com/comment/84977053
has body: Try this piece of code: import pandas as pd df = pd.read_csv("testing.csv", sep=',', encoding="utf-8") df.fillna('', inplace=True) def clear_data(x): fname = x['First Name'] lname = x['Last Name'].strip() url = x['Profile URL'] if not lname: fname = fname.split(' ')[0] url_name = url.split('/')[-1].split('-') if len(url_name) &gt; 1: lname = url_name[-2].title() else: index_of_fname = url_name[0].lower().find(fname.lower()) if index_of_fname != -1: index_of_fname += len(fname) lname = url_name[0][index_of_fname:].title() x['First Name'] = fname x['Last Name'] = lname else: lname = lname.split('-')[0].strip() x['Last Name'] = lname return x df.apply(clear_data, axis=1) print(df)
upvote count: 1
has comment: http://stackoverflow.com/comment/84976929
has comment: http://stackoverflow.com/comment/84977591
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84977793
type: Answer
has comment: http://stackoverflow.com/comment/84977493
answers question: http://stackoverflow.com/q/48984869

http://stackoverflow.com/a/49020421
has comment: http://stackoverflow.com/comment/85046888
has comment: http://stackoverflow.com/comment/85047099
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85047339
has comment: http://stackoverflow.com/comment/85046256
score: 1
answers question: http://stackoverflow.com/q/49020321
has body: The table relationships look ok, except that backref='Users' is an odd choice of name, as this will add a "Users" property to the FileUploadPath, which doesn't follow the naming convention of the rest of its properties. I would have expected this to be backref='user' instead. Now, the main problem is that you haven't specified a FileUploadPath that newuser should be associated with, so it hasn't inserted any entry in FileUploadPath that references the ID of newuser. Or maybe you have inserted a new FileUploadPath that you intended to be linked to newuser, though you haven't shown that code in your example. In any case, it doesn't know which FileUploadPath to associate with which User, and it doesn't automatically create a new FileUploadPath for each User, and so when you only create a new User, or if you individually create new User and FileUploadPath but don't link them, you don't end up with a FileUploadPath associated with your new User. So, what you need to do is to link a FileUploadPath to newuser either by adding a child=newFileUploadPath parameter (where newFileUploadPath is the already constructed FileUploadPath object) when you call the User constructor, or by individually constructing and adding the User and FileUploadPath objects, and setting newuser.child = newFileUploadPath, or newFileUploadPath.user = newuser. (Note that newFileUploadPath.user assumes my suggested backref='user' change.) Edit: Here's an MVCE that shows how to add a file upload for a user. But the file upload does not exist when the user is initially created, which should be the expected behaviour. You definitely should not have an entry in FileUploadPath that contains all empty strings. Also, if you plan to allow up to 4 uploads per user, you need to make it a many-to-one relationship instead, by getting rid of that uselist=False and treating Users.child as a list, and maybe also renaming it to children or uploads. (Note, this example uses plain SQLAlchemy rather than Flask-SQLAlchemy,…
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49020321
has comment: http://stackoverflow.com/comment/85047659

http://stackoverflow.com/comment/85058879
has text: yes, it's the same if you leave it as a tuple
score: 0
comment on: http://stackoverflow.com/q/49027108
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85138012
type: Comment
has text: The answer is: It is not possible without modifying the source of ``libconf`` the information is getting lost by design.
comment on: http://stackoverflow.com/a/49066101
type: AnswerComment
score: 0

http://stackoverflow.com/q/49109363
tagged with: python
has title: Django: Permission per instance
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49109613
accepted answer: http://stackoverflow.com/a/49109613
has comment: http://stackoverflow.com/comment/85223799
has body: At the moment, I plan to write a website where users can write blog posts. I haven't started with the implementation yet because I am new to Django and want to get an overview in how I should solve problems and structure the overall project. My problem: The users aren't allowed to use Django's admin page (/admin). The users should only interact with the website that I write. The users at my website will be able to create blog posts. Now, I have to ensure that only the creator of the blog post should be able to edit/delete his own post. All the other users should only be able to read this post. So, I need permissions per user/instance. I know that there are some full-blown permission-systems like django-guardian, but I would like to prefer to solve it on my own. Also to better understand the Django framework. I`ve already read the Django docs, but I am overwhelmed. I guess this is such a common problem that I there is also a common solution to this problem. Can someone help me where I should look at, where to start? My idea so far (please comment): In create a page like blog/5/edit that is only accessible for the user that created the blog post number 5. This should be easily within the view function, right? On this page there is a Form to edit the blog post. Something like this for the view (pseudo-code!) if request.user != blogpost.user: redirect/error page else: show Form/process Form Is this secure? I haven't found such a solution so far while searching the internet. However, spontaneously and as a Django beginner, I think this could already by enough.
type: Question
has comment: http://stackoverflow.com/comment/85223835
upvote count: 2
linked to: http://stackoverflow.com/q/6069070
answer count: 1
favorite count: 0
tagged with: django

http://stackoverflow.com/comment/84985112
type: AnswerComment
comment on: http://stackoverflow.com/a/48989568
type: Comment
has text: @MrT Whats your problem? My question is clear already, you considered a = 2.7 and something which has no any relation to my question. Why you are interested in my question even if you don't understand the question properly and not able to answer my question.
score: 0

http://stackoverflow.com/q/49018413
has comment: http://stackoverflow.com/comment/85042418
tagged with: python
has body: I'm playing around with subprocess.Popen for shell commands as it seems it has more flexbility with regards to piping compared to subprocess.run I'm starting off with some simple examples but I'm getting FileNotFoundError: I was told that shell = True is not necessary if I make the arguments as proper lists. However it doesn't seem to be working. Here are my attempts: import subprocess p1 =subprocess.Popen(['dir'], stdout =subprocess.PIPE) output = p1.communicate[0] p = subprocess.Popen([ "dir", "c:\\Users"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) outputs = p.communicate() Both are leading to FileNotFoundError
possible better answer: http://stackoverflow.com/a/49018557
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3172470
has answer: http://stackoverflow.com/a/49018557
tagged with: subprocess
has answer: http://stackoverflow.com/a/59183527
accepted answer: http://stackoverflow.com/a/49018736
has title: FileNotFoundError: subprocess.Popen(['dir'] (Windows 7)
type: Question
score: 5
upvote count: 5
downvote count: 0
answer count: 3
linked to: http://stackoverflow.com/q/3022013
has answer: http://stackoverflow.com/a/49018736
duplicate of: http://stackoverflow.com/q/3022013
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/49094101
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85217996
has body: Next to the fix by @solarissmoke (changing instance.owner to instance.user) which fixes IntegrityError, you are triggering user_logged_in() signal in the is_valid() method here: def form_valid(self, form): if form.is_valid(): roote = Post.objects.filter(owner =self.request.user) instance = form.save(commit=False) instance.user = self.request.user # Here you trigger signal that creates UserSession! user_logged_in.send(self.request.user, request=self.request) return super(NewLocationCreateForm, self).form_valid(form) One object is therefore created with the CreateView and another one with this signal. Remove this line in form_valid(). EDIT: To include data from signal, simply add this to form_valid() like this: def form_valid(self, form): if form.is_valid(): roote = Post.objects.filter(owner =self.request.user) instance = form.save(commit=False) instance.user = self.request.user instance.ip_address = get_client_ip(self.request) instance.city_data = get_client_city_data(instance.ip_address) instance.session_key = self.request.session.session_key return super(NewLocationCreateForm, self).form_valid(form)
type: Answer
has comment: http://stackoverflow.com/comment/85231280
answers question: http://stackoverflow.com/q/49091357
has comment: http://stackoverflow.com/comment/85228903
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49091357
has comment: http://stackoverflow.com/comment/85211083

http://stackoverflow.com/q/48990507
has body: I'm trying to get a count of rows in an sqlalchemy database, for each unique entry in a column, while simultaneously filtering for another two columns. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy(app) class FPTP(db.Model): id = db.Column(db.Integer, primary_key=True) candid = db.Column(db.String(40), index=True, unique=False) riding = db.Column(db.String(50), index=True, unique=False) election = db.Column(db.String(30), index=True, unique=False) def results(self, riding, election): result = self.query(func.count(self.candid), self.candid).\ filter(and_(self.election==election, self.riding==riding)).\ group_by(self.candid) return result The documentation makes func.count an argument of query, and so does a tutorial, and some of the other answers here: count unique rows in sql-alchemy, SQLAlchemy func.count with filter. But when I do that I get:TypeError: 'BaseQuery' object is not callable. And another answer here explained that query is an instance and not a class with it's own functions, which was helpful. But the documentation and the tutorial make func.count called by query. I also see examples are in a "session": Group by & count function in sqlalchemy. I want this in a module, not in an interpreter. So building a shell, making a session, and binding an engine is not a solution I am looking for. I see other answers here (like: Define name for column func.count in sqlalchemy), but that's about naming the columns and getting the count for a unique occurrence. I want to do it more pythonic than here: TypeError: 'BaseQuery' object is not callable Flask. I want to call this function: results = FPTP.results("Some Riding", "Election") and get a count of all occurrences like what is given on page 21 of the documentation: [(1, 'ed'), (1, 'fred'), (1, 'mary'), (1, 'wendy')] after filtering by two other columns.
downvote count: 0
linked to: http://stackoverflow.com/q/32497179
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/84986026
has comment: http://stackoverflow.com/comment/84988466
linked to: http://stackoverflow.com/q/1052148
has comment: http://stackoverflow.com/comment/84987303
linked to: http://stackoverflow.com/q/34446725
upvote count: 2
linked to: http://stackoverflow.com/q/31863255
has comment: http://stackoverflow.com/comment/84988196
linked to: http://stackoverflow.com/q/18058438
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: sqlachlemy multiple counts in a module
tagged with: python
score: 2

http://stackoverflow.com/comment/100776231
comment on: http://stackoverflow.com/a/49075409
type: AnswerComment
type: Comment
score: 0
has text: Yeah, I figured out that later, that's exactly what I want.

http://stackoverflow.com/q/48984818
tagged with: taskkill
type: AnsweredQuestion
score: 3
has title: How to kill windows processes whose resource consumption doesn't change using python?
upvote count: 3
type: Question
tagged with: windows-process
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84974591
has answer: http://stackoverflow.com/a/49164871
favorite count: 0
tagged with: memory-management
has body: I have a python script that tests if any firefox processes are running on my windows machine and then kills them: import os, subprocess running_processes = subprocess.check_output('tasklist', shell = True) if "firefox.exe" in running_processes: os.system("TASKKILL /F /IM firefox.exe") I would like to only kill firefox processes whose memory consumption and CPU usage are constant over time (i.e. do not change within a certain interval). How to kill windows processes with constant memory and CPU usage in python?
tagged with: cpu-usage
accepted answer: http://stackoverflow.com/a/49164871
tagged with: python

http://stackoverflow.com/q/49029871
tagged with: python-3.x
has title: Splitting a long text into smaller samples via python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85064300
answer count: 0
score: 0
type: Question
tagged with: text-chunking
has comment: http://stackoverflow.com/comment/85136371
has body: I have tried the sample code in https://de.dariah.eu/tatom/preprocessing.html to chunk 58 text files into seprated n number chunked text file. The code is as the following. But at the end I get one .txt0001 in the output directory instead of chunked files . Could anybody please tell me where do I do a mistake? import os import numpy as np # speeches are in the directory corpus/CorpusTopicModeling # gather all the filenames, sorted alphabetically corpus_path = os.path.join('c:/','corpus', 'CorpusTopicModeling') # look at the first few filenames # (we are sorting because different operating systems may list files in different orders) sorted(os.listdir(path=corpus_path))[0:5] speeches_filenames = [os.path.join(corpus_path, fn) for fn in sorted(os.listdir(corpus_path))] #One way to split a text is to read through it and create a chunk every n words #where n is a number such as 500, 1,000 or 10,000 def split_text(filename, n_words): #Split a text into chunks approximately `n_words` words in length.""" input = open(filename, 'r') words = input.read().split(' ') input.close() chunks = [] current_chunk_words = [] current_chunk_word_count = 0 for word in words: current_chunk_words.append(word) current_chunk_word_count += 1 if current_chunk_word_count == n_words: chunks.append(' '.join(current_chunk_words)) current_chunk_words = [] current_chunk_word_count = 0 chunks.append(' '.join(current_chunk_words) ) return chunks speeches_filenames = [os.path.join(corpus_path, fn) for fn in sorted(os.listdir(corpus_path))] #for consistency across platforms (Linux, OS X, Windows) we must sort the filenames speeches_filenames.sort() chunk_length = 1000 chunks = [] for filename in speeches_filenames: chunk_counter = 0 texts = split_text(filename, chunk_length) if texts is not None: #You need to add check for None prior iteration for text in texts: chunk = {'text': text, 'number': chunk_counter, 'filename': filename} chunks.append(chunk) chunk_counter += 1 # we started with this many files …

http://stackoverflow.com/comment/85000033
score: 0
has text: Your question still isn't clear. The URL is being served by the `deal_by_detail` view, not `deals_by_category`. If this isn't what you expect, you need to post the whole urls.py.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48997218

http://stackoverflow.com/a/49034831
answers question: http://stackoverflow.com/q/49033178
score: 0
has body: Actually you can access your dataframe(s) in vars() if you incorporate it into the __init__ method. Below builds a dictionary of dataframes with keys being original csv file names. class myClass: def __init__(self, name, filepathlist): self.name = name self.filepathlist = filepathlist self.mydataframedict = self.formatData() def formatData(self): tmp_dict = {} for f in self.filepathlist: DFRAW = pd.read_csv(f, header = 9) DFRAW['DateTime'], DFRAW['dummycol1'] = DFRAW[' ;W;W;W;W'].str.split(';', 1).str DFRAW['Col1'], DFRAW['dummycol2'] = DFRAW['dummycol1'].str.split(';', 1).str DFRAW['Col2'], DFRAW['dummycol3'] = DFRAW['dummycol2'].str.split(';', 1).str DFRAW['Col3'], DFRAW['Col4'] = DFRAW['dummycol3'].str.split(';', 1).str DFRAW = DFRAW.drop([' ;W;W;W;W', 'dummycol1', 'dummycol2', 'dummycol3'], axis = 1) tmp_dict[f] = DFRAW return tmp_dict filepathlist = [r"file1.csv", r"file2.csv"] myINST = myClass("MyInstName", filepathlist ) new_dict = myINST.formatData() # LOCAL VARIABLE (ALSO ACCESSIBLE IN VARS) print(vars(myINST)) # {'name': 'MyInstName', 'mydataframedict': {'file1.csv': ..., 'file2.csv': ...}, # 'filepathlist': ['file1.csv', 'file2.csv']}
type: Answer

http://stackoverflow.com/q/49036421
linked to: http://stackoverflow.com/q/17129947
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85078089
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49037649
tagged with: graph
has title: ticker.FixedFormatter strategy to show the tics of the ax2 axis
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/49037649
has comment: http://stackoverflow.com/comment/85078759
tagged with: python
has comment: http://stackoverflow.com/comment/85078964
has body: Given 3 arrays: X1 = 10.00, 30.10, 50.20, 70.30 ... X2 = 1.9976433815311, 2.0109630315475, 2.0372702369401, 2.0665284897891 ... Y = -0.0000008764356, -0.0000149459573, -0.0000326996870, -0.0000513717121 ... There is a one-to-one correspondence between X1, X2 and Y, i.e. the i-th element of X1 has an i-th associated value of X2 and a i-th value of Y. The following is the plot of Y as a function of X1 (blue dots). I would need the X2 axis to show all the corresponding X2 values for each X1 value. Following the second answer on this post, I have partially accomplished this thorugh the ticker.FixedFormatter strategy, by which: the X2 array needs to be transformed to a tuple, and each element of this tuple needs to be a string. As can be seen, not all red values of X2 are displayed for each value of X1, e.g. for X1 = 10.0 the corresponding X2 = 2.00 appears to be displaced. I do not understand very well why this is occurring. I would appreciate if you could help me. import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import sys X1 = np.array([10.0000000000000, 30.1000000000000, 50.2000000000000, 70.3000000000000, 90.4000000000000, 110.5100000000000, 130.6100000000000, 150.7100000000000, 170.8100000000000, 190.9100000000000, 211.0100000000000, 231.1100000000000, 251.2100000000000, 271.3100000000000, 291.4100000000000, 311.5200000000000, 331.6200000000000 ]) Y = np.array([-0.0000008764356, -0.0000149459573, -0.0000326996870, -0.0000513717121, -0.0000652350399, -0.0000842214902, -0.0001003825474, -0.0001214363281, -0.0001376971422, -0.0001572720132, -0.0001971891337, -0.0002203926200, -0.0002747064193, -0.0003217228112, -0.0003764577474, -0.0004657478828, -0.0006232016207]) X2 = np.array([1.9976433815311, 2.0109630315475, 2.0372702369401, 2.0665284897891, 2.0995743328944, 2.1392386324550, 2.1789200955649, 2.2290243968267, 2.2872281293691, 2.3180577547912, 2.4100643103912, 2.4826981368480, 2.5794602952095, 2.6764219232389, 2.7963983991814, 2…

http://stackoverflow.com/a/49098617
score: 0
type: Answer
has body: Off the top of my head, since you know the center of the object but not its shape or its height/width, I would do this by finding the connected components in the image. In Opencv, this can be done via the connectedComponents function. Take a look at this post for an example explaining how to call it from python. This function is quite optimized so unless you want to do real-time compute-intensive optimization you can use it without noticing any overhead. Once you have the connected components, you can order the pixels of each component (once according to the horizontal component, and once according to the vertical one), and get a bounding box of the form [left,right,top,bottom]. After that, checking whether a point falls inside it is trivial.
answers question: http://stackoverflow.com/q/49098518

http://stackoverflow.com/q/49091145
tagged with: data-science
has answer: http://stackoverflow.com/a/49122750
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/49091225
type: UnansweredQuestion
tagged with: python
has title: Can I keyboard interrupt GridSearchCV somehow and still have the best parameters gathered until that point?
has comment: http://stackoverflow.com/comment/85188487
has body: So I have the following code- params = {'n_estimators': [1000, 2000], 'max_depth': [10, 20], 'min_samples_split': [2, 3], 'learning_rate': [0.1, 0.05, 0.01], 'loss': ('ls', 'huber', 'lad', 'quantile'), 'verbose': [1]} gbr = ensemble.GradientBoostingRegressor() clf = GridSearchCV(gbr, params) And, although I don't think I've given it much to contemplate, it's taking FOREVER to determine the best parameters. After watching for a couple hours I've seen great instances (verbose:[1]) and wish to stop it from continuing. I don't want to have to come back to this in the morning and hope that it's finished. I want to finish it now without losing the hours of tuning in the process. Is there a safe way I can stop the tuning and still have the best result?
type: Question
linked to: http://stackoverflow.com/q/39377052
answer count: 2
score: 5
upvote count: 5
tagged with: grid-search

http://stackoverflow.com/comment/111917632
score: 25
comment on: http://stackoverflow.com/a/48994441
type: AnswerComment
type: Comment
has text: I love how you explained why 'after_request' and 'teardown_request' don't achieve what the questioner's asking for, because all ove stackoverflow people have mentioned these two as the solutions.

http://stackoverflow.com/comment/113733798
has text: I'm getting the same trash and I'm simply removing them by `[os.remove(spurious_file) for spurious_file in glob(LOCAL_TEST_DATA_STORAGE_PATH+"/**/._*", recursive=True)]`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49097306
score: 1

http://stackoverflow.com/q/49077843
has body: I have a dataframe, and I am trying to get a Series of the form: col1 col2 col3 col1 1.0 0.20 0.70 col2 0.2 1.00 0.01 col3 0.7 0.01 1.00 GOAL: col1Xcol1 1.0 col1Xcol2 0.2 col1Xcol3 0.7 col2Xcol1 0.2 ... My code so far: pvals2=pd.DataFrame({'col1': [1, .2,.7], 'col2': [.2, 1,.01], 'col3': [.7,.01,1]}, index = ['col1', 'col2', 'col3']) print(pvals.transpose().join(pvals, how='outer',lsuffix='_left', rsuffix='_right')) OUTPUT: vote_left ballot1_left ballot1_x_left vote_right ballot1_right \ vote 0 0.0923 0.0521 0 0.0923 ballot1 0.0923 0 0.8213 0.0923 0 ballot1_x 0.0521 0.8213 0 0.0521 0.8213 ballot1_x_right vote 0.0521 ballot1 0.8213 ballot1_x 0
type: Question
has answer: http://stackoverflow.com/a/49078103
has comment: http://stackoverflow.com/comment/85161751
downvote count: 0
has answer: http://stackoverflow.com/a/49078497
tagged with: pandas
has answer: http://stackoverflow.com/a/49078188
answer count: 4
has answer: http://stackoverflow.com/a/49078200
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49078497
has comment: http://stackoverflow.com/comment/85162073
has title: turn pandas dataframe into series by iterating over columns
has comment: http://stackoverflow.com/comment/85162672
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85161887
score: 1
possible better answer: http://stackoverflow.com/a/49078103

http://stackoverflow.com/comment/85222495
type: AnswerComment
score: 0
type: Comment
has text: @UtkarshAgrawal OK please give me a minute.
comment on: http://stackoverflow.com/a/49108603

http://stackoverflow.com/a/48965545
has body: I modified a stackoverflow answer into tardata.py which looks for control.txt and places it in a data directory and calls the extracted file control.tar.gz. import os import tarfile tar_file = "control.tar.gz" source_file = "control.txt" inside_dir = "data" def make_tarfile(tar_file, source_file, inside_dir): with tarfile.open(tar_file, "w:gz") as tar: tar.add(source_file, arcname=os.path.join(inside_dir, source_file)) make_tarfile(tar_file, source_file, inside_dir) The code uses the optional argument arcname which allows the creation of the directory inside the tar file. The tarfile.Add() documentation says If given, arcname specifies an alternative name for the file in the archive. Run $ python tardata.py Check the created tar files heirarchy $ tar --list -f control.tar.gz data/control.txt
upvote count: 1
has comment: http://stackoverflow.com/comment/84945346
has comment: http://stackoverflow.com/comment/84966762
has comment: http://stackoverflow.com/comment/84990684
type: Answer
answers question: http://stackoverflow.com/q/48964886
has comment: http://stackoverflow.com/comment/84986183
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84958351
has comment: http://stackoverflow.com/comment/84965644
has comment: http://stackoverflow.com/comment/84987487

http://stackoverflow.com/q/48970770
tagged with: artificial-intelligence
has answer: http://stackoverflow.com/a/48971126
has body: I am trying to install lastest Kivy (development version). I encounter error (detail log is attached below). Following is my environment: OS: macOS Sierra 10.12.6 (16G1212) Python: 3.6 ( on virtual envrioment) I have done (Following Official Installation Guide brew install pkg-config sdl2 sdl2_image sdl2_ttf sdl2_mixer gstreamer pip install Cython==0.26.1 Then: pip install kivy After this one failed, I tried installing dev version as suggested in Kivy Issue Tracker USE_OSX_FRAMEWORKS=0 pip install https://github.com/kivy/kivy/zipball/master Error I got: .... There are lot of log before this ....... In file included from /private/var/folders/m_/cxdqcdn179x_rxt6ly6k216w0000gn/T/pip-0g4ixb48-build/kivy/lib/gstplayer/_gstplayer.c:482: In file included from /usr/local/Cellar/gstreamer/1.12.4/include/gstreamer-1.0/gst/gst.h:89: /usr/local/Cellar/gstreamer/1.12.4/include/gstreamer-1.0/gst/gstutils.h:159:27: warning: shift count &gt;= width of type [-Wshift-count-overflow] *(guint64*)(void*)(p) = GUINT64_SWAP_LE_BE (v); ^~~~~~~~~~~~~~~~~~~~~~ /usr/local/Cellar/glib/2.54.3/include/glib-2.0/glib/gtypes.h:247:40: note: expanded from macro 'GUINT64_SWAP_LE_BE' # define GUINT64_SWAP_LE_BE(val) (GUINT64_SWAP_LE_BE_IA32 (val)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/local/Cellar/glib/2.54.3/include/glib-2.0/glib/gtypes.h:234:18: note: expanded from macro 'GUINT64_SWAP_LE_BE_IA32' __r.__ll = GUINT64_SWAP_LE_BE_CONSTANT (__w.__ll); \ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/local/Cellar/glib/2.54.3/include/glib-2.0/glib/gtypes.h:175:53: note: expanded from macro 'GUINT64_SWAP_LE_BE_CONSTANT' (guint64) G_GINT64_CONSTANT (0x00ff000000000000U)) &gt;&gt; 40) | \ ^ ~~ In file included from /private/var/folders/m_/cxdqcdn179x_rxt6ly6k216w0000gn/T/pip-0g4ixb48-build/kivy/lib/gstplayer/_gstplayer.c:482: In file included from /usr/local/Cellar/gstreamer/1.12.4/include/gstreamer-1.0/gst/gst.h:89: /usr/local/Cellar/gstreamer/1.12.4/include/gstreamer-1.0/gst/gstutils.h:159:27: warning: shift coun…
type: UnansweredQuestion
has title: Install latest version of Kivy fails
type: Question
answer count: 1
score: 0
tagged with: python
tagged with: kivy

http://stackoverflow.com/a/49079096
answers question: http://stackoverflow.com/q/49079008
score: 0
upvote count: 1
downvote count: 1
type: Answer
has body: You can try to change URLs in the settings of the whole project like this: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^timer/$', include('timer.urls')), ] As for the timer, the URLs will be like this: urlpatterns = [ url(r'^$', views.index, name="index"), ] Don't forget about r's in the url().
has comment: http://stackoverflow.com/comment/85203331

http://stackoverflow.com/q/48976039
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48976152
favorite count: 0
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 1
type: Question
tagged with: benchmarking
has body: I found the following example in Python's document. def test(): """Stupid test function""" L = [] for i in range(100): L.append(i) if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) However that only works when the code is defined in a script. How can I test a function that is defined in a Python repl? Hope someone can point me the right direction. Below is my testing. &gt;&gt;&gt; import timeit &gt;&gt;&gt; dir(timeit) ['Timer', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__sp ec__', '_globals', 'default_number', 'default_repeat', 'default_timer', 'dummy_src_name', 'gc', 'itertools', 'main', 're indent', 'repeat', 'sys', 'template', 'time', 'timeit'] &gt;&gt;&gt; help(timeit.timeit) Help on function timeit in module timeit: timeit(stmt='pass', setup='pass', timer=&lt;built-in function perf_counter&gt;, number=1000000, globals=None) Convenience function to create Timer object and call timeit method. &gt;&gt;&gt; timeit.timeit('''a=""; a+="b"*1000;''') 0.14870357161726633 &gt;&gt;&gt; timeit.timeit('''a=""; a+="b"*1000;''') 0.13576636550958954 &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; def testme(): ... a = "" ... a = "eyang" * 10000 ... &gt;&gt;&gt; timeit("testme()") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'module' object is not callable &gt;&gt;&gt; &gt;&gt;&gt; timeit("testme()", setup="from __main__ import testme") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'module' object is not callable &gt;&gt;&gt;
has title: How to import functions from the interactive session namespace for timeit benchmarks?
has answer: http://stackoverflow.com/a/48976152

http://stackoverflow.com/a/49000174
has body: Please see this notebook for more details. https://nbviewer.jupyter.org/github/emican86/48999037/blob/master/48999037.ipynb .loc is primarily label based. Data had to be aligned and labels set.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85247687
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48999037
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48999037
score: 1

http://stackoverflow.com/comment/85491245
has text: The alibi lines I meant are the lines that surround the important information, namely the `xmlDesc = ` and the `dom = ...`. In between is configuration, which is used by libvirt to boot a KVM instance. Since KVM starts successfully, I'd say that part works. If whatever you run inside the VM doesn't work and that is controlled by the configuration which is passed through, it's a configuration issue and it doesn't seem to have any relation to programming, in particular not to Python.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49012747
score: 0

http://stackoverflow.com/a/49078325
has comment: http://stackoverflow.com/comment/85163433
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49078267
type: AcceptedAnswer
upvote count: 5
has comment: http://stackoverflow.com/comment/85168457
has body: str.isupper returns a boolean (True or False) if a string is entirely uppercased. In Python 1 == True and 0 == False so you can sum booleans. The only thing left is to split the original string into words using .split. sum(map(str.isupper, "This was a great product".split())) # 0 sum(map(str.isupper, "This was NOT AT ALL GOOD".split())) # 4
has comment: http://stackoverflow.com/comment/85163215
has comment: http://stackoverflow.com/comment/85163609
score: 4
answers question: http://stackoverflow.com/q/49078267
type: Answer

http://stackoverflow.com/comment/85007037
comment on: http://stackoverflow.com/q/49000249
score: 0
type: QuestionComment
has text: i dont think so.. but how to check that? i dont think its getting mapped correctly because everytime i query with pystun it always returns the same port 54320
type: Comment

http://stackoverflow.com/comment/117244498
comment on: http://stackoverflow.com/a/51116910
type: Comment
score: 1
has text: @MikeWilliamson Thank you :-) You can search for "Start a bounty", it's right right below the question, and select "award an existing answer".
type: AnswerComment

http://stackoverflow.com/q/49022482
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/85050021
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49023539
accepted answer: http://stackoverflow.com/a/49023539
has body: I have read a ton of stackoverflow answers and a bunch of tutorials. In addition, I tried to read the Python documentation, but I cannot make this import work. This is how the directory looks like: myDirectory ├── __init__.py ├── LICENSE ├── project.py ├── README.md ├── stageManager.py └── tests ├── __init__.py └── test_project.py There is a class in project.py called Project, and I want to import it in a file under tests directory. I have tried the following: Relative import: from ..project import Project def print_sth(): print("something") This gives me the following error: (running from the tests directory as python test_project.py and from myDirectory as python tests/test_project.py) Traceback (most recent call last): File "test_project.py", line 1, in &lt;module&gt; from ..project import Project SystemError: Parent module '' not loaded, cannot perform relative import Absolute import with package name: If I have something like the following, I get ImportError (with the same run command as above). from project import Project def print_sth(): print("something") ------------------------------------------------------ Traceback (most recent call last): File "test_project.py", line 1, in &lt;module&gt; from project import Project ImportError: No module named 'project' and this too: from myDirectory.project import Project def print_sth(): print("something") ------------------------------------------------------ Traceback (most recent call last): File "test_project.py", line 1, in &lt;module&gt; from myDirectory.project import Project ImportError: No module named 'myDirectory' Finally, I tried adding the if __name__ == '__main__' statement within the test_project.py file, but it still failed. I would really appreciate if anyone could help. If there is a solution where I do not have to write a verbose command, I would prefer that.
type: Question
has comment: http://stackoverflow.com/comment/85051209
tagged with: python-import
upvote count: 1
has title: Python 3.5 cannot import a module

http://stackoverflow.com/q/49045299
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: -5
tagged with: evernote
has title: error : exec x in pypdfocr in python
type: Question
has body: How can i solve this problem, I am getting the exec x error in evernote/setup.py while installing pypdfocr in python
downvote count: 5
has answer: http://stackoverflow.com/a/49045332
upvote count: 0
answer count: 1
tagged with: exec

pandas
tags question: http://stackoverflow.com/q/49075166
tags question: http://stackoverflow.com/q/49036714
tags question: http://stackoverflow.com/q/48992868
tags question: http://stackoverflow.com/q/49052687
tags question: http://stackoverflow.com/q/49110112
tags question: http://stackoverflow.com/q/49077885
tags question: http://stackoverflow.com/q/49052270
tags question: http://stackoverflow.com/q/49090600
tags question: http://stackoverflow.com/q/49115877
tags question: http://stackoverflow.com/q/48990987
tags question: http://stackoverflow.com/q/49050974
tags question: http://stackoverflow.com/q/48996822
tags question: http://stackoverflow.com/q/49049771
tags question: http://stackoverflow.com/q/49009475
tags question: http://stackoverflow.com/q/49120845
tags question: http://stackoverflow.com/q/49057589
tags question: http://stackoverflow.com/q/49008179
tags question: http://stackoverflow.com/q/49030144
tags question: http://stackoverflow.com/q/49031333
tags question: http://stackoverflow.com/q/48967861
tags question: http://stackoverflow.com/q/49099861
tags question: http://stackoverflow.com/q/49069624
tags question: http://stackoverflow.com/q/48965221
tags question: http://stackoverflow.com/q/49109744
tags question: http://stackoverflow.com/q/49100471
tags question: http://stackoverflow.com/q/49120232
tags question: http://stackoverflow.com/q/49064814
tags question: http://stackoverflow.com/q/48980425
tags question: http://stackoverflow.com/q/49052783
tags question: http://stackoverflow.com/q/49025162
tags question: http://stackoverflow.com/q/48965791
tags question: http://stackoverflow.com/q/49068020
tags question: http://stackoverflow.com/q/49027906
tags question: http://stackoverflow.com/q/49024654
tags question: http://stackoverflow.com/q/49110542
tags question: http://stackoverflow.com/q/49115514
tags question: http://stackoverflow.com/q/48981870
tags question: http://stackoverflow.com/q/49095323
tags question: http://stackoverflow.com/q/49102057
tags question: http://stackoverflow.com/q/49090239
tags question: http://stackoverflow.com/q/49051409
tags question: http://stackoverflow.com/q/49056949
tags question: http://stackoverflow.com/q/49047244
tags question: http://stackoverflow.com/q/49018295
tags question: http://stackoverflow.com/q/49027872
tags question: http://stackoverflow.com/q/49072001
tags question: http://stackoverflow.com/q/49010052
tags question: http://stackoverflow.com/q/49037065
tags question: http://stackoverflow.com/q/49022769
tags question: http://stackoverflow.com/q/49102424
tags question: http://stackoverflow.com/q/49020522
tags question: http://stackoverflow.com/q/49077843
tags question: http://stackoverflow.com/q/49067640
tags question: http://stackoverflow.com/q/49074021
tags question: http://stackoverflow.com/q/48993925
tags question: http://stackoverflow.com/q/49098072
tags question: http://stackoverflow.com/q/49008313
tags question: http://stackoverflow.com/q/49103308
tags question: http://stackoverflow.com/q/48999328
tags question: http://stackoverflow.com/q/48973793
tags question: http://stackoverflow.com/q/49091919
tags question: http://stackoverflow.com/q/49039057
tags question: http://stackoverflow.com/q/49045401
tags question: http://stackoverflow.com/q/49015475
tags question: http://stackoverflow.com/q/49119785
tags question: http://stackoverflow.com/q/49080911
tags question: http://stackoverflow.com/q/49113637
tags question: http://stackoverflow.com/q/49091835
tags question: http://stackoverflow.com/q/49054415
tags question: http://stackoverflow.com/q/48994973
tags question: http://stackoverflow.com/q/49019531
tags question: http://stackoverflow.com/q/49051805
tags question: http://stackoverflow.com/q/49007680
tags question: http://stackoverflow.com/q/49106732
tags question: http://stackoverflow.com/q/49000361
tags question: http://stackoverflow.com/q/49121109
tags question: http://stackoverflow.com/q/49073818
tags question: http://stackoverflow.com/q/48994666
tags question: http://stackoverflow.com/q/49019834
tags question: http://stackoverflow.com/q/49088759

http://stackoverflow.com/comment/85212164
type: Comment
has text: I dont see any update ...what was the copy/paste error?
comment on: http://stackoverflow.com/a/49102680
score: 0
type: AnswerComment

http://stackoverflow.com/a/49061812
type: Answer
answers question: http://stackoverflow.com/q/49061757
accepted answer of: http://stackoverflow.com/q/49061757
score: 0
type: AcceptedAnswer
has body: https://docs.python.org/2/library/copy.html Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below). Interface summary: copy.copy(x) Return a shallow copy of x. copy.deepcopy(x) Return a deep copy of x. Please read through the above link, that should help with your problem

http://stackoverflow.com/a/74137286
downvote count: 1
answers question: http://stackoverflow.com/q/49005651
has body: If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows many planes to land simultaneously on the same runway by using the event loop to suspend functions and allow other functions to run when you use the await syntax it basically means that plane(function can be suspended and allow other functions to process
type: Answer
score: 2
upvote count: 3

http://stackoverflow.com/q/49115628
has answer: http://stackoverflow.com/a/54032683
has answer: http://stackoverflow.com/a/50106075
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50106075
tagged with: installation
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/67436096
has comment: http://stackoverflow.com/comment/85236548
tagged with: anaconda
score: 1
tagged with: python-2.7
answer count: 3
upvote count: 1
favorite count: 0
tagged with: cvxpy
tagged with: python
has title: How to install CVXPY on MS Windows?
possible better answer: http://stackoverflow.com/a/54032683
has body: I am trying to install CVXPY on windows. I already had installed Anaconda, so I am following this steps. I updated anaconda to the latest version, and checked that the Visual Studio C++ compiler for Python was already installed on my computer. After that I installed SCS from Anaconda running the command suggested: conda install -c https://conda.anaconda.org/omnia scs This returned an error message: Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - blaze - scs Use "conda info &lt;package&gt;" to see the dependencies for each package. I dont know what the blaze package is, something installed by anaconda I guess, so I unistalled it from pip and then installed scs ( I say this just in case it is important, the real problem comes now) After installing SCS I installed CVXPY: pip install cvxpy Apparently no error mesdsages appeared during the installation, but then I run the nosetest: nosetests cvxpy And this returned 27 error messages that I have no idea how to solve. ¿Anyone else had this problem and can give me some hints? (I paste here some of the error messages I get). ====================================================================== ERROR: Failure: ImportError (cannot import name SymbolicQuadForm) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\alvaromc317\Anaconda2\lib\site-packages\nose\loader.py", line 418, in loadTestsFromName addr.filename, addr.module) File "C:\Users\alvaromc317\Anaconda2\lib\site-packages\nose\importer.py", line 47, in importFromPath return self.importFromDir(dir_path, fqname) File "C:\Users\alvaromc317\Anaconda2\lib\site-packages\nose\importer.py", line 94, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "C:\Users\alvaromc317\Anaconda2\lib\site-packages\cvxpy\reductions\__init__.py", line 25, in &lt;module&gt; from cvxpy.reductions.dcp2cone.cone_matrix_stuffing import ConeMatrixStuf…

http://stackoverflow.com/comment/85317573
type: Comment
has text: The OP explicitly said they didn't want to have to handle the exception to set a flag - but *setting a flag is handling the exception*. You can't say, "I want to do something when an exception happens, but I don't want to do anything when the exception happens". It just so happens that in the OPs case, "doing something" is recording that an exception happened. Then at that point the options are a) re-raise the exception b) raise a new exception (from the current one) and b) silence all exceptions. If you have specific handling to perform for exception types A, B, and C, but you want different
type: AnswerComment
comment on: http://stackoverflow.com/a/49113413
score: 0

http://stackoverflow.com/q/48973464
type: UnansweredQuestion
tagged with: firebase-realtime-database
type: Question
tagged with: firebase
has answer: http://stackoverflow.com/a/48975506
answer count: 1
has title: Firebase connection limit reached
score: 0
tagged with: rest
tagged with: python
has body: I was working with Pyrebase( python library for firebase) and was trying .stream() method but when I saw my firebase dashboard it showed 100 connection limit reached. Is there any way to remove those concurrent connection?
has comment: http://stackoverflow.com/comment/90293558

http://stackoverflow.com/comment/85050254
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49014910
type: Comment
has text: s=s.str.split('=',expand=True) needs to changed to s=New.str.split('=',expand=True)

http://stackoverflow.com/comment/84935353
has text: Check the fundamentales. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data Your form have no action and no fields. So your sending form have no data.
comment on: http://stackoverflow.com/a/48964455
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49118482
favorite count: 0
has comment: http://stackoverflow.com/comment/85281631
type: Question
has title: How to find words which contain the first 3 characters input by a user
has comment: http://stackoverflow.com/comment/85281621
has answer: http://stackoverflow.com/a/49118623
tagged with: python
has answer: http://stackoverflow.com/a/49118581
has body: How can I find words which contain the first 3 characters input by a user. If the file contains words NYL000234 and other words, and user gives an input like NYL, then output would be NYL000234. Example - Text file contains - 10099834 COL01139 OD 1_1_2_1 T1 10115177 COL01356 OD 1_1_3_1 T1 10099848 COL03031 OD 1_1_2_1 T1 10093544 COL03008 OD 1_1_1_1 T1 10101126 COL03050 ID 1_1_2_1 10093697 COL03002 ID 1_1_3_1 10122993 COL05067 ID 1_1_2_1 10093668 COL03047 ID 1_1_2_1 10127012 COL05077 ID 1_1_3_1 10093664 COL03045 ID 1_1_2_1 If the user gives input COL then output would be like this.. (output should be column not in row) COL01139 COL01356 COL03031 COL03008 COL03050 COL03002 COL05067 COL03047 COL05077 COL03045
upvote count: 2
score: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85281469
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85243588

http://stackoverflow.com/q/49106837
has comment: http://stackoverflow.com/comment/85218807
tagged with: python
has title: using pandas dt functions under a groupby
has comment: http://stackoverflow.com/comment/85219919
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85219300
has comment: http://stackoverflow.com/comment/85219752
has comment: http://stackoverflow.com/comment/85220748
has comment: http://stackoverflow.com/comment/85220405
has answer: http://stackoverflow.com/a/49107394
answer count: 1
has comment: http://stackoverflow.com/comment/85219712
has body: I have a column 'dateTime' and I am trying to achieve the following (which works without gropuby): df['time_of_day_10'] = df['dateTime'].dt.floor('10min') df['time_of_day_30'] = df['dateTime'].dt.floor('30min') but the problem is that after I gorupby my data using: groups = df.groupby(groupbytime,as_index=True) df_grouped = (groups.agg({ 'clients1': [np.mean,np.max,], 'clients2': [np.mean,np.max,], })) I lost my dateTime so I am trying to add it back and added this: groups = df.groupby(groupbytime,as_index=True) df_grouped = (groups.agg({ 'dateTime':['first'], 'clients1': [np.mean,np.max,], 'clients2': [np.mean,np.max,], })) which will give me the dateTims in type of dateTime first datetime64[ns] and I am trying to get the rounded time and the date as separated coulmns within the groupby. Thanks! edited adding sample data: the original data: dateTime Clients1 Clients2 8 2017-10-23 08:00:04.854309 12991.5 2 10 2017-10-23 08:00:04.875162 12991.5 1 11 2017-10-23 08:00:04.875162 12991.5 1 12 2017-10-23 08:00:04.875162 12991.5 1 13 2017-10-23 08:00:04.875162 12991.5 1 23 2017-10-23 08:00:04.876464 12989.5 1 24 2017-10-23 08:00:04.876464 12989.5 1 32 2017-10-23 08:00:04.964356 12990 1 34 2017-10-23 08:00:04.968549 12990.5 1 38 2017-10-23 08:00:05.008758 12990 1 43 2017-10-23 08:00:05.996090 12990 2 45 2017-10-23 08:00:06.018212 12990 1 51 2017-10-23 08:00:06.344568 12989.5 1 56 2017-10-23 08:00:06.903661 12990 1 60 2017-10-23 08:00:07.120324 12990 1 66 2017-10-23 08:00:07.206179 12990.5 1 74 2017-10-23 08:00:07.358889 12991.5 3 77 2017-10-23 08:00:07.491244 12991 1 80 2017-10-23 08:00:07.671106 12991 1 83 2017-10-23 08:00:07.897968 12991 1 87 2017-10-23 08:00:08.028444 12991 1 95 2017-10-23 08:00:09.787827 12991.5 3 98 2017-10-23 08:00:10.178936 12991.5 3 104 2017-10-23 08:00:10.505921 12991.5 2 110 2017-10-23 08:00:11.438628 12992 1 112 2017-10-23 08:00:12.145907 12992 1 the gorupby result is this: dateTime Clients1 Clients1 Clients2 Clients2 first mean amax mean amax 1m…
score: 0
tagged with: pandas

http://stackoverflow.com/q/49008781
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Why do string comparison and identity behave differently in pdb and python console
has comment: http://stackoverflow.com/comment/85021992
tagged with: pdb
type: Question
linked to: http://stackoverflow.com/q/15541404
has comment: http://stackoverflow.com/comment/85023528
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/49010083
answer count: 1
downvote count: 0
has body: I run same snippet of python code in python console and pdb, but I get different results as below: pdb: &gt;&gt;&gt; import pdb &gt;&gt;&gt; pdb.set_trace() (Pdb) print u'你好' == u'\u4f60\u597d' False (Pdb) print u'你好' is u'\u4f60\u597d' False (Pdb) print id(u'你好'), id(u'\u4f60\u597d') 4431713024 4431713120 (Pdb) id(u'你好') 4431713024 (Pdb) id(u'\u4f60\u597d') 4431713024 python console: &gt;&gt;&gt; print u'你好' == u'\u4f60\u597d' True &gt;&gt;&gt; print u'你好' is u'\u4f60\u597d' True &gt;&gt;&gt; print id(u'你好'), id(u'\u4f60\u597d') 4376711984 4376711984 &gt;&gt;&gt; id(u'你好') 4376711984 &gt;&gt;&gt; id(u'\u4f60\u597d') 4376711984 My python version is 2.7.13 So my questions: 1.why operators(like '==' and 'is') perform differently in two consoles. 2.In pdb, id(u'\u4f60\u597d') equals 4431713120 in print id(u'你好'), id(u'\u4f60\u597d') but 4431713024 in id(u'\u4f60\u597d') 3.Why this situation does not occur in python3

http://stackoverflow.com/comment/84995309
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48993468
has text: imageDisp.bound (that arises the error), is initialized with [ ] within the "select_ROI" function. It seems that its content is not being changed ("boundaries" that I printed out is "imageDisp.bound" ). And, the reason is that its content should be the x and y of the clicked point, but I never get the chance to click on the GUI before the program reaches to this point (which is the problem that I seek help with).

http://stackoverflow.com/comment/85061060
type: AnswerComment
type: Comment
has text: While I like f-strings, I think `str(i)` is a lot clearer here.
comment on: http://stackoverflow.com/a/49027448
score: 1

dataframe
tags question: http://stackoverflow.com/q/48974896
tags question: http://stackoverflow.com/q/49118062
tags question: http://stackoverflow.com/q/49016451
tags question: http://stackoverflow.com/q/48989679
tags question: http://stackoverflow.com/q/48985027
tags question: http://stackoverflow.com/q/49026638
tags question: http://stackoverflow.com/q/49020776
tags question: http://stackoverflow.com/q/49117161
tags question: http://stackoverflow.com/q/49099163
tags question: http://stackoverflow.com/q/48972164
tags question: http://stackoverflow.com/q/48978035
tags question: http://stackoverflow.com/q/49075820
tags question: http://stackoverflow.com/q/49100945
tags question: http://stackoverflow.com/q/49111859
tags question: http://stackoverflow.com/q/49061921
tags question: http://stackoverflow.com/q/48998235
tags question: http://stackoverflow.com/q/49077911
tags question: http://stackoverflow.com/q/49067073
tags question: http://stackoverflow.com/q/48991200
tags question: http://stackoverflow.com/q/49058978
tags question: http://stackoverflow.com/q/49074101
tags question: http://stackoverflow.com/q/49016956
tags question: http://stackoverflow.com/q/49059296
tags question: http://stackoverflow.com/q/49085245
tags question: http://stackoverflow.com/q/48969754
tags question: http://stackoverflow.com/q/48976646
tags question: http://stackoverflow.com/q/49114612
tags question: http://stackoverflow.com/q/49004503
tags question: http://stackoverflow.com/q/49032555
tags question: http://stackoverflow.com/q/49090415
tags question: http://stackoverflow.com/q/48969482
tags question: http://stackoverflow.com/q/49061430
tags question: http://stackoverflow.com/q/48994681
tags question: http://stackoverflow.com/q/48977918
tags question: http://stackoverflow.com/q/49099548
tags question: http://stackoverflow.com/q/49042729
tags question: http://stackoverflow.com/q/48989597
tags question: http://stackoverflow.com/q/49101113
tags question: http://stackoverflow.com/q/49118592
tags question: http://stackoverflow.com/q/49021810
tags question: http://stackoverflow.com/q/49073547
tags question: http://stackoverflow.com/q/49036205
tags question: http://stackoverflow.com/q/49118966
tags question: http://stackoverflow.com/q/49037483
tags question: http://stackoverflow.com/q/49054969
tags question: http://stackoverflow.com/q/49017178
tags question: http://stackoverflow.com/q/48967953
tags question: http://stackoverflow.com/q/49088894
tags question: http://stackoverflow.com/q/49117357
tags question: http://stackoverflow.com/q/49026520
tags question: http://stackoverflow.com/q/49053252
tags question: http://stackoverflow.com/q/49033178
tags question: http://stackoverflow.com/q/49040364
tags question: http://stackoverflow.com/q/49000268
tags question: http://stackoverflow.com/q/48986025
tags question: http://stackoverflow.com/q/49063991
tags question: http://stackoverflow.com/q/48972525
tags question: http://stackoverflow.com/q/48976142
tags question: http://stackoverflow.com/q/48985034
tags question: http://stackoverflow.com/q/49085445
tags question: http://stackoverflow.com/q/49045203
tags question: http://stackoverflow.com/q/48997644
tags question: http://stackoverflow.com/q/49075047
tags question: http://stackoverflow.com/q/49019323
tags question: http://stackoverflow.com/q/49011034
tags question: http://stackoverflow.com/q/49043614
tags question: http://stackoverflow.com/q/49022851
tags question: http://stackoverflow.com/q/48998325
tags question: http://stackoverflow.com/q/49045283
tags question: http://stackoverflow.com/q/48973840
tags question: http://stackoverflow.com/q/48999774
tags question: http://stackoverflow.com/q/48995329
tags question: http://stackoverflow.com/q/49039402
tags question: http://stackoverflow.com/q/48998843
tags question: http://stackoverflow.com/q/49006710
tags question: http://stackoverflow.com/q/48971488
tags question: http://stackoverflow.com/q/49014811
tags question: http://stackoverflow.com/q/49089325
tags question: http://stackoverflow.com/q/48971745
tags question: http://stackoverflow.com/q/48999007

http://stackoverflow.com/q/48986465
tagged with: python
tagged with: netcdf4
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85114634
has comment: http://stackoverflow.com/comment/116063216
tagged with: python-xarray
score: 0
has body: I am trying to resample precipitation data, PET-data and temperature data from hourly to six hourly with xarray in Python. After this step, the idea is to merge these three datasets into one netCDF4-file. Until this merge, xarray performs reasonably fast (approximately 40 seconds), but the save to netcdf takes two days and then crashes. The data is together ~25GB. I saw that this problem occurs more often, but I have not found any solution yet.. Thanks in advance for your help! Below my used code: import xarray import datetime from datetime import * import time start = time.time()` # Rhine P = xarray.open_dataset("D:\P_Rhine_total.nc", decode_times=True, chunks={'time':500}) P = P.sel(time=slice(datetime(2010, 1, 1, 1), datetime(2015, 12, 31, 0))) Pnew = P.precipitation_thickness.rename("P") Pagg = Pnew.resample('6H','time',how='sum', closed='right', label='right') PET = xarray.open_dataset("D:\PET_Rhine_total.nc", decode_times=True, chunks={'time':500}) PET = PET.sel(time=slice(datetime(2010, 1, 1, 1), datetime(2015, 12, 31, 0))) PETnew = PET.makkink_potential_evaporation.rename("PET") PETagg = PETnew.resample('6H','time',how='sum', closed='right', label='right') T = xarray.open_dataset("D: \T_Rhine_total.nc", decode_times=True, chunks={'time':500}) T = T.sel(time=slice(datetime(2010, 1, 1, 1), datetime(2015, 12, 31, 0))) Tnew = T.air_temperature.rename("TEMP") Tagg = Tnew.resample('6H','time',how='mean', closed='right', label='right') New = xarray.merge((Pagg,PETagg,Tagg)) New.chunk(chunks={'time':500}) New.to_netcdf(path="D:\\forcing_Rhine.nc",mode="w",format="NETCDF4", encoding={'P': {'dtype': 'float32', 'scale_factor': 0.001, '_FillValue': -9999}, 'PET': {'dtype': 'float32', 'scale_factor': 0.001, '_FillValue': -9999}, 'TEMP': {'dtype': 'float32', 'scale_factor': 0.001, '_FillValue': -9999}}) End = time.time() print End-start
has comment: http://stackoverflow.com/comment/85297760
tagged with: dask
type: UnansweredQuestion
has title: Xarray to_netcdf very slow and crashes for large dataset in python

http://stackoverflow.com/q/49036075
tagged with: list
has answer: http://stackoverflow.com/a/49036155
tagged with: mysql
has body: import MySQLdb items = [] db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '******' , db = '*******') cursor = db.cursor() cursor.execute("SELECT longitude FROM coordinates") data = cursor.fetchall() for row in data: new_items = items[row] print new_items my database has 4 columns. an integer id, and three decimal rows called longitude, latitude, and heading. there are 4 sets of 'dummy' data in the database, and I am trying to be able to grab all 4 of those longitude data (they are of type decimal) and store them in some type of array. I know my code is set up as a list right now, which is why I am getting an error that says lists only except integer data type... does anybody know how to store decimal data types as an array of some sort?
type: Question
tagged with: decimal
has title: pulling decimal data from database and storing in array
accepted answer: http://stackoverflow.com/a/49036155
has comment: http://stackoverflow.com/comment/85077237
tagged with: arrays
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85077179
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49019609
has answer: http://stackoverflow.com/a/49019995
type: AnsweredQuestion
has body: I want to group the number of messages by recipient user -> {'User 1': 5};{'User 2': 7}... My model: class Mensaje(models.Model): remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Remitente') destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Destinatario') mensaje = models.TextField(validators=[MaxLengthValidator(1000)]) leido = models.BooleanField(default=False) fechaEnvio = models.DateTimeField(auto_now_add=True) My query: mensajes = Mensaje.objects.filter(destinatario=request.user).values('pk', 'remitente__username').annotate(num_msg=Count('pk')).order_by('-fechaEnvio') Result: {'pk': 28, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 27, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 26, 'remitente__username': 'jota', 'num_msg': 1}, {'pk': 25, 'remitente__username': 'jota', 'num_msg': 1}... As you can see, the query returns all the messages without group by user. Another question: Why does not work mensajes = request.user.mensaje_set.all()?
has comment: http://stackoverflow.com/comment/85044855
tagged with: django
has comment: http://stackoverflow.com/comment/85053068
type: Question
has answer: http://stackoverflow.com/a/49023675
accepted answer: http://stackoverflow.com/a/49023675
has title: Django query does not group
possible better answer: http://stackoverflow.com/a/49019995
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85046029
tagged with: python

http://stackoverflow.com/q/49048143
downvote count: 0
has comment: http://stackoverflow.com/comment/85103258
tagged with: datetime
has body: I have a list of datetime.date and a list of datetime.time values. I would like the date on the x axis and the time on the y axis. x = [datetime.date(2018, 1, 15), datetime.date(2018, 1, 16), datetime.date(2018, 1, 17)] y = [datetime.time(18, 15), datetime.time(17, 15), datetime.time(17, 47)] When I try to plot the time on the y axis and the date on the x I get a numpy error: "TypeError: float() argument must be a string or a number" To get around it, I converted both values into datetimes, adding an arbitrary date to the time and a time of zero to the date: x_new = [datetime.datetime.combine(d, datetime.datetime.min.time()) for d in x] y_new = [datetime.datetime.combine(datetime.datetime.now().date(), t) for t in y] That's fine, but when I plot this my y axis shows no minutes or seconds and instead has the format 'dd HH:MM' e.g: '01 17:16' if I plot today. If I zoom in I can see the minutes and seconds, but that's no good. I want only hour, min, second to show, no date. I hoped that using the plot_date option rather than just plot, I might find what I need, but that hasn't helped me. I hope my question makes sense. Any help would be much appreciated. I saw an example where someone had their times formatted as strings, but I had some issues with that (another story), and I'd rather use datetimes really if possible. Thanks!
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: Plotting python datetime.time on y axis and datetime.date on x axis
upvote count: 1
tagged with: python
tagged with: plot
linked to: http://stackoverflow.com/q/35663705
has comment: http://stackoverflow.com/comment/85104829
score: 1
type: Question
has comment: http://stackoverflow.com/comment/85104797
has comment: http://stackoverflow.com/comment/85103724
has comment: http://stackoverflow.com/comment/85102677
has comment: http://stackoverflow.com/comment/85104705
has comment: http://stackoverflow.com/comment/85104073

http://stackoverflow.com/a/49051121
answers question: http://stackoverflow.com/q/49049940
downvote count: 0
upvote count: 1
type: Answer
has body: There is a neat library for displaying progress in terminal, named tqdm. Install it with $ pip install tqdm Example script: import time from tqdm import tqdm seconds = 10 for i in tqdm(range(seconds)): time.sleep(1) # sleep one second in each iteration Run the script: $ python spam.py 100%|██████████████████████████████| 10/10 [00:10&lt;00:00, 1.00s/it] tqdm is highly customizable, check out the documentation available on its PyPI page. Example with prepending custom message before the progress bar: import time from tqdm import tqdm for i in tqdm(range(10), desc='LOADING'): time.sleep(1) Output: $ python spam.py LOADING: 100%|█████████████████████| 10/10 [00:10&lt;00:00, 1.00s/it]
score: 1

http://stackoverflow.com/comment/85214682
type: Comment
score: 0
has text: If you code is working [codereview.se] may be a better place to ask. Remember to read their help center before asking.
comment on: http://stackoverflow.com/q/49104556
type: QuestionComment

http://stackoverflow.com/comment/98432372
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48986874
has text: Same question and looking forward for solutions
score: 0

http://stackoverflow.com/comment/85006980
type: QuestionComment
has text: [os.path.exists()](https://docs.python.org/2/library/os.path.html#os.path.exists)
comment on: http://stackoverflow.com/q/49000893
score: 0
type: Comment

http://stackoverflow.com/q/49077702
answer count: 1
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/20375561
has comment: http://stackoverflow.com/comment/85161525
tagged with: pandas
tagged with: python
tagged with: python-3.x
has body: I'm trying to join 2 dataframes in a kind of strange way and was wondering if anyone has any advice. My first data frame looks like this, call it df1: 2nd one looks like, call it df2: I want my final output to merge each team's stats next to their respective names in the games dataframe. A brute force way I thought of doing this was to change the name of the TEAM column in df1 to Home, join it on that. Then, change the TEAM column to Visitor and join it on that too but I feel their should be an easier way. Can anyone give me advice on this, thanks!
duplicate of: http://stackoverflow.com/q/53645882
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: join
score: 1
has title: Joining 2 dataframes in pandas with different column names
tagged with: dataframe
has comment: http://stackoverflow.com/comment/85161430
linked to: http://stackoverflow.com/q/53645882
has answer: http://stackoverflow.com/a/49077774

http://stackoverflow.com/a/48964894
score: 0
answers question: http://stackoverflow.com/q/48964787
type: Answer
upvote count: 1
downvote count: 1
has body: Regex: \n^(?!;500) Details: ^ Asserts position at start of a line (?!) Negative Lookahead Python code: text = open(r'C:\....txt').read() r = re.compile(r'\n^(?!;500)', re.M) text = r.sub(';', text) Output: ;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”;;” 6,291.00”;; ;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”;;” 6,991.00”;; Demo code

http://stackoverflow.com/comment/121885262
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49169125
has text: ERROR: Could not find a version that satisfies the requirement tensorflow==1.5.0

http://stackoverflow.com/q/49098380
has comment: http://stackoverflow.com/comment/85202177
favorite count: 0
has answer: http://stackoverflow.com/a/49098744
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49098430
possible better answer: http://stackoverflow.com/a/49098744
has title: Pandas: condense survey results
answer count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/49098430
has comment: http://stackoverflow.com/comment/85202269
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has body: I have survey results that have the following format: Lab Shepherd Poodle Frisky Sleepy Hungry 0 NaN NaN Yes Yes NaN NaN 1 Yes NaN NaN NaN NaN Yes 2 NaN Yes NaN NaN Yes NaN I would like to transform my dataframe to the following: Breed Disposition 0 Poodle Frisky 1 Lab Hungry 2 Shepherd Sleepy What is the most effective way to accomplish this? Groupby? Pivot? Is there any advantage to replacing every instance of 'Yes' with 'True' and use Boolean tests? Thanks in advance. DataFrame code follows, for ease of answering. d = [['', '','Yes','Yes','',''],['Yes', '','','','','Yes'],['','Yes','','','Yes','']] df = pd.DataFrame(data=d,columns=['Lab','Shepherd','Poodle','Frisky','Sleepy','Hungry']) df.replace(r'^\s*$', np.nan, regex=True, inplace = True)
score: 1

http://stackoverflow.com/comment/85193720
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49094280
has text: Please indent your code properly. And the statement `mylinks[i]` doesn't seem to do anything. Also provide the URL you're using.

http://stackoverflow.com/comment/85076747
has text: The problem seems to be that your decorator can't see class variables, i.e. `self` is not recognised.
comment on: http://stackoverflow.com/a/49034926
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49040123
score: 1
type: Question
has comment: http://stackoverflow.com/comment/85146572
tagged with: expect
downvote count: 0
has comment: http://stackoverflow.com/comment/85089082
tagged with: pexpect
accepted answer: http://stackoverflow.com/a/49042132
has body: This is sort of a clunky question as I can't figure out a good way to describe it, but in expect you can do something like this: interact { \001 {do_something} \003 {do_something_else} "?" { set timeout 1 expect_user { "?" {send "?"} timeout {send_user "show a menu of the things you can do"} } stty raw -echo set timeout 60 } \035 {send "^]" send "quit\r" send_user "\n" exit } } which would create an interactive session where the user could go about business as usual, but upon pressing keyboard combos (ctrl+a, ctrl+c, ctrl+e, ?, etc) execute actions or display text describing the possible shortcuts. I'm trying to update a number of scripts to python &amp; pexpect but haven't been able to figure out if this is possible in pexpect. I tried putzing around with an input filter but it seems this isn't really the 'right' place to do it, or maybe I just can't seem to find any good examples of it in action. @pynexj: tried your script, though I'm not getting anything on stdout from the ctrl commands. 16:51:16 ~/scripts $ p3 testInputFilter.py | tee testInput.txt 16:51:19 ~/scripts $ ps u USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND usr 45721 0.0 0.0 109620 1876 pts/1 Ss 16:49 0:00 -ksh usr 46622 0.0 0.0 108436 1776 pts/1 S 16:51 0:00 bash usr 46734 5.5 0.0 135728 7688 pts/1 S+ 16:51 0:00 python3.6 testI usr 46735 0.0 0.0 100912 632 pts/1 S+ 16:51 0:00 tee testInput.t usr 46736 0.0 0.0 108336 1692 pts/5 Ss 16:51 0:00 /bin/bash --nor usr 46759 0.0 0.0 110236 1132 pts/5 R+ 16:51 0:00 ps u 16:51:21 ~/scripts $ ^C 16:51:42 ~/scripts $ exit 16:51:43 ~/scripts $ cat testInput.txt 16:51:19 ~/scripts $ ps u USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND usr 45721 0.0 0.0 109620 1876 pts/1 Ss 16:49 0:00 -ksh usr 46622 0.0 0.0 108436 1776 pts/1 S 16:51 0:00 bash usr 46734 5.5 0.0 135728 7688 pts/1 S+ 16:51 0:00 python3.6 testI usr 46735 0.0 0.0 100912 632 pts/1 S+ 16:51 0:00 tee testInput.t usr 46736 0.0 0.0 108336 1692 pts/5 Ss 16:51 0:00 /bin/bash --nor usr 46759 0.0…
has title: Creating interactive options in pexpect
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/43371249
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49042132
linked to: http://stackoverflow.com/q/49069887

http://stackoverflow.com/q/48979245
has body: I want to split up a list of lists ((A,1,2,3),(B,4,5,6),(C,7,8,9)) into: (A,1) (A,2) (A,3) (B,4) (B,5) ... I tried rdd.flatMapValues(lambda x: [x]) but it just gave me the first values. Then I wrote a little python function: item_index = [] for list in master_list: for item in list: item_index.append((list[0],item)) But I didn't realize you can't pass an RDD into it. Any suggestions would be great.
score: 1
type: AnsweredQuestion
tagged with: pyspark
type: Question
upvote count: 1
has title: Splitting up an RDD
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48980912
accepted answer: http://stackoverflow.com/a/48980912
tagged with: apache-spark
tagged with: python
tagged with: rdd

http://stackoverflow.com/q/49020725
has comment: http://stackoverflow.com/comment/85047461
has title: Django refuses to cascade on delete
has comment: http://stackoverflow.com/comment/85046828
score: 0
tagged with: cascade
has comment: http://stackoverflow.com/comment/85046763
tagged with: postgresql
has body: Django 1.9 with PostgreSQL. I have a model that looks like this: class MyCrossModel(models.Model): one_thing = models.ForeignKey('OneThing', on_delete=models.CASCADE) other_thing = models.ForeignKey('OtherThing', on_delete=models.CASCADE) When I go to delete one of these in the database, it cascade-deletes the one_thing, but does not cascade_delete the other_thing. Scouring the Django docs but cannot find any mention of this behavior.
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85116625
type: Question
has comment: http://stackoverflow.com/comment/85116662

http://stackoverflow.com/q/49114732
answer count: 1
has comment: http://stackoverflow.com/comment/85234618
has answer: http://stackoverflow.com/a/49114882
has title: Python numpy floating point array precision
tagged with: precision
has body: I am trying to solve for SVM optimisation problem using Pegasos mini-batch algorithm (as in Fig 2) from this link: http://www.cs.huji.ac.il/~shais/papers/ShalevSiSrCo10.pdf #X: m*n matrix with m examples and n features per example (m=4000 and n=784 in my case), Y: m length vector containing 1 or -1 for each example, l: lambda as given in algorithm (l=1 in my code), itr: number of iterations, k: size of batch (100) in my case def pegasos(X,Y,l,n,m,itr,k): w = np.zeros((1,n),dtype=np.float32) print m, n diff = 0.0 for t in range(1,itr+1): A = random.sample(range(1,m),k) total = np.zeros((1,n),dtype=np.float32) eta = 1/(l*t) for i in A: x = X[i] y = Y[i] p = y*(np.dot(w,x.T)) if p &lt; 1: p1 = y*x total = np.add(total,p1) #update rule w = np.add((w*(1-(1/t))) , (eta*total*(1/k))) return w My dataset is in such a way that when my variable total is computed, I get mostly 0s but there are a few values in the order of 10^(-1) to 10^(-5). As soon as total is multiplied by (eta/k) at the update rule, all the values become 0. and hence at every iteration the w I obtain is 0. which should not be the case. I have tried ways to increase the precision of my floats but they don't seem to work at all. When I use basic Pegasos algorithm (as given in Fig 1 in the above link), I don't face any problem, thus my dataset is not utterly weird. Any help regarding this issue would be highly appreciated :)
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49114882
tagged with: svm
type: Question
tagged with: numpy
score: 0

http://stackoverflow.com/q/48998086
upvote count: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48998406
has comment: http://stackoverflow.com/comment/85002297
answer count: 1
tagged with: arrays
has title: 2d array compare to 1d array returns 2d array
favorite count: 0
has answer: http://stackoverflow.com/a/48998406
tagged with: python
has body: I am trying to compare a 1D array element-wise to a 2D array, and returns the elements of the 2D array which fulfils the condition in a 2D array form without using a for loop. Preferably using numpy or quicker method. a = range(1,10) Tna = np.random.choice(a, size=[250,10,1000], replace=True) sum_Ta = np.sum(Tna, axis = 1) percent = np.percentile(sum_Ta, 5, axis =0) Now I would like to get a 2D array which contains the elements of sum_Ta if the elements are smaller the percent. Such that 250 elements of sum_Ta are comparing with 1 element of percent for 1000 times. Originally I can do, ES = sum_Ta[sum_Ta &lt; percent[:,None]], but it only gives me a 1D array, not a 2D array.
score: 2
type: AnsweredQuestion
tagged with: elementwise-operations
downvote count: 0
tagged with: machine-learning
type: Question

http://stackoverflow.com/q/49096749
linked to: http://stackoverflow.com/q/35861482
has comment: http://stackoverflow.com/comment/85198790
has comment: http://stackoverflow.com/comment/85202327
downvote count: 0
answer count: 1
favorite count: 0
tagged with: keyerror
has answer: http://stackoverflow.com/a/49097052
accepted answer: http://stackoverflow.com/a/49097052
tagged with: exception
tagged with: python
has comment: http://stackoverflow.com/comment/85201932
upvote count: 13
has body: Python's built-in exception documentation defines LookupError as: The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup(). Should this base class be used only when catching try sections that access dictionaries using both indices and keys when one wants to shorthand catching both, or is there another case where you would use it?
tagged with: lookup
type: AnsweredQuestion
has title: When should I raise LookupError in python?
has comment: http://stackoverflow.com/comment/85202160
score: 13
linked to: http://stackoverflow.com/q/4326658
type: Question

http://stackoverflow.com/comment/85025224
type: QuestionComment
has text: @BryanOakley True, but that's modifying the structure. If adding widgets for layout reasons then it's trivial to achieve the same layout with pack as well. But that's stepping into rewriting the code, hence I reached my concl. of _"Rewrite the entire thing with better struct.(at which point it should be trivial to have a layout using both grid or pack), or have a quick fix using place(which is while easier to understand not exactly the long-term solution)."_ I figured if OP wanted to learn the long-term solution they'd ask more of a conceptual question ins. of which I think to be an exact one.
comment on: http://stackoverflow.com/q/49007295
score: 0
type: Comment

http://stackoverflow.com/comment/85154026
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49074117
has text: The problem is in 2nd if condition. if i+ 1 < len(n) and (n[i] == n[i + 1]) and (n[i + 1] <= len(n)):

http://stackoverflow.com/comment/85181115
comment on: http://stackoverflow.com/a/49087609
type: Comment
has text: We are getting too deep in this argument for the comment section. Especially for a detail that technical.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85050836
comment on: http://stackoverflow.com/q/49022718
score: 0
type: Comment
type: QuestionComment
has text: you need to import like this in your __init__ file: "from APIService import routes" instead of "from app import routes".

http://stackoverflow.com/comment/85115479
type: AnswerComment
type: Comment
score: 1
has text: Thks for your answer but it seems very costly to do it
comment on: http://stackoverflow.com/a/49055403

http://stackoverflow.com/a/49068687
has comment: http://stackoverflow.com/comment/85142586
upvote count: 1
has body: For a start, search_list is an attribute of the Profile, not the User. However this will not do what you want, since search_list and shopping_basket are class attributes and will therefore be shared by all Profiles. Do not do this. To store arbitrary data, use the session.
downvote count: 0
has comment: http://stackoverflow.com/comment/85142181
answers question: http://stackoverflow.com/q/49068613
has comment: http://stackoverflow.com/comment/85142990
type: Answer
score: 1

http://stackoverflow.com/a/49010155
type: Answer
has comment: http://stackoverflow.com/comment/85025195
accepted answer of: http://stackoverflow.com/q/49007740
downvote count: 0
answers question: http://stackoverflow.com/q/49007740
score: 1
has comment: http://stackoverflow.com/comment/85057912
has comment: http://stackoverflow.com/comment/85039892
type: AcceptedAnswer
upvote count: 1
has body: you can use glob.glob() to get the contents of the directory as a list, then use a for loop to create a figure for each file: import glob # assuming you want to go ove the current working directory files = glob.glob('RawData*.csv') for f in files: values = pd.read_csv(f) slope, intercept, r_value, p_value, std_err = stats.linregress(values['Displacement'],values['Force']) ax = sns.regplot(x="Displacement", y="Force", data=values, color='b', line_kws={'label':"y={0:.1f}x+{1:.1f}".format(slope,intercept)}) ax.legend() plt.show()
has comment: http://stackoverflow.com/comment/85024757

http://stackoverflow.com/comment/85133393
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49063795
has text: Thank you oh so very much! I appreciate it a lot!

http://stackoverflow.com/comment/84997382
comment on: http://stackoverflow.com/q/48995831
type: Comment
type: QuestionComment
has text: It seems like `at` and `iat` do not support MultiIndex but they don't raise appropriate errors when called on a MultiIndex: https://github.com/pandas-dev/pandas/issues/9259
score: 3

http://stackoverflow.com/comment/85127695
type: QuestionComment
has text: Welcome to SO! Please provide a **[mcve]**. Keep word in this situation is *Minimal*.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49061132

http://stackoverflow.com/q/48966973
upvote count: 4
has answer: http://stackoverflow.com/a/48967054
answer count: 3
downvote count: 0
favorite count: 0
has title: Proper use of decorators
has comment: http://stackoverflow.com/comment/84939715
tagged with: python
accepted answer: http://stackoverflow.com/a/48967054
tagged with: python-decorators
has answer: http://stackoverflow.com/a/48967126
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84939754
has comment: http://stackoverflow.com/comment/84939725
has answer: http://stackoverflow.com/a/48967004
has body: I have just started to use decorators in Python and I'm not sure to understand how to correctly use it. Let's say I have this code : def viable_decorator(fonction_viable): def viable(sequences, pos): codons = [seq[pos:pos+3] for seq in sequences] return not any("-" in codon for codon in codons) return viable @viable_decorator def viable(sequences, pos): codons = [seq[pos:pos+3] for seq in sequences] return not all("-" in codon for codon in codons) sequncess = ["---aaacacaacaacaaat", "------aaacacacac---", "aaggcggaggcgg---ggg",] print viable(sequences, 0) My objective is to be able to use alternatively the two versions of the function viable(), according to the situation. Is this how decorators are supposed to work ? And if yes, how do I determine the choice of the viable() function ? Because for now, in this code, the decorator is always called. Thanks in advance.
type: Question
possible better answer: http://stackoverflow.com/a/48967004
score: 4

http://stackoverflow.com/comment/85078666
comment on: http://stackoverflow.com/a/49036836
type: Comment
has text: Why re? for such a small thing.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49039436
answer count: 5
has title: How to import a module from a different folder?
possible better answer: http://stackoverflow.com/a/49039555
tagged with: python-module
tagged with: python
accepted answer: http://stackoverflow.com/a/49039535
tagged with: python-packaging
has answer: http://stackoverflow.com/a/79017209
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78375277
linked to: http://stackoverflow.com/q/4383571
tagged with: python-import
linked to: http://stackoverflow.com/q/14132789
downvote count: 0
score: 75
has answer: http://stackoverflow.com/a/49039555
upvote count: 75
favorite count: 0
has answer: http://stackoverflow.com/a/72021489
tagged with: python-3.x
has body: I have a project which I want to structure like this: myproject ├── api │ ├── __init__.py │ └── api.py ├── backend │ ├── __init__.py │ └── backend.py ├── models │ ├── __init__.py │ └── some_model.py └── __init__.py Now, I want to import the module some_model.py in both api.py and backend.py. How do I properly do this? I tried: from models import some_model but that fails with ModuleNotFoundError: No module named 'models'. I also tried: from ..models import some_model which gave me ValueError: attempted relative import beyond top-level package. What am I doing wrong here? How can I import a file from a different directory, which is not a subdirectory?
has answer: http://stackoverflow.com/a/49039535

http://stackoverflow.com/q/49040720
score: 0
tagged with: elasticsearch
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49041134
accepted answer: http://stackoverflow.com/a/49041134
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: change JSON elasticsearch query to python
has body: I have been using basic queries in python for elasticsearch like this: from elasticsearch import Elasticsearch from elasticsearch_dsl import Search es = Elasticsearch() def someView(request): s = Search().query("regexp", title_en="someword.*") response = s.execute() I would like to combine a query to check if someword exists in either of the fields "title_en" or "text_en" Any idea how to accomplish this? In this link I saw an example of a bool query using JSON, but I don´t understand how something similar could be done with python code. { "query": { "bool" : { "must" : { "term" : { "user" : "kimchy" } }, "filter": { "term" : { "tag" : "tech" } }, "must_not" : { "range" : { "age" : { "gte" : 10, "lte" : 20 } } }, "should" : [ { "term" : { "tag" : "wow" } }, { "term" : { "tag" : "elasticsearch" } } ], "minimum_should_match" : 1, "boost" : 1.0 } } }

http://stackoverflow.com/comment/85064922
score: 0
comment on: http://stackoverflow.com/q/49030147
type: Comment
type: QuestionComment
has text: Dear Aparna, welcome on StackOverflow. Please read https://stackoverflow.com/help/on-topic. The question should include all the context within the question itself, and since you have discovered the similar question, you may want to explain why the answer doesn't work for you.

http://stackoverflow.com/a/49026823
has body: I don't really understand how you want to order your parameters but the idea is to have a list of tuples because your function takes 2 arguments, so something like this : p.map(f, [(1, 4), (2, 5), (3, 6)]) and make f take a tuple as argument def f(t): return t[0] * t[1]
answers question: http://stackoverflow.com/q/49026675
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/84981142
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48984627
type: Comment
has text: *"Do I need to use "select"?"* - Do you even understand what you are trying to achieve with the code or did you just copy the code from somewhere but don't understand it?

http://stackoverflow.com/a/49052374
has comment: http://stackoverflow.com/comment/85109670
accepted answer of: http://stackoverflow.com/q/49051853
has body: How about the following: import pandas as pd df = pd.DataFrame({'Date': ['2014-12-30 23:00:00','2014-12-30 23:15:00','2014-12-30 23:30:00','2014-12-30 23:45:00','2014-12-31 00:00:00']}) DFHolidays = pd.DataFrame({'NAME': ['Neujahr', 'Heilige Drei Könige', 'Karfreitag', 'Ostersonntag', 'Ostermontag', '1. Mai', 'Erster Weihnachtsfeiertag', 'Zweiter Weihnachtsfeiertag'], 'DATE': ['2014-01-01','2014-01-06','2014-04-18','2014-04-20','2014-04-21','2014-05-01','2015-12-25','2015-12-26']}) # Ensure all dates are actually dates df['Date'] = pd.to_datetime(df['Date']) DFHolidays['DATE'] = pd.to_datetime(DFHolidays['DATE']) DFHolidays.set_index('NAME', inplace=True) # Loop over each holiday, apply the calculation for holiday_name, date in DFHolidays['DATE'].to_dict().items(): df[holiday_name] = date - df['Date'] This returns, with the sample data given: Date Neujahr Heilige Drei Könige \ 0 2014-12-30 23:00:00 -364 days +01:00:00 -359 days +01:00:00 1 2014-12-30 23:15:00 -364 days +00:45:00 -359 days +00:45:00 2 2014-12-30 23:30:00 -364 days +00:30:00 -359 days +00:30:00 3 2014-12-30 23:45:00 -364 days +00:15:00 -359 days +00:15:00 4 2014-12-31 00:00:00 -364 days +00:00:00 -359 days +00:00:00 Karfreitag Ostersonntag Ostermontag \ 0 -257 days +01:00:00 -255 days +01:00:00 -254 days +01:00:00 1 -257 days +00:45:00 -255 days +00:45:00 -254 days +00:45:00 2 -257 days +00:30:00 -255 days +00:30:00 -254 days +00:30:00 3 -257 days +00:15:00 -255 days +00:15:00 -254 days +00:15:00 4 -257 days +00:00:00 -255 days +00:00:00 -254 days +00:00:00 1. Mai Erster Weihnachtsfeiertag Zweiter Weihnachtsfeiertag 0 -244 days +01:00:00 359 days 01:00:00 360 days 01:00:00 1 -244 days +00:45:00 359 days 00:45:00 360 days 00:45:00 2 -244 days +00:30:00 359 days 00:30:00 360 days 00:30:00 3 -244 days +00:15:00 359 days 00:15:00 360 days 00:15:00 4 -244 days +00:00:00 359 days 00:00:00 360 days 00:00:00 With changed sample data Understanding that the year of the data is important, we could do the followi…
has comment: http://stackoverflow.com/comment/85110021
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49051853

http://stackoverflow.com/q/48991909
has comment: http://stackoverflow.com/comment/84989472
has title: Python calling function in an function from another function
has comment: http://stackoverflow.com/comment/84989043
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/84988738
upvote count: 0
has comment: http://stackoverflow.com/comment/84989141
score: -7
has comment: http://stackoverflow.com/comment/84993354
has comment: http://stackoverflow.com/comment/85003714
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85003589
has body: I want to call 1 precise function in another function from another function def exemple(): def dostuff1(): print('Stuff 1') def dostuff2(): print('Stuff 2') def dostuff3(): print('Stuff 3') def training(): #want to call ONLY Dostuff2
has answer: http://stackoverflow.com/a/48992086
has comment: http://stackoverflow.com/comment/84989644
tagged with: python
has comment: http://stackoverflow.com/comment/84989587
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17395338
has answer: http://stackoverflow.com/a/48992043
has comment: http://stackoverflow.com/comment/84989539
downvote count: 7
type: Question
accepted answer: http://stackoverflow.com/a/48992086
possible better answer: http://stackoverflow.com/a/48992043

http://stackoverflow.com/comment/85225419
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49109600
type: Comment
has text: A TypeError: TypeError: arguments did not match any overloaded call:

http://stackoverflow.com/q/49103579
tagged with: python-typing
favorite count: 0
type: Question
tagged with: python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/53448499
type: UnansweredQuestion
has body: Today I was introduced to multiple ways of using static type checking in Python (by the the Coconut tutorial). It lists python 3.5 type hints, python 3.6 variable annotations, and MyPy. I then found another, from Google, called pytype. Do these alternatives conflict? Does any of them rely on any of the others? Does any (subset) of them render any of the others unnecessary?
has title: Static type checking in Python: Conflicting alternatives?
downvote count: 0
score: 1

http://stackoverflow.com/a/49102970
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90205522
accepted answer of: http://stackoverflow.com/q/49079990
score: 1
answers question: http://stackoverflow.com/q/49079990
upvote count: 1
has body: Compiling tensorflow from source solved the problem, so it seems my system wasn't supported.
type: AcceptedAnswer

mat
tags question: http://stackoverflow.com/q/48970785
type: Tag
tag name: mat
tags question: http://stackoverflow.com/q/49038022

http://stackoverflow.com/comment/85211929
type: QuestionComment
comment on: http://stackoverflow.com/q/49103333
type: Comment
has text: @EricPostpischil it's a number with nearly a million digits, not "nearly a number with a million digits" :)
score: 1

http://stackoverflow.com/q/49075036
answer count: 1
tagged with: tkinter-canvas
tagged with: frame
favorite count: 0
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Python Tkinter Frame flashing with Scrollbar
has body: I'm attempting to create a level selection menu of sorts for a terminal-based game I'm making. I had it sorting levels into columns of ten, but it occured to me that the menu would get very wide as more levels are added. Instead, I'm trying to make an alphabetical list that can be scrolled through. I've followed several posts' advice about making a scrollable frame, and I've run into a problem I haven't seen before: The window keeps flashing and spazzing out. It only occurs one I add the line indicated below, but that line also is the one that makes the level buttons appear. def show_levels(self, frames): self.menu_title = tk.Label(self, text=" Nonstop Robot ", fg="blue" ) if frames: self.frame_levels = tk.Frame(self, relief="sunken", width=50, height=100 ) self.level_canvas = tk.Canvas(self.frame_levels) self.level_list = tk.Frame(self.level_canvas) self.level_scroll = tk.Scrollbar(self.frame_levels, orient="vertical", command=self.level_canvas.yview ) self.level_canvas.configure(yscrollcommand=self.level_scroll.set) self.frame_menu = tk.Frame(self) def level_bind(event): self.level_canvas.configure( scrollregion=self.level_canvas.bbox("all"), width=70, height=200 ) self.level_buttons = [] """ Code that adds the buttons to all the frames. """ for b in self.level_buttons: b.pack() if frames: self.level_scroll.pack(side="right", fill="y") self.level_canvas.pack(side="left") self.level_canvas.create_window((0, 0), window=self.frame_levels, anchor="nw" ) self.frame_levels.bind("&lt;Configure&gt;", level_bind) self.frame_levels.pack(side="bottom") self.level_list.pack() # This is the line in question self.frame_menu.pack(side="top") self.menu_title.pack() I removed the code that actually creates all the buttons, since it's very long. If needed, I can add it.
tagged with: scrollbar
has comment: http://stackoverflow.com/comment/85155976
type: Question
accepted answer: http://stackoverflow.com/a/49075281
score: -2
downvote count: 2
has answer: http://stackoverflow.com/a/49075281

http://stackoverflow.com/a/49101636
has comment: http://stackoverflow.com/comment/85219711
answers question: http://stackoverflow.com/q/49084864
has comment: http://stackoverflow.com/comment/85220324
accepted answer of: http://stackoverflow.com/q/49084864
has comment: http://stackoverflow.com/comment/85222005
type: Answer
upvote count: 2
has body: First of all, based on the project structure you've provided, you're not specifying the package_data correctly. If goosempl is a package and stylelib a directory inside it containing the mplstyle files (what I assume from your code), then your package_data configuration line should be: package_data = {'goosempl': ['stylelib/goose.mplstyle']}, As described in Building and Distributing Packages with Setuptools: The package_data argument is a dictionary that maps from package names to lists of glob patterns. The globs may include subdirectory names, if the data files are contained in a subdirectory of the package. So your package is goosempl and stylelib/goose.mplstyle is the file to be included in package data for goosempl. Your second issue (No such file or directory) is simple: in the copy_style() function, you never check if the parent directory of the file exists before writing the file. You should be able to reproduce this locally by removing the directory /home/&lt;user&gt;/.config/matplotlib/stylelib/ (or moving it temporarily). The fix is also quite simple, actually there are lots of them. Use whatever you want to create missing directories. distutils.dir_util.mkpath is suitable for both python2 and python3: for fname in files: path = os.path.join(matplotlib.get_configdir(), fname) distutils.dir_util.mkpath(os.dirname(path)) My preferred one is using pathlib, but it is available only since Python 3.4: for fname in files: path = pathlib.Path(matplotlib.get_configdir(), fname) path.parent.mkdir(parents=True, exist_ok=True)
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85218578
downvote count: 0

http://stackoverflow.com/q/49057443
type: Question
has comment: http://stackoverflow.com/comment/85119576
tagged with: rank
has body: Say that you have generated a tf idf value for each term in a document But when it comes to queries of multiple terms for example "hey well done" It'll return multiple tf idf values for each document, for example.... {2: [0.00527108433734938, 0.005271084337249398]} How would I rank this or which tf idf value would I use? Appreciate any responses, thank you!
tagged with: tf-idf
tagged with: subquery
has comment: http://stackoverflow.com/comment/85121987
score: 0
has title: How do you rank tf idf values to use
has comment: http://stackoverflow.com/comment/85120701
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49076125
tagged with: machine-learning
type: Question
score: 3
has comment: http://stackoverflow.com/comment/85194191
has title: Xgboost custom eval function using Xvars
has body: I want to build a custom evaluation function that xgb could use. It is essentially weighted average function across multiple groups. AFAIK from xgboost's documentation a sample custom eval call is somewhat like this : def custom_loss(yhat, dtrain): y = dtrain.get_label() return 'mae', mean_absolute_error(np.exp(y)-shift, np.exp(yhat)-shift) What I would want to pass with this is my dataframe as well. so the function call could be something like : def custom_loss(yhat, dtrain, X): y = dtrain.get_label() # Do some groupby with X and so on.... # Get wrmse here return 'wrmse', wrmse Where X could be my train/eval dataframe. Could someone please let me know if there is a way to achieve this ? My second point is that even if I am able to pass this "X"(train/eval dataframe) will it be a DMatrix object? If yes is there some way to extract columns from this ?
upvote count: 3
has comment: http://stackoverflow.com/comment/85192712
tagged with: xgboost
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85216498
answer count: 0
downvote count: 0

http://stackoverflow.com/q/49061324
tagged with: python
tagged with: discord
type: UnansweredQuestion
type: Question
tagged with: discord.py
tagged with: if-statement
has body: So, I am fairly new to this (30 minutes of experience as of right now) and an trying to get my Discord bot to display a message when one option of a command is used. But it just isn't working. async def cmd_warn(self, message, user_mentions, option): """ Usage: {command_prefix}warn [ spam | racism | discrimination | inappropriate | inpersonating | arguing | rudeness | harassment ] @UserName [@UserName2 ...] Warn users for spam / racism / discrimination / inappropriate / inpersonating / arguing / rudeness / harassment """ if not user_mentions: raise exceptions.CommandError("**Error:** No users listed.", expire_in=20) if option not in ['spam', 'racism', 'discrimination', 'inappropriate', 'inpersonating', 'arguing', 'rudeness', 'harassment']: raise exceptions.CommandError( '**Invalid reason:** Use !help warn for more info!' % option, expire_in=20 ) for user in user_mentions.copy(): if user.id == self.config.owner_id: print("[Commands:Warn] The owner cannot be warned (Tyler rigged).") user_mentions.remove(user) old_len = len(self.blacklist) if option in ['spam']: return Response('( %s ) You were warned for spam!') )
has title: How to respond with message if option is true
has comment: http://stackoverflow.com/comment/85127800
answer count: 1
has answer: http://stackoverflow.com/a/49070611
score: 0

http://stackoverflow.com/a/49113052
accepted answer of: http://stackoverflow.com/q/49112580
has comment: http://stackoverflow.com/comment/85231204
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49112580
type: AcceptedAnswer
downvote count: 0
has body: I see your question and am editing my answer You'll change the settings from "code" to "markdown": After changing the settings from "code" to "markdown" at the top of your notebook, you'll simply type whatever you want to type and press shift + enter.
type: Answer
has comment: http://stackoverflow.com/comment/85232180

http://stackoverflow.com/comment/85026302
type: QuestionComment
has text: @v.coder that will result in a TypeError, because os.path is a Module.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49010883

http://stackoverflow.com/comment/114629856
has text: Though it's an old thread, but would refer to https://stackoverflow.com/a/43989185/282155 which suggests `export PYTHONIOENCODING=UTF-8` before executing the python script in console.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49057682
type: QuestionComment

http://stackoverflow.com/a/48993752
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48993022
has body: Awk really is easier, isn't it? #!/usr/bin/env python files_count = 1 first_col = None with open('maria.txt') as maria: for line in maria: line = line.rstrip() columns = line.split() if columns[0] == first_col: print (line, file=current_out) else: first_col = columns[0] current_out = open(first_col+'.'+str(files_count), 'w') files_count+=1 print (line, file=current_out)
type: Answer
upvote count: 2

http://stackoverflow.com/comment/85182336
type: Comment
type: QuestionComment
has text: Mixing hsv and bgr values @api55
comment on: http://stackoverflow.com/q/49088100
score: 0

http://stackoverflow.com/a/49000413
score: 0
answers question: http://stackoverflow.com/q/49000392
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85006272
type: Answer
has body: If you don't need to format it, simply SaveFile.write(json.dumps(all_data)) but since you didn't change anything.. why dont just save the data instead? or you can access each value like you did with the tweet
accepted answer of: http://stackoverflow.com/q/49000392
has comment: http://stackoverflow.com/comment/85006391

http://stackoverflow.com/comment/85059908
type: Comment
score: 0
type: AnswerComment
has text: You need to change the delimiter in excel to ';' . I apologize that I don't have excel right now thus can't point out the steps to you.
comment on: http://stackoverflow.com/a/49024849

http://stackoverflow.com/comment/85159970
type: QuestionComment
comment on: http://stackoverflow.com/q/49075047
score: 1
has text: Are there more than one *var*? If not, no need for `apply` or *columnName*: `df['std'] = df.rolling(window=16).std(); df['var'] = df['var'] / df['std']`
type: Comment

http://stackoverflow.com/comment/85183259
type: QuestionComment
type: Comment
has text: Are your neurons linear ??
score: 0
comment on: http://stackoverflow.com/q/49088752

http://stackoverflow.com/q/49084202
has comment: http://stackoverflow.com/comment/85182400
accepted answer: http://stackoverflow.com/a/49117275
tagged with: python
tagged with: regex
tagged with: parsing
type: AnsweredQuestion
has title: How to parse multiple line catalina log in python - regex
score: 0
has comment: http://stackoverflow.com/comment/85198671
tagged with: catalina
type: Question
has answer: http://stackoverflow.com/a/49117275
has comment: http://stackoverflow.com/comment/85220047
has comment: http://stackoverflow.com/comment/85198329
answer count: 1
has body: I have catalina log: oct 21, 2016 12:32:13 AM org.wso2.carbon.identity.sso.agent.saml.SSOAgentHttpSessionListener sessionCreated WARNING: HTTP Session created without LoggedInSessionBean oct 21, 2016 3:03:20 AM com.sun.jersey.spi.container.ContainerResponse logException SEVERE: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException at ais.api.rest.rdss.Resource.lookAT(Resource.java:22) at sun.reflect.GeneratedMethodAccessor3019.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) I try to parse it in python. My problem is that I dont know how many lines there are in log. Minimum are 2 lines. I try read from file and when first line start with j,m,s,o etc. it mean it is first line of log, because this are first letters of months. But I dont know how to continue. When I stop read the lines ? When next line will starts with one of these letters ? But how I do that? import datetime import re SPACE = r'\s' TIME = r'(?P&lt;time&gt;.*?M)' PATH = r'(?P&lt;path&gt;.*?\S)' METHOD = r'(?P&lt;method&gt;.*?\S)' REQUEST = r'(?P&lt;request&gt;.*)' TYPE = r'(?P&lt;type&gt;.*?\:)' REGEX = TIME+SPACE+PATH+SPACE+METHOD+SPACE+TYPE+SPACE+REQUEST def parser(log_line): match = re.search(REGEX,log_line) return ( (match.group('time'), match.group('path'), match.group('method'), match.group('type'), match.group('request') ) ) db = MySQLdb.connect(host="localhost", user="myuser", passwd="mypsswd", db="Database") with db: cursor = db.cursor() with open("Mylog.log","rw") as f: for line in f: if (line.startswith('j')) or (line.startswith('f')) or (line.startswith('m')) or (line.startswith('a')) or (line.startswith('s')) or (line.startswith('o')) or (line.startswith('n')) or (line.startswith('d')) : logLine = line result = parser(logLine) sql = ("INSERT INTO ..... ") data = (result[0]) cursor.execute(sql, data) f.close() db.close() Best idea I have is read just two lines at a time. But that means dis…

http://stackoverflow.com/comment/85304146
type: Comment
has text: Lets say I have [1,2,3,4,5,6,7,8,9,10] elements and I do: `batch(2)` would I get `[1,2], [2,3][3,4]..` or `[1,2][3,4][5,6]..` ? My goal would be the former. I guess it would result in the latter which I do not want.
type: AnswerComment
comment on: http://stackoverflow.com/a/49140261
score: 0

http://stackoverflow.com/q/48967169
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48967501
upvote count: 3
has body: I have Time series data as numpy array. I want to generate Time delay embedding of data like this: Time Series is like this: [[ 1. 37.17] [ 2. 36.99] [ 3. 36.84] [ 4. 37.57] [ 5. 37.49] [ 6. 37.45] [ 7. 37.82] [ 8. 37.95] [ 9. 37.36] [ 10. 37.84] [ 11. 37.85] [ 12. 37.12]] Suppose my window size (w) = 4 and gap (g) = 2. We will pick every 3rd point till we get points = window size to form one 'w' dimensional point. For next 'w' dimensional point we shift the series by 1 and repeat the same process for shifted series. This will give us several 'w' dimensional points which will eventually be stored in 2D numpy array. We stop when we cant form 'w' dimensional point i.e. when we reach end of series. Then time delay embedding for this series should be: [[ 37.17 37.57 37.82 37.84] [ 37.99 36.49 36.95 37.85] [ 37.84 37.45 36.36 37.12]] We will stop at this particular point because for next point in 4 dimension we will run out of the fourth point. I have approximately 1600 points long time series and I want parameters w and g to be variable. The function will take 'w' and 'g' and time series as given and will spit out the Time Delay Embedding.
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48967501
answer count: 1
downvote count: 0
favorite count: 0
has title: Time Delay Embedding of Time Series in Python

http://stackoverflow.com/comment/85078821
has text: @stevendesu - thank you for experience of your test. Be free modify my answer with your another solution, because now I am only on phone. Thanks.
type: Comment
comment on: http://stackoverflow.com/a/49014062
score: 0
type: AnswerComment

http://stackoverflow.com/a/49120201
has body: Can you just do df.drop_duplicates().groupby(['studentid','subj','topic','lesson')
has comment: http://stackoverflow.com/comment/85248371
answers question: http://stackoverflow.com/q/49120130
has comment: http://stackoverflow.com/comment/85248517
score: 0
has comment: http://stackoverflow.com/comment/85246465
type: Answer
has comment: http://stackoverflow.com/comment/85248283
has comment: http://stackoverflow.com/comment/85248469

http://stackoverflow.com/q/49103854
tagged with: http://stackoverflow.com/tag/html
tagged with: python
downvote count: 1
type: Question
score: -1
has body: I am currently learning HTML in my Python class. My assignment is to ask the user for their name and a short bio of themselves and print it on a web-page. I believe my code is correct, I'm not too confused on that, but after I've created everything how do I see if it actually worked? When I try to open the file location with google chrome nothing happens. def main(): f = open('Userbio', 'w') f.write("&lt;html&gt;" + "\n") f.write("&lt;heads&gt;" + "\n") name = input("What is your name?") bio = input ("Please write a sentence about yourself!") f.write("&lt;naming&gt;" + "\n") f.write(name) f.write("/naming&gt;" + "\n") fout.write("&lt;/heads&gt;" + "\n") fout.write("&lt;/body&gt;" + "\n") fout.write("&lt;/html&gt;" + "\n") fout.close() f.close() main() Basically after this program is written and the user inputs their information I'm trying to figure out how to open the web page. This method works when I use a regular writer like notepad, I just save it and open it with chrome and I can see my webpage. But not Python?
has answer: http://stackoverflow.com/a/49103885
upvote count: 0
answer count: 1
favorite count: 0
has title: How can I view an HTML that I have written in Python?
type: UnansweredQuestion

http://stackoverflow.com/q/48976588
answer count: 1
has answer: http://stackoverflow.com/a/48976822
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84959067
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84958230
has body: I am analyzing some old code in python and found this somewhere from tools import bool_dir I tried searching it but could not find anything. All I know is that maybe it is deprecated now and weblib is used instead of it. Can anyone please tell me the usage of this bool_dir.
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/273192
score: -1
accepted answer: http://stackoverflow.com/a/48976822
has title: Usage of bool_dir in python "from tools import bool_dir"

http://stackoverflow.com/comment/84938451
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48966135
type: QuestionComment
has text: Is it 32-bit python , or 64-bit python? What operating-system runs the Db2-server?

recursion
type: Tag
tags question: http://stackoverflow.com/q/49063499
tags question: http://stackoverflow.com/q/49059247
tags question: http://stackoverflow.com/q/48989490
tags question: http://stackoverflow.com/q/49059681
tags question: http://stackoverflow.com/q/49086677
tags question: http://stackoverflow.com/q/49051378
tags question: http://stackoverflow.com/q/49042486
tags question: http://stackoverflow.com/q/49000947
tag name: recursion
tags question: http://stackoverflow.com/q/49075560
tags question: http://stackoverflow.com/q/49100254
tags question: http://stackoverflow.com/q/48996063
tags question: http://stackoverflow.com/q/49051781
tags question: http://stackoverflow.com/q/49065003
tags question: http://stackoverflow.com/q/49078127
tags question: http://stackoverflow.com/q/48964502
tags question: http://stackoverflow.com/q/48978957
tags question: http://stackoverflow.com/q/49099356

http://stackoverflow.com/comment/85008456
score: 0
has text: @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 I have mistakenly wrote `list_word` instead `list_of_words`. Thank you for correction.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49001670

http://stackoverflow.com/q/49014370
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/85033534
tagged with: pandas
has body: please I'm have a simple question but I can't see it answered anywhere. My starting point is a pandas dataframe with multiple columns. I need to select one of the columns by position and eventually convert this column to a series. df = pd.Dataframe(no.random.randn(20,2), columns=['a','b']) price = df.iloc[:,[1]] # this should give us a dataframe still I tried: price_series = pd.Series(price) but it doesn't work.
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: Convert a pandas dataframe single column into a pandas series
linked to: http://stackoverflow.com/q/14941097
type: Question
has comment: http://stackoverflow.com/comment/85033472
duplicate of: http://stackoverflow.com/q/14941097

http://stackoverflow.com/q/49002676
upvote count: 1
has body: if(stuckSomewhere()||lost() == true) { stuckSomewhere().stop(); lost().stop(); debugAvailableOptions(); } I'm pretty much newbie for python. I was exploring python but I'm unable to come to a solution for this snippet.
type: Question
accepted answer: http://stackoverflow.com/a/49003196
has comment: http://stackoverflow.com/comment/85009931
downvote count: 4
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49003196
score: -3
tagged with: python
type: AnsweredQuestion
has title: How to write the below snippet in python?

http://stackoverflow.com/q/49080605
has title: Subtracting matrix elements
score: 0
has comment: http://stackoverflow.com/comment/85166969
answer count: 1
has answer: http://stackoverflow.com/a/49080705
has comment: http://stackoverflow.com/comment/85166936
has body: Suppose I have one 4x3 matrix. I want to subtract every element in that matrix from each other. I've looked around TensorFlow documentation extensively (and on SO) and noticed that there is a tf.subtract operator. In adding, I know that there is tf.add_n operator which adds all input tensors. I'm new to TensorFlow and was wondering: is there such a subtraction operator which subtracts all input tensors and if not, can you please provide an example of the fastest way to do so? Example matrix tensor: [[0.10, 0.20], [0.20, 0.40]] so expanded as: 0.10 0.20 0.20 0.40 Desired subtraction: 0.10 - 0.20 - 0.20 - 0.40 with desired output as: -.7
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49080705
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/87826047
type: Comment
has text: @olive_tree Glad you found about the complication in training from scratch. You are open to use models that were trained on COCO dataset, you should think deepnets are a net that extracts the features from the image rather than a pattern matcher. So, even if you use medical data for fine-tuning on a coco pretrained model, in theory it should work.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49105854

http://stackoverflow.com/a/49051395
has comment: http://stackoverflow.com/comment/85111091
has comment: http://stackoverflow.com/comment/85108892
type: Answer
accepted answer of: http://stackoverflow.com/q/49049136
answers question: http://stackoverflow.com/q/49049136
has body: Working code from tkinter import* from tkinter import Tk, StringVar, ttk #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# import random import datetime import time; #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# start = Tk() start.geometry("100x600+0+0") start.title ("R.E.D Inventory Control System") #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# Heading = Frame(start, width = 1000, height = 100, bd = 10, relief = 'raise') Heading.pack(side = TOP) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# LowerHeading = Frame(start, width = 500, height = 100, bd = 20, relief = 'raise') LowerHeading.pack(side = BOTTOM) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# LMiddle = Frame(start, width = 500, height = 1000, bd = 12, relief = 'raise') LMiddle.pack(side = LEFT) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# RMiddle = Frame(start, width = 500, height = 1000, bd = 12, relief = 'raise') RMiddle.pack(side=RIGHT) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# Title = Label(Heading, font=('arial',40,'bold'), text = "R.E.D Inventory Control System", bd = …
score: 0
has comment: http://stackoverflow.com/comment/85109070
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85107556

data-science
tags question: http://stackoverflow.com/q/49090638
tags question: http://stackoverflow.com/q/49087869
tags question: http://stackoverflow.com/q/49088259
tags question: http://stackoverflow.com/q/48993412
tags question: http://stackoverflow.com/q/49083155
type: Tag
tags question: http://stackoverflow.com/q/49035107
tags question: http://stackoverflow.com/q/48989120
tags question: http://stackoverflow.com/q/49030479
tags question: http://stackoverflow.com/q/49072356
tags question: http://stackoverflow.com/q/49091145
tags question: http://stackoverflow.com/q/49015848
tags question: http://stackoverflow.com/q/49096990
tags question: http://stackoverflow.com/q/49087108
tag name: data-science
tags question: http://stackoverflow.com/q/49099293
tags question: http://stackoverflow.com/q/49006013

pycharm
tags question: http://stackoverflow.com/q/49023511
tags question: http://stackoverflow.com/q/49105469
tags question: http://stackoverflow.com/q/49095910
tags question: http://stackoverflow.com/q/49030636
tags question: http://stackoverflow.com/q/48968668
tags question: http://stackoverflow.com/q/49010193
tags question: http://stackoverflow.com/q/49081249
tags question: http://stackoverflow.com/q/49052983
tags question: http://stackoverflow.com/q/49007292
tags question: http://stackoverflow.com/q/48963665
tags question: http://stackoverflow.com/q/48981913
tag name: pycharm
tags question: http://stackoverflow.com/q/49095677
tags question: http://stackoverflow.com/q/49114180
tags question: http://stackoverflow.com/q/49077132
tags question: http://stackoverflow.com/q/49076072
tags question: http://stackoverflow.com/q/49035988
tags question: http://stackoverflow.com/q/49048520
tags question: http://stackoverflow.com/q/48969124
tags question: http://stackoverflow.com/q/49118799
tags question: http://stackoverflow.com/q/49100741
type: Tag
tags question: http://stackoverflow.com/q/49097715
tags question: http://stackoverflow.com/q/49089721
tags question: http://stackoverflow.com/q/49043362

http://stackoverflow.com/q/49074623
tagged with: string
score: 0
answer count: 1
tagged with: python-3.x
tagged with: python
has title: saving string to tarfile in python 3 throws unexpected end of data error
has body: I'm trying to open a tar.gz file full of json data, extract the text from them, and save them back to tar.gz. Here's my code in Python 3 thus far. from get_clean_text import get_cleaned_text # my own module import tarfile import os import json from io import StringIO from pathlib import Path def make_clean_gzip(inzip): outzip = "extracted/clean-" + inzip with tarfile.open(inzip, 'r:gz') as infile, tarfile.open(outzip, 'w:gz') as outfile: jfiles = infile.getnames() for j in jfiles: dirtycase = json.loads(infile.extractfile(j).read().decode("utf-8")) cleaned = get_cleaned_text(dirtycase) newtarfile = tarfile.TarInfo(Path(j).stem + ".txt") fobj = StringIO() fobj.write(cleaned) newtarfile.size = fobj.tell() outfile.addfile(newtarfile, fobj) However, this throws an OSError: unexpected end of data. (I've verified, incidentally, that all the strings I want to write are of non-zero length, and also verified that calling tell() on the file object returns the same value as calling len() on the string.) I found this prior SO, which suggested that the problem is that StringIO isn't encoded, so I swapped out BytesIO for StringIO and then fobj.write(cleaned.encode("utf-8")), but this still throws the same error. I also tried simply not setting the size on the TarInfo object, and that code ran, but created an archive with a bunch of empty files. What am I missing? Thanks!
accepted answer: http://stackoverflow.com/a/49074745
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/tar
type: Question
has answer: http://stackoverflow.com/a/49074745
linked to: http://stackoverflow.com/q/13988973
tagged with: gzip

http://stackoverflow.com/comment/85144869
comment on: http://stackoverflow.com/a/49068298
score: 0
type: AnswerComment
type: Comment
has text: Use `df.index = df.index.values.astype('datetime64[us]')`

http://stackoverflow.com/comment/85192494
type: Comment
type: QuestionComment
score: 1
has text: Because your dictionary has no key called `'key'`? It does have a key `'server'`, which is why that one works. You will have to use the django equivalent of `data[key]`, instead of `data['key']`, which is what it is doing now.
comment on: http://stackoverflow.com/q/49093652

http://stackoverflow.com/q/49059610
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/62597878
tagged with: python
tagged with: pulseaudio
linked to: http://stackoverflow.com/q/62597878
answer count: 0
downvote count: 1
type: Question
upvote count: 5
score: 4
has body: I want to run pygame mixer inside systemd, i used this code as an example: from pygame import mixer import signal,sys,time def signal_handler(signal,frame): global inter inter=True sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def play_audio_file(fname): if mixer.get_init() != None: mixer.quit() mixer.init() mixer.Sound(fname).play() while True: play_audio_file('/home/mohammad/tmp/ding.wav') time.sleep(0.5) and the following systemd service file: [Unit] Description=pygame mixer test Wants=network-online.target After=network-online.target [Service] Environment=VIRTUAL_ENV=/home/mohammad/env Environment=PATH=/home/mohammad/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin ExecStart=/usr/bin/python /home/mohammad/tmp/service.py WorkingDirectory=/home/mohammad/ StandardOutput=inherit StandardError=inherit Restart=always User=mohammad [Install] WantedBy=multi-user.target When I start the service without other programs the script works as expected (the wav file play repeatedly) but when I start a program that output sound and then start the service I get this error: Mar 02 01:12:04 mohammad-pc python[3415]: ALSA lib pcm_dmix.c:1099:(snd_pcm_dmix_open) unable to open slave Mar 02 01:12:04 mohammad-pc python[3415]: Traceback (most recent call last): Mar 02 01:12:04 mohammad-pc python[3415]: File "/home/mohammad/tmp/service.py", line 20, in Mar 02 01:12:04 mohammad-pc python[3415]: play_audio_file('/home/mohammad/tmp/ding.wav') Mar 02 01:12:04 mohammad-pc python[3415]: File "/home/mohammad/tmp/service.py", line 14, in play_audio_file Mar 02 01:12:04 mohammad-pc python[3415]: mixer.init() Mar 02 01:12:04 mohammad-pc python[3415]: pygame.error: No available audio device This problem only appears on my manjaro linux machine running pulseaudio, but when I run the same code in my raspberrypi(raspbian strech) which runs alsa only without pulseaudio then the problem is resolved. I was able to solve the problem (on my manjaro machine of course) by passing t…
has title: pygame.error: > No available audio device when running pygame inside systemd with pulseaudio
tagged with: pygame
favorite count: 0
tagged with: alsa

http://stackoverflow.com/a/49117816
answers question: http://stackoverflow.com/q/49117648
type: Answer
has body: Dictionary comprehension objdict = {feature: getattr(obj, feature) for feature in features} You have to make sure the strings in features do match with the attribute name of the object.
score: 0

http://stackoverflow.com/comment/85243929
type: QuestionComment
has text: The problem comes also from ignoring the return value of cap read. see http://stackoverflow.com/questions/35242735/ddg#35245814 and try "/path to/RGB/I%d.jpg"
comment on: http://stackoverflow.com/q/49117586
type: Comment
score: 0

http://stackoverflow.com/q/49025737
has answer: http://stackoverflow.com/a/49025873
has body: I have have the following code: for i in alist: if i not in alist: result.append(i) I am not sure whether that would be O(n) or O(n^2), because of the in statement?
has comment: http://stackoverflow.com/comment/85056319
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85056487
favorite count: 0
tagged with: python
tagged with: big-o
type: UnansweredQuestion
has title: Working out the time complexity
upvote count: 1
downvote count: 1
type: Question

python-3.6
tags question: http://stackoverflow.com/q/49067070
tags question: http://stackoverflow.com/q/49088038
tags question: http://stackoverflow.com/q/49093956
tags question: http://stackoverflow.com/q/48971454
tags question: http://stackoverflow.com/q/48979771
tags question: http://stackoverflow.com/q/49087145
tags question: http://stackoverflow.com/q/49071831
tags question: http://stackoverflow.com/q/49058713
tags question: http://stackoverflow.com/q/49038137
type: Tag
tags question: http://stackoverflow.com/q/49061406
tags question: http://stackoverflow.com/q/48968668
tags question: http://stackoverflow.com/q/49023099
tags question: http://stackoverflow.com/q/49036842
tags question: http://stackoverflow.com/q/48981243
tags question: http://stackoverflow.com/q/49001361
tags question: http://stackoverflow.com/q/48993459
tags question: http://stackoverflow.com/q/49061821
tags question: http://stackoverflow.com/q/48980611
tags question: http://stackoverflow.com/q/49075226
tags question: http://stackoverflow.com/q/49022163
tags question: http://stackoverflow.com/q/48975053
tags question: http://stackoverflow.com/q/49084650
tags question: http://stackoverflow.com/q/49031491
tags question: http://stackoverflow.com/q/49057888
tags question: http://stackoverflow.com/q/49100990
tag name: python-3.6
tags question: http://stackoverflow.com/q/49020826
tags question: http://stackoverflow.com/q/49015535
tags question: http://stackoverflow.com/q/48985154
tags question: http://stackoverflow.com/q/49082620
tags question: http://stackoverflow.com/q/49061171

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

http://stackoverflow.com/comment/131672714
has text: When I install opencv on raspbian OS, I also met some errors, but they can be solved using the website above. Maybe you can try it.
type: Comment
comment on: http://stackoverflow.com/a/49707904
score: 0
type: AnswerComment

http://stackoverflow.com/a/49061335
type: Answer
has body: Use super().__init__() not super.__init__()
accepted answer of: http://stackoverflow.com/q/49061295
answers question: http://stackoverflow.com/q/49061295
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48981308
score: 7
downvote count: 0
has body: Easy , if you do df'A','B'[df['B']=='two'] you will get: A B 2 foo two 4 foo two 5 bar two To filter on both A and B: df'A','B'[(df['B']=='two') &amp; (df['A']=='foo')] You get: A B 2 foo two 4 foo two and if you want all the columns : df[df['B']=='two'] you will get: A B C D 2 foo two 2 4 4 foo two 4 8 5 bar two 5 10
type: Answer
answers question: http://stackoverflow.com/q/48979561
upvote count: 7

http://stackoverflow.com/a/49003139
has body: with open("file1.txt","r") as file1: with open("file2.txt","r") as file2: print(file1.read() in file2.read()) You could try this python script
answers question: http://stackoverflow.com/q/49002956
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85018123
downvote count: 0
type: Answer

http://stackoverflow.com/q/49087407
has comment: http://stackoverflow.com/comment/85181828
favorite count: 0
has title: pyodbc on Azure
has answer: http://stackoverflow.com/a/49105747
type: Question
upvote count: 2
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/85186875
tagged with: azure-sql-database
linked to: http://stackoverflow.com/q/33725862
has comment: http://stackoverflow.com/comment/85181506
has comment: http://stackoverflow.com/comment/85181710
has comment: http://stackoverflow.com/comment/85182134
answer count: 1
has body: I have a python webapp in Azure which I would like to read from an SQLServer also in Azure in the same resource group. Following this example Connecting to Microsoft SQL server using Python, I have added pyodbc to my requirements.txt, the deployment to Azure fails complaining that it doesn't have the correct version of C++ redistributable (9.0) available. Is there anything that can be done about this, or is a different architecture required (and if so, which?)?
type: UnansweredQuestion
tagged with: azure
score: 2
downvote count: 0

http://stackoverflow.com/a/49060273
answers question: http://stackoverflow.com/q/49059920
has comment: http://stackoverflow.com/comment/85162331
has body: EDIT: I just noticed that message is only being used for the signature, and is not being included in the request. I think you probably need something like data = requests.get(url + report, data=message, headers=headers). Old, almost certainly incorrect theory is below: Since it works for an empty message, my guess is that it has to do with the byte encoding of the message. The utf-16 or utf-32 encodings of the empty message will be the same as the utf-8, but they will differ for non-empty messages. So perhaps try message.encode('utf-16') or message.encode('utf-32')? The API docs should describe this detail of how auth is done. Is it possible to link to the docs for the API, or is it internal?
has comment: http://stackoverflow.com/comment/85125664
has comment: http://stackoverflow.com/comment/85126073
score: 0
has comment: http://stackoverflow.com/comment/85157927
type: Answer

http://stackoverflow.com/comment/84980999
comment on: http://stackoverflow.com/q/48988038
score: 0
type: Comment
type: QuestionComment
has text: Can you [Boyer--Moore](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm)-search it?

http://stackoverflow.com/comment/84998462
has text: Thanks for your answers, the problem was that I defined it as `E=10,` I shouldn't have put ',' at the end!
type: AnswerComment
comment on: http://stackoverflow.com/a/48995994
score: 0
type: Comment

http://stackoverflow.com/comment/85183858
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49089165
score: 1
has text: you're not trying to remove anything

http://stackoverflow.com/q/49096884
type: Question
has answer: http://stackoverflow.com/a/49100219
tagged with: python-import
answer count: 2
score: 0
has title: Passing variables between files in a project without init
tagged with: python
type: UnansweredQuestion
has body: is in Python any way how to initialize the variable only once and then just import it into the remaining modules? I have following python project structure: api v1 init.py v2 init.py init.py logging.py logging.py: from raven import Client sentry = None def init_sentry(): global sentry sentry = 'some_dsn' api/init.py from app import logging logging.init_sentry() #run flask server (v1,v2) api/{v1,v2}/init.py from logging import sentry try: 1 / 0 except ZeroDivisionError: sentry.captureException() In files api/v1/init.py and api/v2/init.py a get a error NoneType on sentry variable. I know I can call init_sentry in all files when I use it, but I'm looking for a better way. Thanks
has answer: http://stackoverflow.com/a/49097407
tagged with: global-variables

http://stackoverflow.com/comment/85249362
comment on: http://stackoverflow.com/a/49079359
type: Comment
has text: @MichelleB., I think I figured out a way to log those network loads in **chrome** if you interested in this still.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48992406
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48992253
has comment: http://stackoverflow.com/comment/84989897
upvote count: 2
has body: Not sure if I get your question right, but this is the code what you are asking for. views.py: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['item'] = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}] return context template.html: {{ item.0.price }} Results in 15.52 If you want to loop over it you can do it like so: {% for i in item %} {{ i.price }} {% endfor %} After you have updated the question, I would do the following: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) item0 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}] item1 = [{'itemCode': 'BZ001', 'price': 12.55}, {'itemCode': 'BB01', 'price': 34.1}] import itertools context['zip_longest'] = itertools.zip_longest(item0, item1) return context template.html: {% for element in zip_longest %} {% for item in element %} {% if item %} {{ item.price }} &lt;br&gt; {% endif %} {% endfor %} {% endfor %} Results in: 15.52 12.55 31.2 34.1 1.2 In my opinion, it's nothing wrong with using zip_longest, since it yields the values from a generator.
score: 2

http://stackoverflow.com/comment/85100733
score: 0
type: AnswerComment
type: Comment
has text: Btw, I initially misread the question thinking that the OP wanted a decorator applied to _every_ function call, not just one particular function, and I pondered a solution based on [`sys.setprofile`](https://docs.python.org/3/library/sys.html#sys.setprofile). It's a rather overkill approach for a single function, but it could be a possible path to it too, I guess...
comment on: http://stackoverflow.com/a/49035754

http://stackoverflow.com/a/48964565
score: 6
has body: All exceptions are a subclass of BaseException, therefore all built-in exceptions should have an args attribute. args: The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message. The args tuple or string can be provided as the first argument when you raise the exception. try: raise ZeroDivisionError("error") except ZeroDivisionError as err: print(err) # prints "error" The err from except Exception as err: is the Exception instance, when you print(err), you're actually calling the __str__ method of the Exception. Most Exception class's __str__ return's args, since it's the default behaviour of BaseException; __str__ will return otherwise if the exception class override BaseException's __str__. When you raised a plain ZeroDivisionError, you provided no args, and ZeroDivisionError does not have a custom __str__ method, therefore it printed args by default, a.k.a args = None. As for your question: Isn't an exception came from raise, same as the a general expression? Yes. They are the same. try: raise ZeroDivisionError("division by zero") except ZeroDivisionError as err: print(err) This will output the same as 1/0. I went ahead and dig through the source code. // (integer division) and / (true division) have a slightly different error message. But basically they are defined as such: if (size_b == 0) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); return -1; } Whereas size_b is the divisor. As you can see, 1/0 or any division by zero raises a ZeroDivsionError with args set as "division by zero" or "integer division or modulo by zero" depending how you divide.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48964408
answers question: http://stackoverflow.com/q/48964408
has comment: http://stackoverflow.com/comment/84935306

http://stackoverflow.com/q/48988580
has body: Let's suppose that I have 3 python two-dimensional lists (data_1, data_2, data_3) of 10x5 dimensions. I want to make one list (all_data) from them with 30x5 dimensions. For now, I am doing this by applying the following: data_1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ..., [46, 47, 48, 49, 50]] data_2 = [[101, 102, 103, 104, 105], [106, 107, 108, 109, 110], ..., [146, 147, 148, 149, 150]] data_3 = [[201, 202, 203, 204, 205], [206, 207, 208, 209, 210], ..., [246, 247, 248, 249, 250]] all_data = [] for index, item in enumerate(data_1): all_data.append(item) for index, item in enumerate(data_2): all_data.append(item) for index, item in enumerate(data_3): all_data.append(item) If I simply do something like this: all_data.append(data_1) all_data.append(data_2) all_data.append(data_3) then I get a list of 3x10x5 which is not what I want. So can I create a 30x5 list by appending three 10x5 lists without using any for loop?
has answer: http://stackoverflow.com/a/48988644
tagged with: arrays
has answer: http://stackoverflow.com/a/48988653
upvote count: 1
accepted answer: http://stackoverflow.com/a/48988653
has title: How to append two-dimensional python list without for loop?
has answer: http://stackoverflow.com/a/48988659
has answer: http://stackoverflow.com/a/48988703
tagged with: append
favorite count: 0
has answer: http://stackoverflow.com/a/48988628
answer count: 5
tagged with: python
linked to: http://stackoverflow.com/q/716477
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84982033
type: Question
possible better answer: http://stackoverflow.com/a/48988644

http://stackoverflow.com/q/49039050
linked to: http://stackoverflow.com/q/2612802
duplicate of: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/85083503
has comment: http://stackoverflow.com/comment/85083502
has comment: http://stackoverflow.com/comment/85083426
favorite count: 0
has answer: http://stackoverflow.com/a/49039521
tagged with: python-3.x
upvote count: 2
has body: I'm trying to check the contents of a list for duplicates by storing the list in a second variable and removing one item from the list and then checking if there is still a copy of that item in the list. Here's what I've got: disposableList = list for i in disposableList: disposableList.remove(i) if i in disposableList: end = True The problem is when it removes i from disposableList it also removes it from List. Is there a way to do this without effecting the original list?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49039461
tagged with: python
downvote count: 1
score: 1
type: Question
answer count: 2
has title: Changing a disposable list without affecting the original Python

http://stackoverflow.com/comment/85103272
comment on: http://stackoverflow.com/a/49049517
score: 0
type: Comment
has text: You can also write a function that will handle your "execute" / "read_sql" assignment and add there error handling.
type: AnswerComment

http://stackoverflow.com/comment/85181620
type: AnswerComment
comment on: http://stackoverflow.com/a/49087609
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166161/discussion-between-olivier-and-isik-kaplan).
score: 0

http://stackoverflow.com/q/49119310
type: Question
has answer: http://stackoverflow.com/a/49119338
has comment: http://stackoverflow.com/comment/85244095
downvote count: 3
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
upvote count: 0
has title: Pandas - How to fill empty values with whatever value defined above
has body: Here is an example of the input: Here is an example of the output:

http://stackoverflow.com/q/49029530
has comment: http://stackoverflow.com/comment/85063294
tagged with: python
has comment: http://stackoverflow.com/comment/85064789
has body: I am reading a .dat file and the first few lines are just metadata before it gets to the actual data. A shortened example of the .dat file is below. &amp;SRS SRSRUN=266128,SRSDAT=20180202,SRSTIM=122132, fc.fcY=0.9000 &amp;END energy rc ai2 8945.016 301.32 6.7959 8955.497 301.18 6.8382 8955.989 301.18 6.8407 8956.990 301.16 6.8469 Or as the list: [' &amp;SRS\n', ' SRSRUN=266128,SRSDAT=20180202,SRSTIM=122132,\n', 'fc.fcY=0.9000\n', '\n', ' &amp;END\n', 'energy\trc\tai2\n', '8945.016\t301.32\t6.7959\n', '8955.497\t301.18\t6.8382\n', '8955.989\t301.18\t6.8407\n', '8956.990\t301.16\t6.8469\n'] I tried this previously but it : def import_absorptionscan(file_path,start,end): for i in range(start,end): lines=[] f=open(file_path+str(i)+'.dat', 'r') for line in f: lines.append(line) for line in lines: for c in line: if c.isalpha(): lines.remove(line) print lines But i get this error: ValueError: list.remove(x): x not in list i started looking through stack overflow then but most of what came up was how to strip alphabetical characters from a string, so I made this question. This produces a list of strings, with each string making up one line in the file. I want to remove any string which contains any alphabet characters as this should remove all the metadata and leave just the data. Any help would be appreciated thank you.
possible better answer: http://stackoverflow.com/a/49030471
has title: How to remove values in list which contain alphabetical characters?
has comment: http://stackoverflow.com/comment/85063456
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/49029680
type: Question
accepted answer: http://stackoverflow.com/a/49029680
has comment: http://stackoverflow.com/comment/85063239
answer count: 2
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49030471
favorite count: 0

http://stackoverflow.com/q/48982832
tagged with: python-decorators
score: 2
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/30104047
tagged with: python-descriptors
accepted answer: http://stackoverflow.com/a/48983261
type: Question
has title: Understanding a technique to make class-based decorators support instance methods
downvote count: 0
linked to: http://stackoverflow.com/q/48981501
has body: I recently came across a technique in the Python decorator library's memoized decorator which allows it to support instance methods: import collections import functools class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if not isinstance(args, collections.Hashable): # uncacheable. a list, for instance. # better to not cache than blow up. return self.func(*args) if args in self.cache: return self.cache[args] else: value = self.func(*args) self.cache[args] = value return value def __repr__(self): '''Return the function's docstring.''' return self.func.__doc__ def __get__(self, obj, objtype): '''Support instance methods.''' return functools.partial(self.__call__, obj) The __get__ method is, as explained in the doc string, where the 'magic happens' to make the decorator support instance methods. Here are some tests showing that it works: import pytest def test_memoized_function(): @memoized def fibonacci(n): "Return the nth fibonacci number." if n in (0, 1): return n return fibonacci(n-1) + fibonacci(n-2) assert fibonacci(12) == 144 def test_memoized_instance_method(): class Dummy(object): @memoized def fibonacci(self, n): "Return the nth fibonacci number." if n in (0, 1): return n return self.fibonacci(n-1) + self.fibonacci(n-2) assert Dummy().fibonacci(12) == 144 if __name__ == "__main__": pytest.main([__file__]) What I'm trying to understand is: how does this technique work exactly? It seems to be quite generally applicable to class-based decorators, and I applied it in my answer to Is it possible to numpy.vectorize an instance method?. So far I've investigated this by commenting out the __get__ method and dropping into the debugger after the else clause. It seems that the self.func is such that it raises a TypeError whenever you try to call it wit…
answer count: 1
has answer: http://stackoverflow.com/a/48983261
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/84968125
comment on: http://stackoverflow.com/a/48981359
has text: FWIW, using ``zip(*m)`` to transpose only works well for small number of inputs. This is because the star fully unpacks the iterable so that it passed in each of the OP's "lots of lists" in as separate arguments to the *zip()* function.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48998248
score: 0
type: Answer
has body: To get crontab to run a task every 10 minutes you could type as follow: */10 * * * * /path/to/command or */10 * * * * /path/to/script
answers question: http://stackoverflow.com/q/48998192

http://stackoverflow.com/comment/85055223
score: 0
comment on: http://stackoverflow.com/q/49025279
type: Comment
type: QuestionComment
has text: You are sending `str` objects, but sockets only take bytes. If this is how your coursera course told you to do it, switch to Python 2, or switch courses.

http://stackoverflow.com/a/49085084
has comment: http://stackoverflow.com/comment/85175628
type: Answer
has comment: http://stackoverflow.com/comment/85199501
has comment: http://stackoverflow.com/comment/85175562
has comment: http://stackoverflow.com/comment/85175502
has comment: http://stackoverflow.com/comment/85195928
has comment: http://stackoverflow.com/comment/85199585
has comment: http://stackoverflow.com/comment/85175734
has comment: http://stackoverflow.com/comment/85175449
has comment: http://stackoverflow.com/comment/85175469
has comment: http://stackoverflow.com/comment/85175789
has comment: http://stackoverflow.com/comment/85175737
has comment: http://stackoverflow.com/comment/85196808
has comment: http://stackoverflow.com/comment/85175595
has comment: http://stackoverflow.com/comment/85175608
score: 0
has comment: http://stackoverflow.com/comment/85199498
has comment: http://stackoverflow.com/comment/85199492
has comment: http://stackoverflow.com/comment/85234169
has comment: http://stackoverflow.com/comment/85175607
has comment: http://stackoverflow.com/comment/85175446
has body: You can have a look into PhotoImage Class. Inserting images is simple. import Tkinter as tk from PIL import ImageTk, Image path = 'C:/xxxx/xxxx.jpg' root = tk.Tk() img = ImageTk.PhotoImage(Image.open(path)) panel = tk.Label(root, image = img) panel.pack(side = "bottom", fill = "both", expand = "yes") root.mainloop() Hope this helps. Do have a look at Using Images in Labels section of Tkinter Labels page. You can read Tkinter's PhotoImage and Label widgets for customizations. UPDATE - For installing 'PIL' from pillow - PIL is from package pillow. use - sudo pip install pillow Then from PIL import ImageTk will not give errors. If pip is not installed then install it by using- sudo apt-get install python-pip
answers question: http://stackoverflow.com/q/49084946
has comment: http://stackoverflow.com/comment/85175531

http://stackoverflow.com/comment/84960192
comment on: http://stackoverflow.com/q/48977473
score: 0
has text: See [redirecting methods to Text](https://stackoverflow.com/q/43137141/7032856).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57486033
upvote count: 8
type: Answer
score: 8
answers question: http://stackoverflow.com/q/48980029
has body: The accepted answer didn't work for me. I had to use requests.exceptions.ProxyError, i.e.: try: req = requests.post(...) except requests.exceptions.ProxyError as err: print("Proxy Error", err)
downvote count: 0

http://stackoverflow.com/q/49006573
tagged with: tensorflow
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/49013663
answer count: 1
tagged with: ocr
favorite count: 0
has title: how to create cutomized dataset for google tensorflow attention ocr?
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/44430310
type: AnsweredQuestion
has body: I am able to create TFRecord file according to this question. But I don't know whether I should write all images into a single TFRecord file or create multiple TFRecord files. Also, I don't quite understand the config file for datesets. What content should be in "charset_filename" file? Should it be a collection of all posible chracters in the dataset? When generating TFRecord file, we converted charcters to integer ids, should this file include characters or their ids?
has answer: http://stackoverflow.com/a/49013663
score: -1

http://stackoverflow.com/comment/85060948
has text: And the line producing the error?
comment on: http://stackoverflow.com/q/49027781
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49016596
linked to: http://stackoverflow.com/q/48647975
tagged with: networkx
type: AnsweredQuestion
tagged with: attributeerror
downvote count: 0
tagged with: directed-graph
type: Question
accepted answer: http://stackoverflow.com/a/49016885
score: 4
has answer: http://stackoverflow.com/a/49016885
answer count: 1
tagged with: python
upvote count: 4
favorite count: 0
has title: networkx DiGraph Attribute Error self._succ
has body: Context: I'm trying to run another researcher's code - it describes a traffic model for the Bay Area road network, which is subject to seismic hazard. I'm new to Python and therefore would really appreciate some help debugging the following error. Issue: When I try to run the code for the sample data provided with the file, following the instructions in the README, I get the following error. DN0a226926:quick_traffic_model gitanjali$ python mahmodel_road_only.py You are considering 2 ground-motion intensity maps. You are considering 1743 different site locations. You are considering 2 different damage maps (1 per ground-motion intensity map). Traceback (most recent call last): File "mahmodel_road_only.py", line 288, in &lt;module&gt; main() File "mahmodel_road_only.py", line 219, in main G = get_graph() File "mahmodel_road_only.py", line 157, in get_graph G = add_superdistrict_centroids(G) File "mahmodel_road_only.py", line 46, in add_superdistrict_centroids G.add_node(str(1000000 + i)) File "/Library/Python/2.7/site-packages/networkx-2.0-py2.7.egg/networkx/classes/digraph.py", line 412, in add_node if n not in self._succ: AttributeError: 'DiGraph' object has no attribute '_succ' Debugging: Based on some other questions, it seems like this error stems from an issue with the networkx version (I'm using 2.0) or the Python version (I'm using 2.7.10). I went through the migration guide cited in other questions and found nothing that I needed to change in mahmodel_road_only.py. I also checked the digraph.py file and found that self._succ is defined. I also checked the definition of get_graph(), shown below, which calls networkx, but didn't see any obvious issues. def get_graph(): import networkx '''loads full mtc highway graph with dummy links and then adds a few fake centroidal nodes for max flow and traffic assignment''' G = networkx.read_gpickle("input/graphMTC_CentroidsLength3int.gpickle") G = add_superdistrict_centroids(G) assert not G.is_multigraph() # Directed! onl…

http://stackoverflow.com/q/48976342
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84963816
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/84963757
has comment: http://stackoverflow.com/comment/84963693
tagged with: 32bit-64bit
has comment: http://stackoverflow.com/comment/84963119
score: 0
has title: pygame won't open with python 64-bit
answer count: 1
has answer: http://stackoverflow.com/a/48980219
has body: I was using python 32-bit and pygame worked perfectly fine, but then I needed python 64-bit to get another module. Now python 64-bit is set to my standard python, so every time I try to open my programs with pygame in them it crashes instantly, and I have to open them with IDLE 32-bit and then press F5 to run them, which is annoying. I was wondering if it is possible to get pygame to work with python 64-bit. I tried pip installing pygame for 64-bit, but it said it was already installed. If it is impossible to get pygame to work with 64-bit python, please tell me how to change it so that 32-bit python is the default. I am using python 3.6.4 by the way. Thank you
linked to: http://stackoverflow.com/q/34803040
has comment: http://stackoverflow.com/comment/84963110
has comment: http://stackoverflow.com/comment/84964093
has comment: http://stackoverflow.com/comment/84963374
has comment: http://stackoverflow.com/comment/84963817
has comment: http://stackoverflow.com/comment/84963752
has comment: http://stackoverflow.com/comment/84963795
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84963590
accepted answer: http://stackoverflow.com/a/48980219

http://stackoverflow.com/q/49070023
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49082474
has comment: http://stackoverflow.com/comment/85147148
type: Question
tagged with: python
has title: cannot use custom related_widget_wrapper.html
accepted answer: http://stackoverflow.com/a/49082474
score: 0
tagged with: django
answer count: 1
has body: I get TemplateDoesNotExist error if I use custom related_widget_wrapper.html. What I did is, I created a folder called widgets inside templates/dashboard directory and add a related_widget_wrapper.html file. This way I got the mentioned error and what strange thing I found is django.template.loaders.filesystem.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django/forms/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django/contrib/admin/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django/contrib/auth/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django_tables2/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/haystack/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/treebeard/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/versatileimagefield/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) it is not searching inside my apps. I mean it should search in my project templates. Am i missing something or what have i done wrong? class RelatedFieldWidgetWrapper(Widget): """ This class is a wrapper to a given widget to add the add icon for the dashboard. """ template_name = 'dashboard/widgets/related_widget_wra…
tagged with: django-widget
has comment: http://stackoverflow.com/comment/85147590

http://stackoverflow.com/q/49012927
has comment: http://stackoverflow.com/comment/85031956
has comment: http://stackoverflow.com/comment/85031083
type: Question
score: 0
has title: Store console output in a file - Python , unittest
answer count: 1
has answer: http://stackoverflow.com/a/49037011
has comment: http://stackoverflow.com/comment/85031097
has comment: http://stackoverflow.com/comment/85033292
tagged with: python-3.x
tagged with: python
has body: I have a python script in which I wrote some unit tests and I am using selenium. I want to extract the whole output of the console (not only my prints but also the unit test related results), so that I can import them later in my test management tool. Here is my code: import unittest from selenium import webdriver import json import requests import sys class TestUbuntuHomepage(unittest.TestCase): global strs strs = [] def setUp(self): sys.stdout = open("C:\\Users\\Marialena\\Downloads\\out2.log", 'wt') self.driver = webdriver.Firefox(executable_path="C:\\Users\\Marialena\\Downloads\\selenium-drivers\\geckodriver") def testTitle(self): self.driver.get('http://www.ubuntu.com/') if self.assertIn('Ubuntu', self.driver.title): strs.append('test'}) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2) Using sys.stdout = open("C:\\Users\\Marialena\\Downloads\\out2.log", 'wt') I get in the file everything I have printed and I also get this exception: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm\PyCharm Community Edition 2017.3.3\helpers\pycharm_jb_unittest_runner.py", line 35, in main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) File "C:\Users\Marialena\AppData\Local\Programs\Python\Python36-32\Lib\unittest\main.py", line 95, in init self.runTests() File "C:\Users\Marialena\AppData\Local\Programs\Python\Python36-32\Lib\unittest\main.py", line 256, in runTests self.result = testRunner.run(self.test) File "C:\Program Files\JetBrains\PyCharm\PyCharm Community Edition 2017.3.3\helpers\pycharm\teamcity\unittestpy.py", line 304, in run return super(TeamcityTestRunner, self).run(test) File "C:\Users\Marialena\AppData\Local\Programs\Python\Python36-32\Lib\unittest\runner.py", line 176, in run test(result) File "C:\Users\Marialena\AppData\Local\Programs\Python\Python36-32\Lib\unittest\suite.py", line 84, in call return self.run(*args, **kwds) File "C:\Users\Mar…
type: UnansweredQuestion
tagged with: file
tagged with: output
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/85030861
has comment: http://stackoverflow.com/comment/85030795

http://stackoverflow.com/q/49089934
has comment: http://stackoverflow.com/comment/85185787
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49090057
downvote count: 1
has comment: http://stackoverflow.com/comment/85185406
type: Question
tagged with: performance
possible better answer: http://stackoverflow.com/a/49090313
has body: Hello im pretty new in Python and i have a simple function that looks like this: def normal_list(p, data, n): cost = 0 cost_list = [] list = [] clappend=cost_list.append listappend=list.append for i in range(n): x = np.random.choice(data, p=p) if (len(list) == 0): listappend(x) else: for i in list: if i == x: clappend(cost) elif i == list[-1]: listappend(x) cost += 1 cost = 0 return cost_list Where p is a list of probability, data is a list of data in almost all case it will be list with numbers 1-100 I must to speed this up cause i've to use this function for n=100000 then it takes very long time and end in memory error for cost_list. Thanks for all advice i just found my error. I messed up couse i didint break loop after finding x in my list.so Thanks again and use of generator was a good idea.
has answer: http://stackoverflow.com/a/49090313
answer count: 2
has title: Python Speed and memory
accepted answer: http://stackoverflow.com/a/49090057
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85186171
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85193391
has comment: http://stackoverflow.com/comment/85185574
tagged with: python

iteration
tags question: http://stackoverflow.com/q/49015378
tags question: http://stackoverflow.com/q/49008313
tags question: http://stackoverflow.com/q/48980048
tags question: http://stackoverflow.com/q/48981183
tags question: http://stackoverflow.com/q/49017469
tags question: http://stackoverflow.com/q/49103874
type: Tag
tags question: http://stackoverflow.com/q/49000384
tags question: http://stackoverflow.com/q/49081377
tag name: iteration

http://stackoverflow.com/comment/85205810
has text: Why are you `hstack`ing in `bias`? A bias is of the same shape as `l0.dot(w0)`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49100135
score: 1

http://stackoverflow.com/a/49039410
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85084544
type: Answer
answers question: http://stackoverflow.com/q/49039340
upvote count: 1
has body: &gt;&gt;&gt; desc = ['\n ', ... '\n2013 Yamaha FJR 1300 Sport Touring, 4 cylinder, 12.120 miles, silver, cruise control, traction control, ABS brakes, heated hand grips, Two Brothers exhaust, handle bar risers, 6.5 gal. gas tank, adjustable windshield, saddlebags, excellent condition, very clean.', ... '\n$ 7.500 (828) 250-0373 WWW.GREENVALLEYCARS.COM', ... '\n', ... '\n '] Before: &gt;&gt;&gt; desc ['\n ', '\n2013 Yamaha FJR 1300 Sport Touring, 4 cylinder, 12.120 miles, silver, cruise control, traction control, ABS brakes, heated hand grips, Two Brothers exhaust, handle bar risers, 6.5 gal. gas tank, adjustable windshield, saddlebags, excellent condition, very clean.', '\n$ 7.500 (828) 250-0373 WWW.GREENVALLEYCARS.COM', '\n', '\n '] Apply replace() and strip() [x.replace('\n', '').strip() for x in desc ] After: ['', '2013 Yamaha FJR 1300 Sport Touring, 4 cylinder, 12.120 miles, silver, cruise control, traction control, ABS brakes, heated hand grips, Two Brothers exhaust, handle bar risers, 6.5 gal. gas tank, adjustable windshield, saddlebags, excellent condition, very clean.', '$ 7.500 (828) 250-0373 WWW.GREENVALLEYCARS.COM', '', ''] If I understand you correctly, you can replace the newline character with empty string and then remove around whitespaces [x.replace('\n', '').strip() for x in desc ]

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/48996961
tags question: http://stackoverflow.com/q/49069960
tags question: http://stackoverflow.com/q/49017458
type: Tag
tags question: http://stackoverflow.com/q/49088100

http://stackoverflow.com/q/49007666
has comment: http://stackoverflow.com/comment/85021021
tagged with: python
has body: I finished my first draft-computation and was wondering how to most effectively communicate the code to non-Python users. I was thinking of a HTML or PDF file (maybe in jupyter notebook style) that allows to neatly show the code with it's rendered outputs, as well as some text to thoroughly explain what is done in every step. I saw that Markdown seems to be a package for that purpose, but I was wondering whether there is a easier way to go about it, before I read into the package specific syntax.
accepted answer: http://stackoverflow.com/a/49007744
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85021208
has comment: http://stackoverflow.com/comment/85020035
upvote count: 1
type: Question
has title: The easiest way to communicate a Python script to supervisors?
has comment: http://stackoverflow.com/comment/85020831
tagged with: markdown
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85020688
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85035085
has answer: http://stackoverflow.com/a/49007744

http://stackoverflow.com/a/49018736
has comment: http://stackoverflow.com/comment/85045615
has body: As dir is simply a command understood by cmd.exe (or powershell.exe) then you could: subprocess.Popen(["cmd", "/c", "dir", "c:\\Users"], stdout=subprocess.PIPE) which corresponds to doing the following in a shell C:\&gt;cmd /c dir c:\Users You may find you have to fully path cmd, as c:\\Windows\\System32\\cmd.exe
answers question: http://stackoverflow.com/q/49018413
downvote count: 0
type: AcceptedAnswer
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/49018413
upvote count: 6

http://stackoverflow.com/q/49038137
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/85081910
has body: I'm making a project for school where users are quizzed on subjects and their results are saved into a report (CSV file called 'reportForFergusTwo') for the 'customer' (Fergus). The report shows the average score a certain quiz, the high score, and the username of the person who achieved it. And then, I'm meant to display the user's details but the user's details are saved in a different CSV file ('details'). So far I've made a function that finds the highest score and username of the person who achieved it in the CSV 'reportForFergusTwo'. I now need to work on a function that searches through another CSV file ('details'). def findHighScoreUser(): print(user) with open ('details.csv', 'r') as stalking: stalkingReader=csv.reader(stalking) valid4=False for row in stalkingReader: if user in row: valid4=True print("Here are the details for user {}... ".format(user)) splitter=row.split(',') name=splitter[0] age=splitter[1] year=splitter[2] print("Name: {}".format(name)) print("Age: {}".format(age)) print("Year Group: {}".format(year)) postReport() if valid4==False: print("Sorry Fergus, this user doesn't seem to be in our records.") 'user' is a variable from my previous function, where I found the username of the person with the highest score. It holds the username. I made it global and printed it at the start of this function, and that's working, making me think this is an issue I've made in reading the CSV. Here is the details CSV: Name,Age,Year Group,Username,Password Erin Jones,15,11,Eri15,Password Lucas Jones,16,11,Luc16,Password2 Michael Jordan,11,7,Mic11,GetSomeHelp La Roux,14,9,La 14,Bulletproof And here is the reportForFergusTwo CSV: Subject,Difficulty,Score,Username language,easy,10,Luc16 chemistry,easy,10,Luc16 maths,easy,9,Luc16 chemistry,easy,5,Eri15 chemistry,easy,6,Mic11 chemistry,easy,0,Eri15 I'm still fairly new to code, so please excuse me if the answer is obvious.
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/49038457
has title: Finding a specific record in a csv file
tagged with: python
has answer: http://stackoverflow.com/a/49038229
has answer: http://stackoverflow.com/a/49038457
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49038229
has comment: http://stackoverflow.com/comment/85081613
type: Question
has comment: http://stackoverflow.com/comment/85082068
has comment: http://stackoverflow.com/comment/85082250

http://stackoverflow.com/comment/85007671
comment on: http://stackoverflow.com/a/49001286
score: 0
has text: Great It works, Is there way we can find True or False. If difference between files True and If no difference files False
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48965561
has comment: http://stackoverflow.com/comment/84936888
has comment: http://stackoverflow.com/comment/84937018
has title: Is key-order same always if there are two different dictionaries with the same key?
has body: I have the following dictionaries in python 3. Both dictionaries have the same key and order, i.e., 'a', 'z', 'foo', 'b'. But each has a different value. I confirmed that both key-orders are always same. But does it depend on environments? I know we cannot usually fix the order of keys. I would like to know the key-order of different dictionaries with same keys' dic1 = {'a': 0, 'z': 2, 'foo': 0, 'b': 0} dic2 = {'a': 1, 'z': 0, 'foo': 8, 'b': 7} for k, v in dic1.items(): print(k, v) for k, v in dic2.items(): print(k, v)
type: Question
has answer: http://stackoverflow.com/a/48965626
score: 0
linked to: http://stackoverflow.com/q/15479928
answer count: 1
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/15479928
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/39980323
has comment: http://stackoverflow.com/comment/84937001
type: UnansweredQuestion

http://stackoverflow.com/a/49012061
has body: The following code seems to be the likely culprit: if i_vals[-index] &lt; 784: # ... i_vals[-index] += 1 If i_vals[-index] is 783 it will be increased to 784, so the next time that value is used as the index it will cause the error.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49011681
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49011681

http://stackoverflow.com/comment/85117704
score: 0
comment on: http://stackoverflow.com/a/49033853
has text: I've gone and tried this solution on several other DXF files. It's working on all of them beautifully. I'm very curious about why groups of four were needed to make this work. When you have time it would be awesome to know why the splines need to be processed in groups of four. From your statements it seems you know a lot about DXF files and Spline curves. In my research I didn't see any reference to groups of 4. Where did you learn about it? Thanks
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85876687
type: QuestionComment
type: Comment
has text: @Fou: This is what I'm saying, what the actual neighborhood looks like depends on the definition of the dilation that they're using. Both definitions are equally valid. To know what a specific implementation does, simply do the experiment as you did and see what the result is. :)
score: 0
comment on: http://stackoverflow.com/q/49007421

http://stackoverflow.com/comment/85143516
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49069195
has text: @MaximilianPeters if I understand you correctly, then I have to input the last sample, and then I'll be able to get a prediction?
score: 0

http://stackoverflow.com/q/48978476
favorite count: 0
score: -1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84984149
has body: I'm new in Flask and not familiar with its tools enough. So, I'm trying to upload a CSV file to my application; in order to use its data to plot some graphs using Pygal. This is was my attempt, but it didn't work: def upload_file(): return render_template('upload.html') @app.route('/uploader', methods = ['GET', 'POST']) def upload(): if request.method == 'POST': f = request.files['file[]'] f.save(secure_filename(f.filename)) x= np.asarray(f) graph = pygal.Line() graph.title = '% Change Coolness of programming languages over time.' graph.add('Graph', x[1,:]) graph_data = graph.render_data_uri() return render_template("upload.html", graph_data = graph_data) The HTML code: {% extends "layout.html" %} {% block content %} &lt;body class="body"&gt; &lt;div class="container" align="left"&gt; &lt;embed type="image/svg+xml" src= style='max-width:1000px'/&gt; &lt;/div&gt; &lt;form action = "http://localhost:5000/uploader" method = "POST" enctype = "multipart/form-data"&gt; &lt;input type = "file" name ="file" /&gt; &lt;input type = "submit"/&gt; &lt;/form&gt; &lt;/body&gt; {% endblock %} the Error message is: ' ERROR: execution aborted' and also this exclamation mark appears beside the "graph.add" line, as a space error! anyone have an idea how do I get to the desired result?
has title: Flask-Python: upload a csv file and use its data in the application
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/84984197
tagged with: flask
answer count: 1
has answer: http://stackoverflow.com/a/49014498

http://stackoverflow.com/comment/85356497
has text: I've found that `select m.*, p.type from multipliers m inner join pushes p on m.push_id = p.id where p.type= 'CONSTANT' order by p.id` returns all of the multiplier entries, but I'm still looking for an efficient way to get all rows with the max push_id from this result
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49116828
type: Comment

http://stackoverflow.com/q/49052479
upvote count: 0
has body: okay so after a lot of searching i decided to ask the question i've tried doing print[0] but i got the error Traceback (most recent call last): File "", line 1, in print[0] TypeError: 'builtin_function_or_method' object is not subscriptable ['a', 'c', 'e'] [1, 3, 5] these are my 2 outputs i want to remove the commas and the inverted commas and make it look like ace 135
score: -3
has title: How do I strip commas, brackets in shell
answer count: 3
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49063133
has answer: http://stackoverflow.com/a/49052660
downvote count: 3
has answer: http://stackoverflow.com/a/49052552
type: Question

http://stackoverflow.com/comment/85061861
has text: Your image has ugly artefacts in it - has it been a JPEG at some point in its life? And can you obtain the image without its having been a JPEG?
score: 0
comment on: http://stackoverflow.com/q/49024632
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49071897
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85149953
has body: I have a very simple algorithm question here, which asks to remove duplicates from a list and return the length of the new list. Here's my code in py3: class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ nums = list(set(nums)) return len(nums) This works fine when I test it in my terminal. But according to leetCode, input: [1,1,2] puts out [1,1] instead of [1,2]. Assuming leetCode doesn't have a bug, I can only come to the conclusion that there's something going on with the scope of nums? Maybe nums is being treated like a local variable when set using nums = list(set(nums))?
has comment: http://stackoverflow.com/comment/85149366
has comment: http://stackoverflow.com/comment/85150763
has title: Simple python leetCode not accepted on technicality?
favorite count: 0
has comment: http://stackoverflow.com/comment/85150229
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49072205
has comment: http://stackoverflow.com/comment/85150161
has comment: http://stackoverflow.com/comment/85150374
has comment: http://stackoverflow.com/comment/85149448
downvote count: 0
has comment: http://stackoverflow.com/comment/85150736
score: 1
accepted answer: http://stackoverflow.com/a/49072205
linked to: http://stackoverflow.com/q/13530998

http://stackoverflow.com/a/49098941
score: 1
upvote count: 1
downvote count: 0
has body: There are eleven CRC-16's in Greg Cook's catalog with that polynomial, and probably more that aren't in his catalog. So when you say "CRC-16", it could be a lot of different things. Your binary data can be interpreted as bytes in two different ways, either most significant bit first, or least significant bit first. If the former, then the CRC in "rest" would be the CRC-16/GENIBUS. If the latter, then it is the X-25 CRC-16. In both cases the CRC register is initialized with all 1's (0xffff), and at the end is inverted, i.e. exclusive-or'ed with 0xffff. It is that initialization and post-processing that you are probably missing in your attempt to replicate the CRC. Here is some simple C code for the X-25 CRC-16, which would operate on your data assuming least significant bit first: unsigned crc16x25(unsigned char *data, size_t len) { unsigned crc = 0xffff; while (len--) { crc ^= *data++; for (unsigned k = 0; k &lt; 8; k++) crc = crc &amp; 1 ? (crc &gt;&gt; 1) ^ 0x8408 : crc &gt;&gt; 1; } crc ^= 0xffff; return crc; } So if you feed that 0x86 0xa2 ... 0x47, you will get 0xec3f as the CRC.
type: Answer
answers question: http://stackoverflow.com/q/49094896

http://stackoverflow.com/comment/84984153
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48989601
has text: Its better you first approach to get well formed json input. Same Json data you need in below format - ["query", { "uid": "7E2M3", "text": "Whhe", "Kaaan": "a tron", "ops": [{ "uid": "64H", "text": "Baa" }, { "uid": "1KR", "text": "Aa" }, { "uid": "CMAO48FK21", "text": "Brahmagupta" }], "user_status": "20" }] If your team is ready to rectify this Json format problem so you need not to do special handling from your end.
score: 0

http://stackoverflow.com/q/49117648
has comment: http://stackoverflow.com/comment/85240912
type: Question
has comment: http://stackoverflow.com/comment/85240625
has answer: http://stackoverflow.com/a/49117863
score: 0
has title: Having a string as a dictionary key
answer count: 3
has answer: http://stackoverflow.com/a/49117816
has comment: http://stackoverflow.com/comment/85240928
has body: I have 20K objects and a set of features provided in a list. I need to extract those features from each object and save them into a dictionary. Each object has almost 100 features. For example: # object1 Object1.Age = '20' Object1.Gender = 'Female' Object1.DOB = '03/05/1997' Object1.Weight = '130lb' Object1.Height = '5.5' #object2 Object1.Age = '22' Object1.Gender = 'Male' Object1.DOB = '03/05/1995' Object1.Weight = '145lb' Object1.Height = '5.8' #object3 .... And the list of features that I need to extract from each object: features = ['Gender', 'DOB', 'Height'] I'm trying to prepare a dictionary for each object with the specified features such that: dict1 = {features[0]:Object1.features[0], features[1]:Object1.features[1], features[2]:Object1.features[2]} dict2 = {features[0]:Object2.features[0], features[1]:Object2.features[1], features[2]:Object2.features[2]} dict3 = ... Since the list of features may be change in future, I need the code to be flexible. I'm sure this is not the way that I can prepare the dictionary for each object but I wrote this to show the problem. How can I write the dictionaries?
accepted answer: http://stackoverflow.com/a/49117814
possible better answer: http://stackoverflow.com/a/49117816
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49117814

http://stackoverflow.com/comment/85081729
type: AnswerComment
comment on: http://stackoverflow.com/a/49036996
score: 0
type: Comment
has text: thanks but that looks a bit black-boxy dont you think :) why cant I have it work with an apply??? :(

http://stackoverflow.com/q/49061818
has answer: http://stackoverflow.com/a/49062483
has body: I want to make decorator with class variables. How can I make decorator to class function? Because I have a lot of functions that need to lock. I don't want to write down with self.lock: or self.lock.release() every function. this is my code! class Something: self.lock = Lock( .. ) #decorator def _lock(self, func): def wrapper(*args, **kwargs): self.lock.acquire() func(*args, **kwargs) self.lock.release() return wrapper @_lock def some_func(self,): #do something
has answer: http://stackoverflow.com/a/49061900
answer count: 3
tagged with: locking
has title: Python decorator in class
downvote count: 0
tagged with: decorator
has answer: http://stackoverflow.com/a/49062060
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49061900
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: multithreading
possible better answer: http://stackoverflow.com/a/49062483
type: Question

http://stackoverflow.com/comment/85040848
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49009871
has text: If you're microoptimizing to the point where you would care about the cost of `bool`, it'd be better to just use `not not x` instead of `truth(x)`.
score: 0

http://stackoverflow.com/q/48966289
has answer: http://stackoverflow.com/a/48966732
favorite count: 0
linked to: http://stackoverflow.com/q/176011
has comment: http://stackoverflow.com/comment/84938268
has answer: http://stackoverflow.com/a/48966757
upvote count: 8
answer count: 3
possible better answer: http://stackoverflow.com/a/48966803
tagged with: python
has comment: http://stackoverflow.com/comment/84938311
has answer: http://stackoverflow.com/a/48966803
score: 8
accepted answer: http://stackoverflow.com/a/48966732
has comment: http://stackoverflow.com/comment/84938527
has body: I am no expert in how Python lists are implemented but from what I understand, they are implemented as dynamic arrays rather than linked lists. My question is therefore, if python lists are implemented as arrays, why are they called 'lists' and not 'arrays'. Is this just a semantic issue or is there some deeper technical reason behind this. Is the dynamic array implementation in Python close to a list implementation? Or is it because the dynamic array implementation makes its behaviour closer to a list's behaviour than an array? Or some other reason I do not understand? To be clear, I am not asking specifically how or why Python lists are implemented as dynamic arrays, although that might be relevant to the answer.
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84938269
type: Question
has title: Why are Python Lists called 'lists' when they are implemented as dynamic arrays
tagged with: arrays
downvote count: 0

http://stackoverflow.com/q/49105473
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49111906
favorite count: 0
upvote count: 7
tagged with: python
tagged with: spring
has answer: http://stackoverflow.com/a/49111906
has body: I am trying to make a web-app that takes input from the user using HTML Form on Spring-boot (Which is running on embedded Tomcat); I need to pass this input to a Python script sitting somewhere on my hard disk as command-line arg. Here is my controller that fetches the data from HTML form (Getting data from the form is working fine.) @Controller public class PortalController { @RequestMapping(value="") public String hello(){ return "portal/welcome"; } @RequestMapping(value="",method=RequestMethod.POST) public String addAObjectForm(@RequestParam String val) throws IOException { String cmd = "python Fetch.py \""+val+"\""; System.out.println(cmd); Runtime.getRuntime().exec(cmd); return "redirect:/"; } } The variable 'cmd' stores this value finally: python Fetch.py "Command-line-arg-from-html" The Python code is scraping web. The code is so big that it cannot be ported to Java. And my v. sweet teacher has asked me to make the web-app on Spring-Boot. Since the app is running on Tomcat, it doesn't look like I will be able to execute the Py script directly as if it were on console. Can someone suggest a way of doing it, please? Any bit of help is highly appreciated. Note: Both, Spring-Boot Project and Python Script, are working standalone without issues. The issue I am having is, the code just prints the variable 'cmd' on the console and continues. No changes are reflected in the database (which are supposed to be done by the Py script), it indicates that the script did not execute. Here is the console window: 2018-03-03 05:44:47.733 INFO 10752 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-03-03 05:44:47.771 INFO 10752 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2018-03-03 05:44:47.771 INFO 10752 --- [ restartedMain] org.OpenLyrics.Portal.PortalApplication : Started PortalApplication in 3.161 seconds (JVM running for 7.414) 2018-03-03…
score: 6
type: AnsweredQuestion
tagged with: spring-boot
tagged with: java
type: Question
has title: Running a Python script from Spring-Boot Web Application on embedded Tomcat

http://stackoverflow.com/comment/85242725
comment on: http://stackoverflow.com/q/49118550
type: Comment
type: QuestionComment
score: 0
has text: But that doesn't mean it is on your path. `which python` will show you what is being executed.

http://stackoverflow.com/comment/85096957
has text: this returns me the Studets data, without data about group and faculty
comment on: http://stackoverflow.com/a/49046162
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84953321
has text: @VivekKalyanarangan Yeah, i realized that. I will adjust the "similar" criteria, to simply the mode of the group
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48973659

http://stackoverflow.com/q/48997785
has body: I am trying to extract value of 'login' from a dump of JSON which is in the form of text (response.text) Here's the string: { "name":"master", "commit":{ "sha":"adc3208a9ac76262250a", "commit":{ "author":{ "name":"root", "email":"dan.ja@foo.ca", "date":"2018-02-26T20:14:41Z" }, "committer":{ "name":"GitHub Enterprise", "date":"2018-02-26T20:14:41Z" }, "message":"Update README.md", "tree":{ "sha":"3e4710d0e021a0a7", "comment_count":0, "verification":{ "verified":false, "reason":"unsigned", "signature":null, "payload":null } }, "author":{ "login":"kyle", "id":5 } I am just trying to pull the value 'kyle' from the login in the last line. The value of 'kyle' can change as it can be a different login each time. Thus I need string in "login":"string" Here's what I have right now but that only gets me "login" : /"login"[^\a]*"/g
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48997882
type: Question
downvote count: 4
answer count: 1
has title: Python - regex to get dynamic usernames from JSON text
favorite count: 0
has comment: http://stackoverflow.com/comment/85001193
has comment: http://stackoverflow.com/comment/85001118
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85002502
has answer: http://stackoverflow.com/a/48997882
has comment: http://stackoverflow.com/comment/85001170
score: -3
upvote count: 1
tagged with: python
tagged with: regex

http://stackoverflow.com/q/49000803
downvote count: 2
has answer: http://stackoverflow.com/a/49014523
tagged with: python
has answer: http://stackoverflow.com/a/49001728
has title: Python iterate through array while finding the mean of the top k elements
has answer: http://stackoverflow.com/a/49005011
has comment: http://stackoverflow.com/comment/85037309
answer count: 15
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49000891
upvote count: 21
has answer: http://stackoverflow.com/a/49000912
score: 19
has answer: http://stackoverflow.com/a/49003096
type: Question
has answer: http://stackoverflow.com/a/49005302
possible better answer: http://stackoverflow.com/a/49005973
tagged with: algorithm
has answer: http://stackoverflow.com/a/49005973
accepted answer: http://stackoverflow.com/a/49000891
has answer: http://stackoverflow.com/a/49000841
has answer: http://stackoverflow.com/a/49000922
has answer: http://stackoverflow.com/a/49001529
linked to: http://stackoverflow.com/q/8269916
has answer: http://stackoverflow.com/a/49001168
has answer: http://stackoverflow.com/a/49029958
has comment: http://stackoverflow.com/comment/85020041
has comment: http://stackoverflow.com/comment/85073913
has body: Suppose I have a Python array a=[3, 5, 2, 7, 5, 3, 6, 8, 4]. My goal is to iterate through this array 3 elements at a time returning the mean of the top 2 of the three elements. Using the above array, during my iteration step, the first three elements are [3, 5, 2] and the mean of the top 2 elements is 4. The next three elements are [5, 2, 7] and the mean of the top 2 elements is 6. The next three elements are [2, 7, 5] and the mean of the top 2 elements is again 6. ... Hence, the result for the above array would be [4, 6, 6, 6, 5.5, 7, 7]. What is the nicest way to write such a function?
has answer: http://stackoverflow.com/a/49014336
favorite count: 0
has answer: http://stackoverflow.com/a/49000898
has comment: http://stackoverflow.com/comment/85036335

http://stackoverflow.com/q/49034670
has answer: http://stackoverflow.com/a/49034753
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49034753
type: AnsweredQuestion
has body: Im trying to locate the symbol " in a large text when it is immediately preceded and followed by a word or character only. I then want to replace it with this symbol without changing the word/number before and after it: ' I tried this: text7 = re.sub(r'(\w)"(\w)', r"$1\'$2", text6) For the word "it"s" all i get now is i$1'$2. What I want is "it's" Any suggestions?
has title: regex sub in python - grouping of characters to identify 3 characters and only change one of them
accepted answer: http://stackoverflow.com/a/49034777
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/49034818
answer count: 3
tagged with: regex
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49034777

http://stackoverflow.com/a/49024828
has comment: http://stackoverflow.com/comment/85054336
answers question: http://stackoverflow.com/q/49024801
has body: You can use the pip command to install from the downloaded .gz file. Ex: pip install pdfminer.six-20170720.tar.gz
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85056788
has comment: http://stackoverflow.com/comment/85056808

http://stackoverflow.com/comment/84965027
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48979808
has text: What do you excatly mean with only evaluate the model on the held-out test set once I've compared models?. You mean avoid making predictions as I mentioned above or to calculate accuracy? Thanks.

http://stackoverflow.com/comment/85073274
type: Comment
type: QuestionComment
has text: Thanks for the explanations and advises, and sorry about the 'broad question', actually I was not even sure myself what the problem actually was :) but thx, I'll be able to figure out a solution now!
comment on: http://stackoverflow.com/q/49025274
score: 0

defaultdict
tags question: http://stackoverflow.com/q/49016260
type: Tag
tags question: http://stackoverflow.com/q/49057951
tag name: defaultdict

http://stackoverflow.com/q/49116021
type: Question
answer count: 2
score: 3
downvote count: 0
has body: Let's say I am having a dictionary as dict1 which is having the skeleton (the order and nested depth) of the new dictionary I desire. For example: dict1 = { "Personnel": { "Performance": "" }, "Gaming": { "Status": "", "Bug Status": "" }, "Compatible": { "Minimum": "", "Integrity": "", "Scaling": "" }, "Comparison": { "Difference": { "DirectX": "" }, "Vendor": { "Intel": "", "Xiaomi": "" } } } And I am having another dictionary as dict2 which is having the values corresponding to keys in above dict1 dictionary along with some additional key value pairs as: dict2 = { "Personnel": { "Performance": "10.5", "Maximum": "50.5" }, "Gaming": { "Status": "Cool", "Bug Status": "None", "Green Status": "Black" }, "Compatible": { "Minimum": "5", "Integrity": "Yes", "Scaling": "No" }, "Comparison": { "Difference": { "DirectX": "50", "Android": "70" }, "Vendor": { "Xiaomi": "40" } }, "Another property": { "Testinfo": "TestTest", "Important": { "Wow": "MuchDoge" } } } I want to create a new dictionary having the skeleton from dict1 and corresponding value of keys fetched from dict2. Note: I'd want to skip key:value pairs that are not the part of dict1. For example: I do not need 'Green Status': 'Black' in my new dictionary. Below is the code I tried: def update(dict1 : dict, dict2: dict): new_data = {} for k, v in dict1.items(): if isinstance(v, dict): v = update(v, dict(dict2.keys())) if v not in dict2.keys(): new_data[k] = v return new_data but I'm totally missing something.
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49116091
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/49116251
type: AnsweredQuestion
has title: Create nested dictionary based on structure (skeleton) from one dict and corresponding values from another dict
has answer: http://stackoverflow.com/a/49116251
upvote count: 3
accepted answer: http://stackoverflow.com/a/49116091

http://stackoverflow.com/comment/84984181
has text: You'd need to check the API documentation - they may strip tags for their own reasons and you simply cannot get around it. OR they may have a parameter which allows you to pass the `\n` or somehow have a way to indicate new lines. Is the API is for a third party system which you have no control over?
comment on: http://stackoverflow.com/q/48989156
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51767163
answers question: http://stackoverflow.com/q/49013049
downvote count: 0
type: Answer
has body: I know I'm about five months late, but my answer might be helpful to some other people. First, the warning indicates that the matrix, that you are running reduce over or any other function that runs reduce internally, has some invalid values. These invalid values are mostly NaN or inf. I created a small snippet to explain what I mean!! In the following snippet, I will create a variable x that has some invalid values in it, then run a function that uses reduce internally like numpy.amax(). &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; x = np.array([[0.2, 0.7], [np.nan, np.nan]]) &gt;&gt;&gt; print(np.amax(x, axis=0)) RuntimeWarning: invalid value encountered in reduce return ufunc.reduce(obj, axis, dtype, out, **passkwargs) [nan nan] So, my advice is to double check the matrix that's causing this problem.. I don't know if this is the same case with you, but it worked for me!! In the next time, when you encounter any problem with your code... it's always a good idea to provide the code that causing the problem.
score: 15
has comment: http://stackoverflow.com/comment/90494682
upvote count: 15

http://stackoverflow.com/q/49089296
type: UnansweredQuestion
tagged with: python
has title: list indices must be integers or slices, not str for XML
tagged with: epub
type: Question
has comment: http://stackoverflow.com/comment/85184841
has body: Hello again StackOverflow, I have got another issue with my code. At line 208 if [currentpage]["headingAnchorName"][currentanchor] in data["pages"]: which has this error list indices must be integers or slices, not str. What I am trying to do is add anchor tags to the XML output in the ePub. I have added an example toc.ncx and the metadata.json. I am trying to add anchor tags to the code. The original, unbroken code with the epub file and other resources are on my Github. This one has definitely had my head scratching so I'd really appreciate the assistance. CreateE-book.py #!/usr/bin/env python #CreateE-book.py - Combines GenMetadata.py and GenEpub.py into one easy script. #GenMetadata.py - Generates the content.opf and toc.ncx files from the metadata.json file. #opf = "OEBPS/content.opf" #ncx = "OEBPS/toc.ncx" #JSON extraction magic import os import time import json from collections import OrderedDict import zipfile with open("metadata.json") as json_file: data = json.load((json_file), object_pairs_hook=OrderedDict) #For some reason the order is randomised, this preserves the order. #Create a compatible content.opf from scratch. def GenOPF(): opf = open(data["containerFolder"] + os.sep + "content.opf", "w") opf.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?> \n') #Metadata tags opf.write('\t \n') opf.write('\t\t<dc:title>' + data["title"] + '</dc:title>\n') opf.write('\t\t<dc:creator>' + data["creator"] + '</dc:creator>\n') opf.write('\t\t<dc:subject>' + data["subject"] + '</dc:subject>\n') opf.write('\t\t<dc:publisher>' + data["publisher"] + '</dc:publisher>\n') opf.write('\t\t<dc:identifier id="bookid">' + data["ISBN"] + '</dc:identifier>\n') opf.write('\t\t<dc:date>' + (time.strftime("%Y-%m-%d")) + '</dc:date>\n') #YYYY[-MM[-DD]] opf.write('\t\t<dc:language>' + data["language"] + '</dc:language>\n') opf.write('\t\t<dc:rights>' + data["rights"] + '</dc:rights>\n') opf.write('\t\t \n') #Fixed (non-reflowable) support if (data["textPresentation"] == …
has comment: http://stackoverflow.com/comment/85188532
score: 0
answer count: 0

http://stackoverflow.com/a/49102503
has comment: http://stackoverflow.com/comment/85210799
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85210228
has comment: http://stackoverflow.com/comment/85210925
has comment: http://stackoverflow.com/comment/85210274
has comment: http://stackoverflow.com/comment/85210732
has comment: http://stackoverflow.com/comment/85210220
has comment: http://stackoverflow.com/comment/85210258
answers question: http://stackoverflow.com/q/49102304
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49102304
has body: There is one way, convert a to dict , then map it back #a=df.groupby('#CNAE',group_keys=False).apply(pd.DataFrame.nlargest,n=3,columns='growth') df['top3growth']=df['#CNAE'].map(a.groupby('#CNAE').apply(lambda x : x.to_dict())) df Out[195]: person_code #CNAE growth size \ 0 231 32 0.54 32 1 233 43 0.12 333 2 432 32 0.44 21 3 431 56 0.32 23 4 654 89 0.12 89 5 764 32 0.20 211 6 434 32 0.82 90 top3growth 0 {'person_code': {0: 231, 2: 432, 6: 434}, 'gro... 1 {'person_code': {1: 233}, 'growth': {1: 0.12},... 2 {'person_code': {0: 231, 2: 432, 6: 434}, 'gro... 3 {'person_code': {3: 431}, 'growth': {3: 0.32},... 4 {'person_code': {4: 654}, 'growth': {4: 0.12},... 5 {'person_code': {0: 231, 2: 432, 6: 434}, 'gro... 6 {'person_code': {0: 231, 2: 432, 6: 434}, 'gro... After create your new column , if you want to convert the single cell back to dataframe pd.DataFrame(df.top3growth[0]) Out[197]: #CNAE growth person_code size 0 32 0.54 231 32 2 32 0.44 432 21 6 32 0.82 434 90
score: 0
upvote count: 1

http://stackoverflow.com/a/49080711
downvote count: 0
has body: The frame_image function uses a string path and not 'PngImageFile' object. get_images function opens the path and you append the 'PngImageFile' to the image variable, so in frame_all_images function you are trying to open an already opened file. The following change will fix the issue: def frame_all_images(): directory = os.getcwd() new_directory = os.path.join(directory, "Framed Images") try: os.mkdir(new_directory) except: pass images, files = get_images(directory) for n in range(len(images)): new_image = frame_image(files[n]) new_name = os.path.join(new_directory, files[n] + ".png") new_image.save(new_name) print('Success! All images have been framed!')
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49080555

http://stackoverflow.com/comment/85122824
has text: @Simon I renamed everything to its original/default setting. Still no luck. I also tried removing everything but Python27 and Python27\Scripts from my Path. Also no luck...
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49058046

http://stackoverflow.com/a/49059702
answers question: http://stackoverflow.com/q/49026950
upvote count: 1
downvote count: 1
has body: Here's the proper way to display text: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GLib import os textview = Gtk.TextView() textview.set_name("TextView") buf = Gtk.TextBuffer() textview.set_buffer(buf) buf.set_text("This is a test message\n") style_provider = Gtk.CssProvider() css = """ #TextView{ background-color: black; } """ style_provider.load_from_data(bytes(css.encode())) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION ) for color in ("red", "yellow", "green", "blue", "white"): buf.insert_markup( buf.get_end_iter(), 'This is a test message\n'.format(color), -1) win = Gtk.Window() win.connect('delete-event', Gtk.main_quit) win.add(textview) win.show_all() Gtk.main() This is a lot easier, by the way. Edit: Include color.
has comment: http://stackoverflow.com/comment/85167437
has comment: http://stackoverflow.com/comment/85167442
score: 0
type: Answer

http://stackoverflow.com/q/49095067
type: AnsweredQuestion
tagged with: dataframe
type: Question
tagged with: graph-theory
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49095592
favorite count: 0
tagged with: python
has body: Data is present in an excel file with first column representing the first node, the second column representing the second node and the third containing the weight. The nodes are strings. Eg: Apple Banana 65 Orange Apple 32
upvote count: 2
has title: How to convert weighted edge list to adjacency matrix in Python?
accepted answer: http://stackoverflow.com/a/49095592
has comment: http://stackoverflow.com/comment/85195269
score: 2

http://stackoverflow.com/comment/85175299
comment on: http://stackoverflow.com/q/49084774
type: Comment
has text: An `Entry` does not have a `command=` option - what would that even mean? You probably want a `Button`, which does have such an option.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85244938
comment on: http://stackoverflow.com/q/49117576
score: 0
type: QuestionComment
has text: Ok. So the error is that it tries to get an `/etc/passwd` entry for a user that has none (that must be your Docker user, [also related](https://github.com/matplotlib/matplotlib/issues/5940/)), but that's probably irrelevant. Try narrowing down the point at which the connection info is lost (does Docker even pass it to the container?). Also please mention Docker in the question (+tags).
type: Comment

http://stackoverflow.com/comment/85043113
type: Comment
comment on: http://stackoverflow.com/q/49016527
has text: **I renamed one method for compatibility with Python 3: Tag.has_key() -> Tag.has_attr()** - You can check it on above mentioned documentation page....
score: 0
type: QuestionComment

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

http://stackoverflow.com/q/49081092
downvote count: 1
has body: I have a small piece of code detecting event on a specific GPIO of my raspberry. When the event is detected, a function named increase_counter is called, if inside the function i only keep the "print('Flash ... ')" i only have one print per event,but if i call a url with urllib2 the whole increase_counter is executed twice, so i will have 2 flashes counted. import RPi.GPIO as GPIO import time import urllib2,json def increase_counter(ch): print('Flash ... ') requete='http://192.168.1.20:8080/json.htm?type=command&amp;param=udevice&amp;idx=52&amp;svalue=1' response=urllib2.urlopen(requete) data = json.loads(response.read()) print data IRPIN = 4 GPIO.setmode(GPIO.BCM) #GPIO SETUP GPIO.setup(IRPIN,GPIO.IN) #GPIO SETUP GPIO.add_event_detect(IRPIN, GPIO.FALLING, callback=increase_counter, bouncetime=3) #Calling event when flash is detected try: while True: time.sleep(1) except KeyboardInterrupt: print(' Stopped !!!') except: print(' Stopped !!!') raise finally: GPIO.remove_event_detect(IRPIN) GPIO.cleanup(IRPIN) # GPIO cleanup
type: Question
score: 0
tagged with: function
favorite count: 0
has comment: http://stackoverflow.com/comment/85168076
has title: function called twice with urllib.urlopen
answer count: 0
has comment: http://stackoverflow.com/comment/85168102
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85168523

http://stackoverflow.com/comment/85171270
has text: Basically a duplicate of https://stackoverflow.com/questions/7939018/c-program-cant-open-file.
score: 0
comment on: http://stackoverflow.com/q/49082945
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85151339
comment on: http://stackoverflow.com/a/49062650
type: Comment
has text: @np05, you left off the start and end anchors on your patterns which are requred when matching in this manner: r"^...$" also your string pattern is missing its brackets: r"^(_|[a-z]|[A-Z])(_|[a-z]|[A-Z]|[0-9])*$" and as currently defined, nothing matches "0abcd" since you're saying strings can't begin with digits and there is no "0a" integer form. Your floating point pattern is close but needs some work but make the changes I just suggested and see what still doesn't match.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85077847
type: Comment
type: QuestionComment
has text: @miradulo I knew I was missing something, sorry. Will edit in a few seconds.
comment on: http://stackoverflow.com/q/49036453
score: 0

http://stackoverflow.com/comment/85123644
score: 1
has text: The URLs you extract all have spaces in them try normalising the URLs first before you download from them see https://stackoverflow.com/questions/120951/how-can-i-normalize-a-url-in-python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49059182

http://stackoverflow.com/comment/84971675
comment on: http://stackoverflow.com/a/48982825
type: Comment
has text: @Punter345 - It seems you need interpolate, please check edited answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/109785893
score: 0
comment on: http://stackoverflow.com/a/49078861
has text: @Leo disagree. It's in the title that they want the creation date, not a modification date
type: AnswerComment
type: Comment

google-vision
tags question: http://stackoverflow.com/q/49096942
tag name: google-vision
type: Tag

http://stackoverflow.com/a/48967238
score: 7
upvote count: 7
type: AcceptedAnswer
downvote count: 0
has body: Using the same asyncio object from multiple tasks is safe in general. As an example, aiohttp has a session object, and it is expected for multiple tasks to access the same session "in parallel". if so, what does it make safe? The basic architecture of asyncio allows for multiple coroutines to await a single future result - they will simply all subscribe to the future's completion, and all will be scheduled to run once the result is ready. And this applies not only to coroutines, but also to synchronous code that subscribes to the future using add_done_callback. That is how asyncio will handle your scenario: tasks A and B will ultimately subscribe to some future awaited by the DB object and. Once the result is available, it will be delivered to both of them, in turn. Pitfalls typically associated with multi-threaded programming do not apply to asyncio because: Unlike with threads, it is very predictable where a context switch can occur - just look at await statements in the code (and also async with and async for - but those are still very visible keywords). Anything between them is, for all intents and purposes, atomic. This eliminates the need for synchronization primitives to protect objects, as well as the mistakes that result from mishandling such tools. All access to data happens from the thread that runs the event loop. This eliminates the possibility of a data race, reading of shared memory that is being concurrently written to. One scenario in which multi-tasking could fail is multiple consumers attaching to the same stream-like resource. For example, if several tasks try to await reader.read(n) on the same reader stream, exactly one of them will get the new data1, and the others will keep waiting until new data arrives. The same applies to any shared streaming resource, including file descriptors or generators shared by multiple objects. And even then, one of the tasks is guaranteed to obtain the data, and the integrity of the stream object will not be comp…
accepted answer of: http://stackoverflow.com/q/48966277
has comment: http://stackoverflow.com/comment/84945896
answers question: http://stackoverflow.com/q/48966277
type: Answer
has comment: http://stackoverflow.com/comment/84947907

http://stackoverflow.com/comment/85073337
type: Comment
comment on: http://stackoverflow.com/a/49034065
has text: Using `zf.open()` is the key difference, since it allows the file created inside the zip to be written incrementally (thus, with a sane ZipFile implementation, with bounded memory usage).
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85236996
type: QuestionComment
has text: @ImportanceOfBeingErnest I edited my post. There an issue with the plot of Z.
score: 0
comment on: http://stackoverflow.com/q/49115251
type: Comment

http://stackoverflow.com/q/49100946
has answer: http://stackoverflow.com/a/49101445
has body: I'm working with a 3rd party package that defines a result object from an expensive method call on a source object: result_object = source_object.method(input_value). I'd like to modify result_object inside a function call, something like this: def modify_result(result_object, update_value): result_object = source_object.method(update_value) Obviously the posted code won't work; it just creates a local result_object that gets discarded. Instead, I could: make result_object nonlocal in the function, and modify it as above extend the result_object class and add a modify_result method something else? A few clarifications. In this context, is result_object considered global? And more importantly, is there a preferred method to update result_object so other functions can access it?
tagged with: methods
has comment: http://stackoverflow.com/comment/85207186
has comment: http://stackoverflow.com/comment/85207145
type: Question
has comment: http://stackoverflow.com/comment/85207744
has comment: http://stackoverflow.com/comment/85207714
has title: update object with function call
tagged with: scope
score: 0
has comment: http://stackoverflow.com/comment/85207747
tagged with: functional-programming
answer count: 1
has comment: http://stackoverflow.com/comment/85207592
has comment: http://stackoverflow.com/comment/85207147
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85046669
comment on: http://stackoverflow.com/a/48998888
score: 0
type: Comment
has text: No worries. Glad it helped.
type: AnswerComment

http://stackoverflow.com/comment/84997765
comment on: http://stackoverflow.com/q/48995892
score: 0
type: Comment
type: QuestionComment
has text: ffmpeg should be able to connect to a video stream -- You would stop using `requests` altogether and delegate that work to ffmpeg.

http://stackoverflow.com/q/49119536
possible better answer: http://stackoverflow.com/a/49119702
type: Question
has answer: http://stackoverflow.com/a/49119702
tagged with: python
score: -1
tagged with: list
has title: Printing a formatted string from a list up to a specified character
has body: I want to print out a formatted string based on a string that is contained within a list. However, I want to print out the formatted string to stop at a comma. Example: a = ['Apple pie, A couple of oranges, Eggs benedict, Chocolate Milkshake'] I want my formatted string to look like this: Shopping list: Fruits: Apple pie, A couple of oranges Poultry: Eggs benedict Drinks: Chocolate Milkshake How would I go about accomplishing this?
accepted answer: http://stackoverflow.com/a/49119686
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/49120332
has comment: http://stackoverflow.com/comment/85244827
upvote count: 0
has comment: http://stackoverflow.com/comment/85244807
has comment: http://stackoverflow.com/comment/85244754
has comment: http://stackoverflow.com/comment/85244814
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85244571
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49119686
favorite count: 0

http://stackoverflow.com/comment/85223152
comment on: http://stackoverflow.com/q/49108795
has text: Just need merging “value” column from File2 to File1. Unmatched values can be skipped. Will edit my question with desired output soon. Tnx @Batman
score: 0
type: Comment
type: QuestionComment

dictionary
tags question: http://stackoverflow.com/q/49027872
tags question: http://stackoverflow.com/q/49072001
tags question: http://stackoverflow.com/q/49120625
tags question: http://stackoverflow.com/q/48982869
tags question: http://stackoverflow.com/q/49100877
tags question: http://stackoverflow.com/q/49007938
tags question: http://stackoverflow.com/q/49076437
tags question: http://stackoverflow.com/q/48974956
tags question: http://stackoverflow.com/q/49089435
tags question: http://stackoverflow.com/q/49055559
tags question: http://stackoverflow.com/q/49118954
tags question: http://stackoverflow.com/q/49110073
tags question: http://stackoverflow.com/q/49079461
tags question: http://stackoverflow.com/q/49101245
tags question: http://stackoverflow.com/q/48989751
tags question: http://stackoverflow.com/q/49091132
tags question: http://stackoverflow.com/q/49121246
tags question: http://stackoverflow.com/q/48970752
tags question: http://stackoverflow.com/q/49095192
tags question: http://stackoverflow.com/q/48967328
tags question: http://stackoverflow.com/q/49039676
tags question: http://stackoverflow.com/q/49016991
tags question: http://stackoverflow.com/q/49041169
tags question: http://stackoverflow.com/q/49060965
tags question: http://stackoverflow.com/q/48971720
tags question: http://stackoverflow.com/q/49083875
tags question: http://stackoverflow.com/q/49000692
tags question: http://stackoverflow.com/q/49120765
tags question: http://stackoverflow.com/q/48983860
tags question: http://stackoverflow.com/q/49065199
tags question: http://stackoverflow.com/q/49109987
tags question: http://stackoverflow.com/q/49073780
tags question: http://stackoverflow.com/q/49004159
tags question: http://stackoverflow.com/q/49000666
tags question: http://stackoverflow.com/q/48980291
tags question: http://stackoverflow.com/q/48991993
tags question: http://stackoverflow.com/q/49116021
tags question: http://stackoverflow.com/q/48969346
tags question: http://stackoverflow.com/q/49015922
tags question: http://stackoverflow.com/q/49058366
tags question: http://stackoverflow.com/q/49077197
tags question: http://stackoverflow.com/q/49107594
tags question: http://stackoverflow.com/q/49037852
tags question: http://stackoverflow.com/q/49019551
tags question: http://stackoverflow.com/q/48984978
tags question: http://stackoverflow.com/q/49117330
tags question: http://stackoverflow.com/q/49020647
tags question: http://stackoverflow.com/q/48965561
tags question: http://stackoverflow.com/q/48994761
tags question: http://stackoverflow.com/q/48963698
tags question: http://stackoverflow.com/q/49014409
tags question: http://stackoverflow.com/q/49021161
tags question: http://stackoverflow.com/q/49089349
tags question: http://stackoverflow.com/q/49061865
tags question: http://stackoverflow.com/q/49001176
tags question: http://stackoverflow.com/q/48998383
tags question: http://stackoverflow.com/q/49082316
tags question: http://stackoverflow.com/q/48994571
tags question: http://stackoverflow.com/q/48972559
tag name: dictionary
tags question: http://stackoverflow.com/q/48966229
tags question: http://stackoverflow.com/q/49017178
tags question: http://stackoverflow.com/q/49084154
tags question: http://stackoverflow.com/q/49095465
tags question: http://stackoverflow.com/q/48995253
tags question: http://stackoverflow.com/q/49049649
tags question: http://stackoverflow.com/q/48980285
tags question: http://stackoverflow.com/q/48996604
tags question: http://stackoverflow.com/q/49107640
tags question: http://stackoverflow.com/q/49061216
tags question: http://stackoverflow.com/q/49025765
tags question: http://stackoverflow.com/q/49117648
tags question: http://stackoverflow.com/q/49087995
tags question: http://stackoverflow.com/q/49026104
tags question: http://stackoverflow.com/q/49037829
tags question: http://stackoverflow.com/q/49013882
tags question: http://stackoverflow.com/q/48967353
tags question: http://stackoverflow.com/q/49028675
tags question: http://stackoverflow.com/q/49115904
tags question: http://stackoverflow.com/q/49060489

http://stackoverflow.com/q/49065891
score: -2
tagged with: flask
has body: @app.route('/get_all/&lt;string:name&gt;', methods=['GET']) def get_info_of_person(name): if request.method == 'GET': person = [city for city in cities if city['name'] == name] print(person) return jsonify({'names_list': person[0]}) else: return render_template('dashboard.html') I want to capture those values form the front end using Jquery
downvote count: 2
answer count: 1
tagged with: jquery
favorite count: 0
duplicate of: http://stackoverflow.com/q/36143283
has title: How Make a GET request using JQuery, to get the values of flsk api
accepted answer: http://stackoverflow.com/a/49069741
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/49069741
linked to: http://stackoverflow.com/q/36143283
type: Question

http://stackoverflow.com/comment/85159490
type: Comment
comment on: http://stackoverflow.com/q/49074360
score: 0
has text: Define "script doesn't work" so we can fix the actual problem. Mixing patch level revisions of Python with mod_wsgi is usually not a problem as explained in the documentation. See http://modwsgi.readthedocs.io/en/develop/user-guides/installation-issues.html#python-patch-level-mismatch
type: QuestionComment

http://stackoverflow.com/comment/85154731
type: Comment
has text: @amazingcarrotsoup you are welcome! Well, in Python there are bound and unbound methods. Method in your code is bound to specific instance, so you cannot pass any other instance as self argument. Check this question for details https://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static
type: AnswerComment
comment on: http://stackoverflow.com/a/49062624
score: 0

http://stackoverflow.com/q/49085805
has answer: http://stackoverflow.com/a/49085828
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49085825
accepted answer: http://stackoverflow.com/a/49085825
score: 0
tagged with: pandas
tagged with: python
has body: I have a data frame with a column message, and I want to create a column media such that if for index x, df.ix[x][message]=="&lt;Media omitted&gt;" ,then I want df.ix[x][media] = 1 for example for the dataframe: index message 1 hello 2 &lt;Media omitted&gt; 3 hello 4 &lt;Media omitted&gt; I would get: index message media 1 hello 0 2 &lt;Media omitted&gt; 1 3 hello 0 4 &lt;Media omitted&gt; 1 I tried to do so only by using a loop, but I'm sure there is a smarter and faster way.
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49085828
type: AnsweredQuestion
has title: pandas replace specific string with numeric value in a new column for all rows

http://stackoverflow.com/comment/85232280
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49113572
has text: If you have [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) in the loop it will exit the function after the first iteration...

http://stackoverflow.com/a/48969238
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84957471
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48968852
score: 1
accepted answer of: http://stackoverflow.com/q/48968852
has comment: http://stackoverflow.com/comment/87685833
has body: Do you minimize it because you are busy with other things? You can use headless mode once your code is doing what you want visually and avoid this problem.
has comment: http://stackoverflow.com/comment/87593048

http://stackoverflow.com/comment/85233767
score: 0
type: Comment
has text: Yup, sounds unrelated.
comment on: http://stackoverflow.com/a/49113307
type: AnswerComment

http://stackoverflow.com/comment/88728586
type: Comment
score: 1
has text: Hello @Tanvir Ahmed. I am having the same issue "coincidently" in an a2hosting shared hosting plan. Can you tell me if you could find a solution?
comment on: http://stackoverflow.com/q/49028254
type: QuestionComment

http://stackoverflow.com/a/48988390
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48988322
answers question: http://stackoverflow.com/q/48988322
type: Answer
has body: Try using the datetime module. Ex: import datetime s = '20180214_145712' print datetime.datetime.strptime(s, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S") Output: 2018-02-14 14:57:12
downvote count: 0
score: 1

http://stackoverflow.com/comment/85110586
score: 0
has text: Do you know how I get alpha value?
comment on: http://stackoverflow.com/q/49049771
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48995959
has comment: http://stackoverflow.com/comment/84997260
has title: Making a repeating iterator over a range of digits?
tagged with: python
has body: I'm trying to make an iterator that prints the repeating sequence 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, ... I want an iterator so I can use .next(), and I want it to loop around to 0 when .next() is called while the iterator is at 9. But the thing is that I'll probably have a lot of these, so I don't just want to do itertools.cycle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]). I don't want to have that many repeated lists of the same sequence in memory. I'd rather have the function x + 1 % 10 in each of the iterators and just have the iterator increment x every time next is called. I can't seem to figure out how to do this though with itertools. Is there a pythonic way of doing this?
has comment: http://stackoverflow.com/comment/84997310
score: 0
accepted answer: http://stackoverflow.com/a/48996046
has answer: http://stackoverflow.com/a/48996007
has answer: http://stackoverflow.com/a/48996058
has answer: http://stackoverflow.com/a/48996086
possible better answer: http://stackoverflow.com/a/48996058
answer count: 4
tagged with: iterator
type: AnsweredQuestion
tagged with: modulo
has answer: http://stackoverflow.com/a/48996046
type: Question

http://stackoverflow.com/comment/89214674
type: Comment
type: QuestionComment
has text: Thanks for picking my question! As far as I know `tags` are not the same as `initialization`. Would be nice if one can use the flag for initialization in the .tpl
comment on: http://stackoverflow.com/q/48976611
score: 0

http://stackoverflow.com/q/48978654
has body: I'm looking for some help 'cause I'm getting a bit frustrated on this... :-( I have a headless Raspberry PI 3 with a PiFi DAC+ audio card, basically an HiFiBerry clone. On the PI I installed mpd and mpc as a client. On top of those I wrote a python script that invokes some mpc commands to control the underlying mpd daemon (load a playlist, play a stream,...). Now the issue. The overall audio setup based on the hifiberry-dacplus overlay works well, the sound is good and I'm fine with it. Mpc &amp; mpd work, I can control all the functionalities of mpd (at least the ones I need) through mpc without a flaw...but, if I try to run my python script suddenly I cannot hear anything anymore, even if no specific errors are traced. The 'scary' thing is that, after aborting the script execution, I'm no more able to play any sound (I tried with several wav files using aplay), and again no specific errors show up in the log files...looks like someone just 'muted' the volume, but alsamixer shows all playback levels to 100%. I need to reboot the PI to get my sound back. I checked for clues in the usual places: /var/log/messages /var/log/syslog dmesg boot.log /var/log/mpd/mpd.log I also run aplay -vvv when audio was blocked and compared the output with a session where audio was running fine but I didn't notice any difference... I know it would be very difficult to diagnose the problem without having access to my system, but do you have any ideas on where else to look to understand if something went wrong? Just for info, here's my aplay -l output: **** List of PLAYBACK Hardware Devices **** card 0: sndrpihifiberry [snd_rpi_hifiberry_dacplus], device 0: HiFiBerry DAC+ HiFi pcm512x-hifi-0 [] Subdevices: 1/1 Subdevice #0: subdevice #0 Thank you! Michele EDIT: seems like there is some incompatibility between the audio board and a 16x2 LCD display I'm using to show the name of the stream I'm playing. The display is a very common one, based on the HD44780 chip. My code uses the AdaFruit py…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49002784
upvote count: 1
has title: Raspberry Pi 3: Unusual behaviour with mpd, PiFi DAC+ audio
tagged with: audio
score: 1
type: Question
tagged with: raspberry-pi
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/85008860
type: Comment
comment on: http://stackoverflow.com/a/49001722
score: 0
type: AnswerComment
has text: @John1024I have rephrased my questions. Thanks for suggestion.

http://stackoverflow.com/comment/84972592
type: Comment
type: QuestionComment
has text: Typically, you would need a symbol for `0`, and 26 should be the first double-digit number for base 26. Compare bases 2 and 10, where those numbers are the first double digit numbers and digit values range from `0` to `n-1`.
score: 5
comment on: http://stackoverflow.com/q/48983939

http://stackoverflow.com/a/49038613
upvote count: 2
has comment: http://stackoverflow.com/comment/85083902
has comment: http://stackoverflow.com/comment/85083871
has comment: http://stackoverflow.com/comment/85084131
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49037391
has comment: http://stackoverflow.com/comment/85198888
has body: In general, this problem is about finding a Hamiltonian path with a minimum length that is closely related to famous Travelling salesman problem (TSP). And it does not look like a special case of this problem that can be solved in polynomial time. There is a huge amount of heuristics and approximate algorithms for solving TSP. This wikipedia article could be a good place to start.

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

http://stackoverflow.com/comment/85135432
comment on: http://stackoverflow.com/q/49061657
score: 0
has text: Are you sure the content of that page are not generated dynamically? If you are then it's ok otherwise you should use any browser simulator to read the elements and then apply the suggested xpaths or even the way you have defined should do as well.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85000910
type: QuestionComment
comment on: http://stackoverflow.com/q/48997695
score: 0
has text: I meant the class Prot1, defined in the file ./protocols/prot1.py. Is the capitalization messing me up?
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/49031102
tags question: http://stackoverflow.com/q/49067798
tags question: http://stackoverflow.com/q/48973972
tags question: http://stackoverflow.com/q/49019898
tags question: http://stackoverflow.com/q/49007070
tags question: http://stackoverflow.com/q/48967068
tags question: http://stackoverflow.com/q/49006083
tags question: http://stackoverflow.com/q/49084636
tags question: http://stackoverflow.com/q/49003884
tags question: http://stackoverflow.com/q/49069195
tags question: http://stackoverflow.com/q/49007066
tags question: http://stackoverflow.com/q/48999585
tags question: http://stackoverflow.com/q/49121199
tags question: http://stackoverflow.com/q/49077644
tags question: http://stackoverflow.com/q/48982715
tags question: http://stackoverflow.com/q/48992033
tags question: http://stackoverflow.com/q/49009857
tags question: http://stackoverflow.com/q/49019319
tags question: http://stackoverflow.com/q/48983468
tags question: http://stackoverflow.com/q/49012912
tags question: http://stackoverflow.com/q/49020509
tags question: http://stackoverflow.com/q/49108322
tags question: http://stackoverflow.com/q/49116544
tags question: http://stackoverflow.com/q/49013410
tags question: http://stackoverflow.com/q/49062287
tags question: http://stackoverflow.com/q/49026632
tags question: http://stackoverflow.com/q/49075760
tags question: http://stackoverflow.com/q/49120961
tags question: http://stackoverflow.com/q/49037211
tags question: http://stackoverflow.com/q/49081353
tags question: http://stackoverflow.com/q/49049467
tags question: http://stackoverflow.com/q/49047205
tags question: http://stackoverflow.com/q/49012907
tags question: http://stackoverflow.com/q/49116570
tags question: http://stackoverflow.com/q/49014208
tags question: http://stackoverflow.com/q/49112896
tags question: http://stackoverflow.com/q/49041971
tags question: http://stackoverflow.com/q/48997418
tags question: http://stackoverflow.com/q/49006909
tags question: http://stackoverflow.com/q/48979102
tags question: http://stackoverflow.com/q/49053434
tags question: http://stackoverflow.com/q/49107832
tags question: http://stackoverflow.com/q/49014885
tags question: http://stackoverflow.com/q/48970108
tags question: http://stackoverflow.com/q/48966762
tags question: http://stackoverflow.com/q/49065312
tags question: http://stackoverflow.com/q/49075214
tags question: http://stackoverflow.com/q/49067869
tags question: http://stackoverflow.com/q/49100161
tags question: http://stackoverflow.com/q/49019784
tags question: http://stackoverflow.com/q/49093535
tags question: http://stackoverflow.com/q/49005710
tags question: http://stackoverflow.com/q/49076558
tags question: http://stackoverflow.com/q/49102978
tags question: http://stackoverflow.com/q/49080605
tags question: http://stackoverflow.com/q/49029142
tags question: http://stackoverflow.com/q/48964836
tags question: http://stackoverflow.com/q/48979023
tags question: http://stackoverflow.com/q/49095860
tags question: http://stackoverflow.com/q/49091401
tags question: http://stackoverflow.com/q/49083680
tags question: http://stackoverflow.com/q/49056451
tags question: http://stackoverflow.com/q/49093362
tags question: http://stackoverflow.com/q/49089894
tags question: http://stackoverflow.com/q/49071212
tags question: http://stackoverflow.com/q/49081129
tags question: http://stackoverflow.com/q/49027781
tags question: http://stackoverflow.com/q/48999962
tags question: http://stackoverflow.com/q/49084934
tags question: http://stackoverflow.com/q/48995422
tags question: http://stackoverflow.com/q/49058913
tags question: http://stackoverflow.com/q/49079990
tags question: http://stackoverflow.com/q/49089775
tags question: http://stackoverflow.com/q/49117914
tag name: tensorflow
tags question: http://stackoverflow.com/q/49048262
tags question: http://stackoverflow.com/q/48977513
tags question: http://stackoverflow.com/q/49041001
tags question: http://stackoverflow.com/q/49105143
tags question: http://stackoverflow.com/q/48986640

http://stackoverflow.com/comment/85043316
has text: Hi liliscent, thanks for the update. Is this just a matter of esthetic and 'religion' (functional programming vs imperative(?)) or is that actual faster? Maybe it is out of scope but I would appreciate it if you could point me in a direction. Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/49017104
score: 0
type: Comment

http://stackoverflow.com/comment/85183963
has text: You need to check that **all** the strings in `remo` aren't in `website` before adding it: `if all(r not in website for r in remo): websites.add(website)`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49089165
type: Comment
score: 2

http://stackoverflow.com/a/49025728
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49025562
upvote count: 1
has body: This might help # -*- coding: utf-8 -*- s = """ "Envelopes" "Labels" "Pens & Art Supplies" "Rubber Bands" "Scissors, Rulers and Trimmers" """ import xml.etree.ElementTree as et tree = et.fromstring(s) for i in tree.findall('.//data/column/calculation/bin'): for j in i.findall('value'): print(j.text) Output: "Envelopes" "Labels" "Pens & Art Supplies" "Rubber Bands" "Scissors, Rulers and Trimmers"

http://stackoverflow.com/comment/85141935
has text: no tweets will be found for a date older than one week. and you can check for the tweets time if it will falls between your time interval (Note: must not be older than a week) then you can save it otherwise discard it.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49068214

http://stackoverflow.com/q/48968426
tagged with: loops
type: Question
score: 2
downvote count: 0
has title: How to simplify the following code for population genetics simulation?
tagged with: simplify
tagged with: simulation
favorite count: 0
has body: Simulation of random mating between a haploid with all diploids except ones that contain the same haploid as itself. It works but seems super redundant - for example, is dictionary a better way in this case? Here's my code: import numpy as np import itertools N = 100 # number of haploids in the population numGen = 5 # number of generations to simulate gen = {'R0':0.1, 'R1':0.2, 'R2':0.25, 'R3':0.15, 'R4':0.3} # haplotypes w/ frequencies gens = [] for i in range(numGen): Pstls = [*gen] # put keys into list freq = np.round(np.random.multinomial(N, list(gen.values()))/N, 4) gen = dict(zip(Pstls, freq)) mating = [] for i in itertools.combinations(Pstls,2): # random mating mating.append(i) # [('R0', 'R1'), ('R0', 'R2'), ('R0', 'R3'), ('R0', 'R4'), ('R1', 'R2'), \ # ('R1', 'R3'), ('R1', 'R4'), ('R2', 'R3'), ('R2', 'R4'), ('R3', 'R4')] haps = [] haps_freq = [] for i in range(len(gen)): for j in range(len(mating)): if Pstls[i] not in mating[j]: # new haplotype frequencies w/ duplicates hf0 = round(gen[Pstls[i]] * gen[mating[j][0]], 4) hf1 = round(gen[Pstls[i]] * gen[mating[j][1]], 4) hap0 = Pstls[i] + ',' + mating[j][0] hap1 = Pstls[i] + ',' + mating[j][1] haps.append(hap0) haps.append(hap1) haps_freq.append(hf0) haps_freq.append(hf1) newHaps = dict(zip(haps,haps_freq)) keys = [] # preparatory steps for the final dictionary for key in newHaps.keys(): keys.append(key.split(',')) newHaps_freq = [] for i in range(len(mating)): for j in range(len(keys)): if keys[j][0] in mating[i] and keys[j][1] in mating[i]: keys[j][0] = mating[i][0] keys[j][1] = mating[i][1] keys_new = [] for i in range(len(keys)): # remove duplicates if keys[i] not in keys_new: keys_new.append(keys[i]) for i in range(len(keys_new)): newHaps_freq.append(round(newHaps[','.join(keys_new[i])], 4)) # diploid frequencies in the next generation nextGen = dict(zip(mating,newHaps_freq)) print(nextGen) haps_new = [] for i in range(len(Pstls)): newHap = 0 for j in range(len(mating)): if Pstls[i] in mating[j]: newHap +=…
upvote count: 2
type: UnansweredQuestion
tagged with: bioinformatics
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90309657

http://stackoverflow.com/comment/85233035
comment on: http://stackoverflow.com/q/49113933
type: Comment
type: QuestionComment
score: 2
has text: well I'm happy for you

http://stackoverflow.com/q/49111490
has answer: http://stackoverflow.com/a/49111930
upvote count: 1
answer count: 1
tagged with: sorting
favorite count: 0
tagged with: python
has title: Django / Python - sorting different Class objects sharing the same attribute?
downvote count: 0
tagged with: django
has body: So let's say I have the following models in Django: class Review(models.Model): datetime = models.DateTimeField(("Date"), default=timezone.now) class Rating(models.Model): datetime = models.DateTimeField(("Date"), default=timezone.now) And my view looks like this: def get_page(request, id_slug): context_dict = {} reviews = Review.objects.filter(attribute=id_slug).order_by('-datetime') ratings = Rating.objects.filter(attribute=id_slug).order_by('-datetime') context_dict['reviews'] = reviews context_dict['ratings'] = ratings return render(request, 'page.html', context_dict) What I want to do is make a query set that would include both Review and Rating objects, ordered by the datetime attribute, so something like: activity = reviewsANDratings.order_by('-datetime') context_dict['activity'] = activity What would be the best way to achieve this? Thank you!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49111930
score: 1
type: Question

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

http://stackoverflow.com/comment/85185422
type: AnswerComment
has text: I'll give this a go.
type: Comment
comment on: http://stackoverflow.com/a/49089794
score: 0

http://stackoverflow.com/q/48969813
has comment: http://stackoverflow.com/comment/84945508
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48970164
has comment: http://stackoverflow.com/comment/84945514
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 3
tagged with: feature-detection
has comment: http://stackoverflow.com/comment/84945179
accepted answer: http://stackoverflow.com/a/48970164
downvote count: 1
type: Question
has title: Foggy images detection
has body: experts I am doing a project about analysing the green trends of the trees. In term of initial processing, I've got intensity value for the whole 500 images and decided the threshold for selecting good images from the datasets. It's around from 60 to 122, and I named the range as good images. However, the tricky issue was that some of the foggy images were also in that range. The intensity of good images is from 90 to 120, some of the foggy images have the same intensity value compared to the good one. the intensity of iamges So far, it's the code for getting the intensity of one image and the average of the intensity for 500 images im = Image.open('IMAG0087.JPG') im_grey = im.convert('LA') width,height = im.size total=0 for i in range(0,width): for j in range(0,height): total += im.getpixel((i,j))[0] mean = total / (width * height) print mean Getting the average of the intensity for 500 images: results = [] for dirpath, dirnames, filenames in os.walk("/Users/Terrynightbleach/Desktop/Dataset-Tree/No2_Fraser_Gully/"): for filename in [f for f in filenames if f.endswith('.JPG')]: img = cv2.imread(filename) avg_color_per_row = numpy.average(img, axis=0) avg_color = numpy.average(avg_color_per_row, axis=0) results.append(sum(avg_color/3)) np_results = np.array(results) plt.hist(np_results,bins=100) plt.show() Are there any other values that I am supposed to use in order to discard those foggy images out from the datasets? And how should I achieve it by python? That would be really helpful if you could show the code. Thank you so much!!!!!
tagged with: image
has comment: http://stackoverflow.com/comment/84945154

http://stackoverflow.com/q/49092363
upvote count: 4
tagged with: python-2.7
answer count: 1
downvote count: 0
has title: Need to round in multiples of 0.25
favorite count: 0
tagged with: odoo-10
has answer: http://stackoverflow.com/a/49092382
tagged with: python
type: AnsweredQuestion
has body: I need to round the currency amount in 0.25, 0.50, 0.75 and if greater than 0.75, it must round to the next integer. How to do it? Example need to round: 25.91 to 26, 25.21 to 25.25 25.44 to 25.50 and so on.
type: Question
accepted answer: http://stackoverflow.com/a/49092382
tagged with: odoo
duplicate of: http://stackoverflow.com/q/455612
score: 4

http://stackoverflow.com/q/49090600
has title: Text file import to dataframe with pandas: Data in Blocks
has comment: http://stackoverflow.com/comment/85187663
has body: I'm kinda new at using pandas, since I've done most of my data analysis usually with R. Data format can be seen from this link where I got my data from: https://snap.stanford.edu/data/web-Movies.html There are also HTML tags in the review/text attribute as well. So I'm thinking I should get rid of those too when I perform text sentiment analysis on it. Data snippet of a record
tagged with: sentiment-analysis
tagged with: pandas
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85187119
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/85186813
score: 0
type: Question

http://stackoverflow.com/comment/85162400
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49078127
has text: Maybe [this](https://stackoverflow.com/questions/11693819/understanding-recursion-in-python) will clarify.

http://stackoverflow.com/a/49097450
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49096656
has comment: http://stackoverflow.com/comment/85201764
type: Answer
answers question: http://stackoverflow.com/q/49096656
upvote count: 1
has body: By default, replace does not modify the dataframe in-place. Instead, it returns a dataframe with the modifications made. Just change the relevant line of code to: com.replace('?', np.NaN, inplace=True)

http://stackoverflow.com/comment/85053491
type: Comment
type: QuestionComment
has text: I am sorry for the code format since this is my first question in stack overflow and don't have a lot of idea how to post code
comment on: http://stackoverflow.com/q/49024226
score: 0

http://stackoverflow.com/a/49057691
has body: At https://pypi.python.org/pypi/allen-bradley-toolkit/2.0.0 I see that the wheel is only available for Python 3. You're trying to install it with Python 2.7. To publish a universal wheel (suitable for both Py2 and Py3) you need to set [bdist_wheel] universal = 1 in setup.cfg or run python setup.py bdist_wheel --universal
has comment: http://stackoverflow.com/comment/85122945
answers question: http://stackoverflow.com/q/49056702
type: Answer
has comment: http://stackoverflow.com/comment/85120060
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49056702

http://stackoverflow.com/q/49037902
type: AnsweredQuestion
tagged with: interpolation
has comment: http://stackoverflow.com/comment/85081524
has comment: http://stackoverflow.com/comment/85082767
upvote count: 21
type: Question
tagged with: algorithm
has answer: http://stackoverflow.com/a/62220660
score: 21
tagged with: math
has title: How to interpolate a line between two other lines in python
has answer: http://stackoverflow.com/a/49041142
has answer: http://stackoverflow.com/a/72431693
accepted answer: http://stackoverflow.com/a/49041142
has comment: http://stackoverflow.com/comment/85081079
linked to: http://stackoverflow.com/q/47493154
has answer: http://stackoverflow.com/a/49038999
downvote count: 0
favorite count: 0
tagged with: geometry
tagged with: python
answer count: 4
possible better answer: http://stackoverflow.com/a/49038999
has comment: http://stackoverflow.com/comment/85081542
has body: Note: I asked this question before but it was closed as a duplicate, however, I, along with several others believe it was unduely closed, I explain why in an edit in my original post. So I would like to re-ask this question here again. Does anyone know of a python library that can interpolate between two lines. For example, given the two solid lines below, I would like to produce the dashed line in the middle. In other words, I'd like to get the centreline. The input is a just two numpy arrays of coordinates with size N x 2 and M x 2 respectively. Furthermore, I'd like to know if someone has written a function for this in some optimized python library. Although optimization isn't exactly a necessary. Here is an example of two lines that I might have, you can assume they do not overlap with each other and an x/y can have multiple y/x coordinates. array([[ 1233.87375018, 1230.07095987], [ 1237.63559365, 1253.90749041], [ 1240.87500801, 1264.43925132], [ 1245.30875975, 1274.63795396], [ 1256.1449357 , 1294.48254424], [ 1264.33600095, 1304.47893299], [ 1273.38192911, 1313.71468591], [ 1283.12411536, 1322.35942538], [ 1293.2559388 , 1330.55873344], [ 1309.4817002 , 1342.53074698], [ 1325.7074616 , 1354.50276051], [ 1341.93322301, 1366.47477405], [ 1358.15898441, 1378.44678759], [ 1394.38474581, 1390.41880113]]) array([[ 1152.27115094, 1281.52899302], [ 1155.53345506, 1295.30515742], [ 1163.56506781, 1318.41642169], [ 1168.03497425, 1330.03181319], [ 1173.26135672, 1341.30559949], [ 1184.07110925, 1356.54121651], [ 1194.88086178, 1371.77683353], [ 1202.58908737, 1381.41765447], [ 1210.72465255, 1390.65097106], [ 1227.81309742, 1403.2904646 ], [ 1244.90154229, 1415.92995815], [ 1261.98998716, 1428.56945169], [ 1275.89219696, 1438.21626352], [ 1289.79440676, 1447.86307535], [ 1303.69661656, 1457.50988719], [ 1323.80994319, 1470.41028655], [ 1343.92326983, 1488.31068591], [ 1354.31738934, 1499.33260989], [ 1374.48879779, 1516.93734053], [ 1394.66020624, 1534.54207116]]) Visu…

http://stackoverflow.com/q/49054599
tagged with: django
has comment: http://stackoverflow.com/comment/85125472
has comment: http://stackoverflow.com/comment/85122647
type: Question
has body: I have added some translation for my website (running django 1.8) that work fine locally but are not working when deployed. I've checked if the .mo and .po files were commited (They were) and if the MIDDLEWARE_CLASSES had been setup correctly (they were / see below) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Since its working just fine locally (and I've commited the .mo and .po' files) I am beginning to suspect that the issue is that DJango is unable to find the files on the server, but I cannot see how - as my settings should account for this. Here is my LOCALE_PATHS setting: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'),) and below is the folder structure on my locale computer src | |- root |- locale | |---fr | |-LC_MESSAGES | | | |- django.mo | |-django.po | |-static |-app1 |-app2 Does anyone have an idea what I am doing wrong?
score: 0
tagged with: python
has title: Django: Translations not working on S2. Path issue?
tagged with: django-settings
answer count: 0
has comment: http://stackoverflow.com/comment/85134359
type: UnansweredQuestion

http://stackoverflow.com/comment/85200769
comment on: http://stackoverflow.com/a/49096185
type: Comment
type: AnswerComment
has text: Perfect, was a little messy trying to get the chrome driver up and running but works perfect now, thanks very much
score: 0

http://stackoverflow.com/q/48974747
downvote count: 0
has title: numpy function cythonization
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84954748
tagged with: python
has comment: http://stackoverflow.com/comment/84954760
accepted answer: http://stackoverflow.com/a/48977654
has comment: http://stackoverflow.com/comment/84954732
upvote count: 2
has comment: http://stackoverflow.com/comment/84957494
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84960992
tagged with: cython
has body: I have the following function in pure python: import numpy as np def subtractPython(a, b): xAxisCount = a.shape[0] yAxisCount = a.shape[1] shape = (xAxisCount, yAxisCount, xAxisCount) results = np.zeros(shape) for index in range(len(b)): subtracted = (a - b[index]) results[:, :, index] = subtracted return results I tried to cythonize it this way: import numpy as np cimport numpy as np DTYPE = np.int ctypedef np.int_t DTYPE_t def subtractPython(np.ndarray[DTYPE_t, ndim=2] a, np.ndarray[DTYPE_t, ndim=2] b): cdef int xAxisCount = a.shape[0] cdef int yAxisCount = a.shape[1] cdef np.ndarray[DTYPE_t, ndim=3] results = np.zeros([xAxisCount, yAxisCount, xAxisCount], dtype=DTYPE) cdef int lenB = len(b) cdef np.ndarray[DTYPE_t, ndim=2] subtracted for index in range(lenB): subtracted = (a - b[index]) results[:, :, index] = subtracted return results However, Im not seeing any speedup. Is there something I'm missing or this process can't be sped up? EDIT -> I've realized that I'm not actually cythonizing the subtraction algorithm in the above code. I've managed to cythonize it, but it has the exact same runtime as a - b[:, None], so I guess this is the maximum speed of this operation. This is basically a - b[:, None] -> has same runtime %%cython import numpy as np cimport numpy as np DTYPE = np.int ctypedef np.int_t DTYPE_t cimport cython @cython.boundscheck(False) # turn off bounds-checking for entire function @cython.wraparound(False) # turn off negative index wrapping for entire function def subtract(np.ndarray[DTYPE_t, ndim=2] a, np.ndarray[DTYPE_t, ndim=2] b): cdef np.ndarray[DTYPE_t, ndim=3] result = np.zeros([b.shape[0], a.shape[0], a.shape[1]], dtype=DTYPE) cdef int lenB = b.shape[0] cdef int lenA = a.shape[0] cdef int lenColB = b.shape[1] cdef int rowA, rowB, column for rowB in range(lenB): for rowA in range(lenA): for column in range(lenColB): result[rowB, rowA, column] = a[rowA, column] - b[rowB, column] return result
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48977654
has comment: http://stackoverflow.com/comment/84954953

http://stackoverflow.com/q/48965341
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48966730
has title: reshaping in pandas (python)
has comment: http://stackoverflow.com/comment/84939062
has comment: http://stackoverflow.com/comment/84937038
favorite count: 0
has answer: http://stackoverflow.com/a/48969891
accepted answer: http://stackoverflow.com/a/48969891
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: I am trying to reshape this file with pivot and pivoed fonction but without any succes. Every user have two tiestamps, one at 19h and the second at 22h, every user have 3 variable and each variable has 8 index file sample : DATA_STAMP;ID;VARIABLES;INDEX;VALUE 2018-02-19 19:15:25;6550692;count1;3;230993 2018-02-19 19:15:25;6550692;count1;2;0 2018-02-19 19:15:25;6550692;count1;1;34513980 2018-02-19 19:15:25;6550692;count1;0;1500517 2018-02-19 19:15:25;6550692;count1;7;0 2018-02-19 19:15:25;6550692;count1;6;14958246 2018-02-19 19:15:25;6550692;count1;5;0 2018-02-19 19:15:25;6550692;count1;4;156 2018-02-19 19:15:25;6549986;count1;3;5047 2018-02-19 19:15:25;6549986;count1;2;0 2018-02-19 19:15:25;6549986;count1;1;1016836 2018-02-19 19:15:25;6549986;count1;0;265705 2018-02-19 19:15:25;6549986;count1;7;0 2018-02-19 19:15:25;6549986;count1;6;18661246 2018-02-19 19:15:25;6549986;count1;5;0 2018-02-19 19:15:25;6549986;count1;4;0 2018-02-19 19:15:25;6549456;count1;7;0 2018-02-19 19:15:25;6549456;count1;5;164663 2018-02-19 19:15:25;6549456;count1;6;4640344 2018-02-19 19:15:25;6550692;count2;3;230993 2018-02-19 19:15:25;6550692;count2;2;0 2018-02-19 19:15:25;6550692;count2;1;34513980 2018-02-19 19:15:25;6550692;count2;0;1500517 2018-02-19 19:15:25;6550692;count2;7;0 2018-02-19 19:15:25;6550692;count2;6;14958246 2018-02-19 19:15:25;6550692;count2;5;0 2018-02-19 19:15:25;6550692;count2;4;156 2018-02-19 19:15:25;6549986;count2;3;5047 2018-02-19 19:15:25;6549986;count2;2;0 2018-02-19 19:15:25;6549986;count2;1;1016836 2018-02-19 19:15:25;6549986;count2;0;265705 2018-02-19 19:15:25;6549986;count2;7;0 2018-02-19 19:15:25;6549986;count2;6;18661246 2018-02-19 19:15:25;6549986;count2;5;0 2018-02-19 19:15:25;6549986;count2;4;0 2018-02-19 19:15:25;6549456;count2;7;0 2018-02-19 19:15:25;6549456;count2;5;164663 2018-02-19 19:15:25;6549456;count2;6;4640344 2018-02-19 19:15:25;6550692;count2;3;230993 2018-02-19 19:15:25;6550692;count3;2;0 2018-02-19 19:15:25;6550692;count3;1;34513980 2018-02-19 …
downvote count: 3
has answer: http://stackoverflow.com/a/48966730
score: -1
tagged with: reshape2
type: Question

http://stackoverflow.com/comment/85176614
type: Comment
type: QuestionComment
score: 0
has text: What are point, size, and center? Does center contain point and size?
comment on: http://stackoverflow.com/q/49085577

http://stackoverflow.com/comment/85004020
type: AnswerComment
comment on: http://stackoverflow.com/a/48999248
type: Comment
score: 1
has text: It's better to do that in a `with` statement, you'd make less mistakes like that

http://stackoverflow.com/q/48966176
tagged with: tweepy
accepted answer: http://stackoverflow.com/a/48967803
possible better answer: http://stackoverflow.com/a/57875947
has answer: http://stackoverflow.com/a/57875947
type: AnsweredQuestion
upvote count: 9
tagged with: twitter
score: 9
type: Question
answer count: 2
has body: This is my code in python import tweepy import csv consumer_key = "?" consumer_secret = "?" access_token = "?" access_token_secret = "?" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) search_tweets = api.search('trump',count=1,tweet_mode='extended') print(search_tweets[0].full_text) print(search_tweets[0].id) and the output is the following tweet RT @CREWcrew: When Ivanka Trump has business interests across the world, we have to ask if she’s representing the United States or her busi… 967462205561212929 which is truncated, although I used tweet_mode='extended'. How can I extract the full text??
downvote count: 0
has answer: http://stackoverflow.com/a/48967803
favorite count: 0
has title: tweepy: truncated tweets when using tweet_mode='extended'
tagged with: python

http://stackoverflow.com/q/49039113
accepted answer: http://stackoverflow.com/a/49041355
tagged with: arrays
has comment: http://stackoverflow.com/comment/85083573
score: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85085179
tagged with: python-3.x
has body: I am not very familiar with python so I apologise in advance. Is it at all possible to have a numpy array such as numpy.array([a, b, c]) and add that array to an empty numpy array as an element? Assuming this is possible, is it possible to then sum the first value of each element of multiple arrays within the main numpy array. For instance, numpy.array([numpy.array([a,b,c]), numpy.array([d,e,f])]) to then become numpy.array([a + d, b + e, c + f]) I hope I have managed to explain clearly if unsure please feel free to ask me to expand. Many Thanks :-)
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85084010
tagged with: python
has answer: http://stackoverflow.com/a/49041355
linked to: http://stackoverflow.com/q/49032948
has title: Can a numpy array have elements that are numpy arrays themselves?
has answer: http://stackoverflow.com/a/49040128
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49040128
has comment: http://stackoverflow.com/comment/85086561
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/a/49084523
score: 0
has comment: http://stackoverflow.com/comment/85174712
has body: I think you want check by contains with all for check all Trues and then str.replace: df = pd.DataFrame({'A':['123anr12', '345anr12']}) print (df) A 0 123anr12 1 345anr12 if df['A'].str.contains('anr12').all(): df['A'] = df['A'].str.replace('anr12','') print (df) A 0 123 1 345 EDIT1: You can use dictionary for lookup: train_df = pd.DataFrame({'477':['123nbf12', '34nbf12'], '479':['tt1', '32'], '482':['anr1234', '345anr12a12']}) obj_features = ['477', '479', '482'] #it's column names substring = ['nbf', 'tt1', 'anr12'] # get rid of 'nbf', 'tt1', 'anr12' substrings d = dict(zip(obj_features, substring)) print (d) {'477': 'nbf', '479': 'tt1', '482': 'anr12'} for k, v in d.items(): if train_df[k].str.contains(v).all(): train_df[k] = train_df[k].str.replace(v,'') print (train_df) 477 479 482 0 12312 tt1 34 1 3412 32 345a12
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85174794
accepted answer of: http://stackoverflow.com/q/49084484
has comment: http://stackoverflow.com/comment/85175917
type: Answer
answers question: http://stackoverflow.com/q/49084484
has comment: http://stackoverflow.com/comment/85174925
has comment: http://stackoverflow.com/comment/85175911
has comment: http://stackoverflow.com/comment/85174433
has comment: http://stackoverflow.com/comment/85174390

http://stackoverflow.com/q/49032610
has answer: http://stackoverflow.com/a/49034819
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85071953
answer count: 1
has comment: http://stackoverflow.com/comment/85071902
favorite count: 0
has title: how to sort out files according to excel
has comment: http://stackoverflow.com/comment/85071652
tagged with: python
accepted answer: http://stackoverflow.com/a/49034819
has comment: http://stackoverflow.com/comment/85070357
has comment: http://stackoverflow.com/comment/85069954
has comment: http://stackoverflow.com/comment/85071703
downvote count: 2
upvote count: 1
tagged with: excel
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85073031
linked to: http://stackoverflow.com/q/123198
has body: I have an Excel file that contains long product tag name like(for now, just working on 3 of them): 4049047000037 4049047000044 4049047118954 and i have a folder on my desktop called "1" containing .jpg files with tag names like: 4049047000037.jpg 4049047000044.jpg 4049047118954.jpg i want to write a code, if tag name in my excel, i want to copy that .jpg file to an other folder. import os import pandas as pd movdir = ["C:\Users\muhammedcan\Desktop\1"] basedir = "C:\Users\muhammedcan\Desktop\2" i=0 #to see what i have in my folder print os.listdir("C:/Users/muhammedcan/Desktop/1/") df= pd.read_excel("deneme.xls", sheetname= "sayfa4") df1= df.columns[1] listSepalWidth = df[df1] print listSepalWidth #to make file name and product tag name same for i in listSepalWidth: i=str(i)+(".jpg") print i can you help me with copying file into an other file if it is exist in my excel? this is my result so far: ['4049047000037.jpg', '4049047000044.jpg', '4049047000068.jpg', '4049047000075.jpg', '4049047000082.jpg', '4049047000105.jpg', '4049047118947.jpg', '4049047118954.jpg'] 4049047000037.jpg 4049047000044.jpg 4049047118954.jpg 4049047000068.jpg 4049047000075.jpg 4049047000082.jpg 4049047118947.jpg 4049047000105.jpg I used following code, and I am recieving error. from shutil import copyfile copyfile("C:\Users\muhammedcan\Desktop\1", "C:\Users\muhammedcan\Desktop\2") Error is: C:\Python27\python.exe "C:/Users/muhammedcan/Desktop/summer courses/programing/MP4/solution/my_work.py" Traceback (most recent call last): File "C:/Users/muhammedcan/Desktop/summer courses/programing/MP4/solution/my_work.py", line 3, in &lt;module&gt; copyfile("C:\Users\muhammedcan\Desktop\1", Process finished with exit code 1
score: -1
has comment: http://stackoverflow.com/comment/85070154

http://stackoverflow.com/comment/85113895
type: QuestionComment
score: 0
type: Comment
has text: Thank you guys for the suggestions. I am thinking about checking the filesize, therefore to copy again the file if the sizes of src and dst do not match.
comment on: http://stackoverflow.com/q/49054134

http://stackoverflow.com/comment/84987736
has text: Yes `r` will work out to be a scalar (The Rayleigh Quotient is a single scalar value). And I think this is where I am not sure, maybe need some Math.Stack in here. From how I understand it, I need to basically plot a unit sphere, as a surface plot, with a scalar value at each point on the sphere. So kind of a "warped sphere" so to say. `r` (well `rps`) represents the distance of each point on the unit sphere from the origin.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48981986

http://stackoverflow.com/comment/85004414
type: Comment
has text: Remember to change the output hour from 7 to 19 as well.
comment on: http://stackoverflow.com/a/48998730
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85203185
has text: `[]*10` is just an empty list `[]`. Lists don't really have slots, you can keep adding items with `anyList.append(item)`
comment on: http://stackoverflow.com/q/49098955
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/a/49118318
score: 10
has body: I would say that the recommended way to install anaconda is to use the official anaconda installer, which can be downloaded from the link I just posted. I've done it several times, never had a problem, and it walks you through it (including an option to automatically add it to your PATH).
answers question: http://stackoverflow.com/q/49118277
has comment: http://stackoverflow.com/comment/107749938
upvote count: 10
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85191374
comment on: http://stackoverflow.com/a/49093098
score: 0
type: AnswerComment
type: Comment
has text: Take a look at [List comphrehensions](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python). If you have any more doubts, feel free to ask. Also, I've made a small change in the `for` loop. Take a look. I think it's easier to understand.

http://stackoverflow.com/q/49011508
favorite count: 0
has comment: http://stackoverflow.com/comment/85028249
linked to: http://stackoverflow.com/q/48672130
type: Question
upvote count: 2
has title: Latency in large file analysis with python pandas
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/49018264
has comment: http://stackoverflow.com/comment/85038045
has comment: http://stackoverflow.com/comment/85027645
has comment: http://stackoverflow.com/comment/85037138
tagged with: numpy
has body: I have a very large file (10 GB) with approximately 400 billion lines, it is a csv with 4 fields. Here the description, the first field is an ID and the second is a current position of the ID, the third field is a correlative number assigned to that row. Similar to this: 41545496|4154|1 10546767|2791|2 15049399|491|3 38029772|491|4 15049399|1034|5 My intention is to create a fourth column (old position) in another file or the same, where the previous position in which your ID was stored is stored, what I do is verify if the ID number has already appeared before, I look for its last appearance and assigned to his field of old position, the position he had in the last appearance. If the ID has not appeared before, then I assign to its old position the current position it has in that same row. Something like this: 41545496|4154|1|4154 10546767|2791|2|2791 15049399|491|3|491 38029772|491|4|491 15049399|1034|5|491 I have created a program that does the reading and analysis of the file but performs a reading of 10 thousand lines every minute, so it gives me a very high time to read the entire file, more than 5 days approximately. import pandas as pd with open('file_in.csv', 'rb') as inf: df = pd.read_csv(inf, sep='|', header=None) cont = 0 df[3] = 0 def test(x): global cont a = df.iloc[:cont,0] try: index = a[a == df[0][cont]].index[-1] df[3][cont] = df[1][index] except IndexError: df[3][cont] = df[1][cont] pass cont+= 1 df.apply(test, axis=1) df.to_csv('file_out.csv', sep='|', index=False, header=False) I have a computer 64 processors with 64 GB of RAM in the university but still it's a long time, is there any way to reduce that time? thank you very much!
has comment: http://stackoverflow.com/comment/85027685
downvote count: 0
accepted answer: http://stackoverflow.com/a/49018264
has comment: http://stackoverflow.com/comment/85027789
has comment: http://stackoverflow.com/comment/85028020
tagged with: pandas
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85027954

http://stackoverflow.com/a/49069793
score: 2
type: AcceptedAnswer
downvote count: 0
has body: We managed to fix this. First of all these two copied below lines are deprecated. They can be removed. self.position_attribute.setDataType(Qt3DRender.QAttribute.Float) self.position_attribute.setDataSize(3) One line is added: self.position_attribute.setVertexSize(3) ByteStride should be set to 12. 3 is the number of coordinates and 4 is length of float32 in bytes. Be aware to set numpy's array: data = np.random.rand(1000, 3).astype(np.float32). self.position_attribute.setByteOffset(0) self.position_attribute.setByteStride(3*4) self.position_attribute.setCount(1000)
accepted answer of: http://stackoverflow.com/q/49049828
upvote count: 2
answers question: http://stackoverflow.com/q/49049828
type: Answer

http://stackoverflow.com/comment/85061576
score: 0
comment on: http://stackoverflow.com/q/49028221
has text: the issue is it's not printing to cmd as it's being run by another .exe. Maybe the question should be, how do you get python to print to cmd when executed by another program?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49084322
type: AnsweredQuestion
upvote count: 19
has comment: http://stackoverflow.com/comment/85564018
linked to: http://stackoverflow.com/q/18797593
downvote count: 1
tagged with: graphene-python
type: Question
has comment: http://stackoverflow.com/comment/85507443
has body: Let's say I have a model: class Employee(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=60) salary = models.DecimalField(decimal_places=2) I want anyone to be able to access first_name and last_name but only want certain users to be able to read salary because this is confidential data. And then I want to restrict write/update for salary to an even different kind of user. How do I restrict field read/write/update depending on the request user? EDIT: This is in the GraphQL API context. I am using Graphene. I'd like to see a scalable solution in the resolver function.
answer count: 2
has title: How to limit field access on a model based on user type on Graphene/Django?
score: 18
linked to: http://stackoverflow.com/q/9766940
possible better answer: http://stackoverflow.com/a/49982983
has answer: http://stackoverflow.com/a/49283138
accepted answer: http://stackoverflow.com/a/49283138
has comment: http://stackoverflow.com/comment/85537394
tagged with: graphene-django
favorite count: 0
has comment: http://stackoverflow.com/comment/85508275
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49982983
has comment: http://stackoverflow.com/comment/85537329

http://stackoverflow.com/comment/85200701
type: QuestionComment
comment on: http://stackoverflow.com/q/49096915
score: 0
has text: In highschool geometry, how wide is a line? 1 unit?
type: Comment

regex
tags question: http://stackoverflow.com/q/48964787
tags question: http://stackoverflow.com/q/49059091
tags question: http://stackoverflow.com/q/49088805
tags question: http://stackoverflow.com/q/49091931
tags question: http://stackoverflow.com/q/48999731
tags question: http://stackoverflow.com/q/49077374
tags question: http://stackoverflow.com/q/49012294
tags question: http://stackoverflow.com/q/49090296
tags question: http://stackoverflow.com/q/48996597
tags question: http://stackoverflow.com/q/48997196
tags question: http://stackoverflow.com/q/49042138
tag name: regex
tags question: http://stackoverflow.com/q/49040728
tags question: http://stackoverflow.com/q/48963908
tags question: http://stackoverflow.com/q/49109400
tags question: http://stackoverflow.com/q/49052446
tags question: http://stackoverflow.com/q/49061099
tags question: http://stackoverflow.com/q/48996879
tags question: http://stackoverflow.com/q/49114778
tags question: http://stackoverflow.com/q/49082387
tags question: http://stackoverflow.com/q/49068875
tags question: http://stackoverflow.com/q/49100785
tags question: http://stackoverflow.com/q/49040641
tags question: http://stackoverflow.com/q/49023967
tags question: http://stackoverflow.com/q/49087282
tags question: http://stackoverflow.com/q/49093971
tags question: http://stackoverflow.com/q/49100697
tags question: http://stackoverflow.com/q/49052931
tags question: http://stackoverflow.com/q/48996450
tags question: http://stackoverflow.com/q/49072373
tags question: http://stackoverflow.com/q/49004693
tags question: http://stackoverflow.com/q/49094060
tags question: http://stackoverflow.com/q/49084713
tags question: http://stackoverflow.com/q/48989493
tags question: http://stackoverflow.com/q/48992644
tags question: http://stackoverflow.com/q/49000574
tags question: http://stackoverflow.com/q/48967376
tags question: http://stackoverflow.com/q/49037981
tags question: http://stackoverflow.com/q/49076311
tags question: http://stackoverflow.com/q/49101962
tags question: http://stackoverflow.com/q/49101366
tags question: http://stackoverflow.com/q/49110029
tags question: http://stackoverflow.com/q/49112001
tags question: http://stackoverflow.com/q/48969862
tags question: http://stackoverflow.com/q/49062324
tags question: http://stackoverflow.com/q/49076253
tags question: http://stackoverflow.com/q/49046242
tags question: http://stackoverflow.com/q/49034670
tags question: http://stackoverflow.com/q/49097580
tags question: http://stackoverflow.com/q/48981566
tags question: http://stackoverflow.com/q/49042181
tags question: http://stackoverflow.com/q/49086900
tags question: http://stackoverflow.com/q/48981348
tags question: http://stackoverflow.com/q/49051765
tags question: http://stackoverflow.com/q/49073252
tags question: http://stackoverflow.com/q/49033871
tags question: http://stackoverflow.com/q/49068634
tags question: http://stackoverflow.com/q/49054634
tags question: http://stackoverflow.com/q/49084068
tags question: http://stackoverflow.com/q/48978912
tags question: http://stackoverflow.com/q/49071158
tags question: http://stackoverflow.com/q/49084471
tags question: http://stackoverflow.com/q/49086222
tags question: http://stackoverflow.com/q/49085756
tags question: http://stackoverflow.com/q/49008237
tags question: http://stackoverflow.com/q/48993565
tags question: http://stackoverflow.com/q/49107547
tags question: http://stackoverflow.com/q/49079552
tags question: http://stackoverflow.com/q/49011340
tags question: http://stackoverflow.com/q/49016826
tags question: http://stackoverflow.com/q/49095596
tags question: http://stackoverflow.com/q/49057818
tags question: http://stackoverflow.com/q/48985667
tags question: http://stackoverflow.com/q/49082093
tags question: http://stackoverflow.com/q/49034083
tags question: http://stackoverflow.com/q/49113646
tags question: http://stackoverflow.com/q/48976751
tags question: http://stackoverflow.com/q/48969595
tags question: http://stackoverflow.com/q/48980725
tags question: http://stackoverflow.com/q/48976701

http://stackoverflow.com/comment/85065871
has text: Thanks! This worked. I just needed to increment all numbers in indices with 2, because I start from r = 2.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49029964

http://stackoverflow.com/a/49117344
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49117074
score: 2
has comment: http://stackoverflow.com/comment/85241279
downvote count: 0
has body: Normally, it's not nice to download and install things on behalf of somebody running your script. As triplee's answer mentions, using a requirements.txt and a proper setup.py is a standard and far better practice. At any rate, the following is a hack to get the behavior you want in a script. import pip import importlib modules = ['requests', 'fake_module_name_that_does_not_exist'] for modname in modules: try: # try to import the module normally and put it in globals globals()[modname] = importlib.import_module(modname) except ImportError as e: result = pip.main(['install', modname]) if result != 0: # if pip could not install it reraise the error raise else: # if the install was sucessful, put modname in globals globals()[modname] = importlib.import_module(modname) If you were to execute this example, you would get output something like as follows Collecting requests Using cached requests-2.18.4-py2.py3-none-any.whl Requirement already satisfied: idna&lt;2.7,&gt;=2.5 in c:\users\spenceryoung\envs\test_venv\lib\site-packages (from requests) Requirement already satisfied: urllib3&lt;1.23,&gt;=1.21.1 in c:\users\spenceryoung\envs\test_venv\lib\site-packages (from requests) Requirement already satisfied: chardet&lt;3.1.0,&gt;=3.0.2 in c:\users\spenceryoung\envs\test_venv\lib\site-packages (from requests) Requirement already satisfied: certifi&gt;=2017.4.17 in c:\users\spenceryoung\envs\test_venv\lib\site-packages (from requests) Installing collected packages: requests Successfully installed requests-2.18.4 Collecting fake_module_name_that_does_not_exist Could not find a version that satisfies the requirement fake_module_name_that_does_not_exist (from versions: ) No matching distribution found for fake_module_name_that_does_not_exist Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; File "C:\Users\spenceryoung\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name…

http://stackoverflow.com/comment/85099733
has text: @Norrius that is correct, but it makes the explanation easier :) The scoping rules also apply for these types, though.
type: Comment
comment on: http://stackoverflow.com/a/49047038
score: 1
type: AnswerComment

http://stackoverflow.com/comment/85047011
comment on: http://stackoverflow.com/a/49020876
score: 0
type: AnswerComment
has text: Can you please explain your `hits()` and `hits` variable?
type: Comment

http://stackoverflow.com/q/49011034
tagged with: python
type: UnansweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/49011189
has body: I have a dataframe with columns containing values like P123Y8O9 mixture of numbers and characters and if I apply sort function to this particular series in dataframe, it sorts the strings basis first digit then second and so on, what I want is to sort the strings basis first all numbers like 32456789 and then mixed strings like 2AJ6JH67 you can see that in above example numerically 2 (first digit of 2AJ6JH67) comes before 3 (first digit of 32456789) but the sorting is to be done 32456789 first and then 2AJ6JH67 How to sort dataframes this way?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85026636
has title: Sortings pandas dataframe numbers first then strings
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/85033759
comment on: http://stackoverflow.com/q/48998130
score: 0
has text: 1. unsure of my JDK version. any idea how to pull that info?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49116926
has body: in my django project, I have a an __init__.py file that imports celery, I suspect this may be causing tox to complain. /testproj/testproj/ ____init___.py from .celery import app as celery_app when I run tox, the tests successfully run, but I see this error. File "/dir/work/testproj/testproj/celery.py", line 2, in &lt;module&gt; from celery import Celery ImportError: cannot import name Celery mobilereports installed: amqp==1.4.9,anyjson==0.3.3,appdirs==1.4.0,Babel==2.3.4,billiard==3.3.0.23,cached-property==1.3.0,celery==3.1.24 What I find strange is that the import error is above the actual imports where celery gets imported. Why am I getting this error? Celery is in my requirements.txt which is being installed by tox as you can see above, so why would I get an import error before the deps actually get installed? tox.ini [tox] envlist = mobilereports skipsdist = True [env] commands = ./runtests.sh setenv = DJANGO_SETTINGS_MODULE=testproj.settings PYTHONPATH={toxinidir} [base] deps = -r{toxinidir}/requirements.txt [env:testproj] basepython = python3 deps = {[base]deps}
tagged with: tox
has comment: http://stackoverflow.com/comment/85241557
has comment: http://stackoverflow.com/comment/85241530
score: 0
has comment: http://stackoverflow.com/comment/85242755
answer count: 1
has comment: http://stackoverflow.com/comment/85271876
has answer: http://stackoverflow.com/a/49117107
type: UnansweredQuestion
tagged with: django
has title: why am i getting a tox import error before the dependencies are installed
tagged with: python
has comment: http://stackoverflow.com/comment/85239162
has comment: http://stackoverflow.com/comment/85242743
type: Question

http://stackoverflow.com/q/49017547
type: Question
has body: I am trying to make a bot for my college website. In that website verification is done in two stages in 1st stage only username and in 2nd step only password is needed. But for out purpose we can directly go on password page because username gets embeded in url. This is the link http://mydy.dypatil.edu/rait/login/index.php?uname=san.yad.rt15@rait.ac.in&amp;wantsurl=. Following is the my code. import requests from lxml import html session_requests = requests.session() login_url = "http://mydy.dypatil.edu/rait/login/index.php?uname=san.yad.rt15@rait.ac.in&amp;wantsurl=" result = session_requests.get(login_url) form_data = { "uname_static": "san.yad.rt15@rait.ac.in", "username": "san.yad.rt15@rait.ac.in", "uname": "san.yad.rt15@rait.ac.in", "password": "dypatil@123" } result = session_requests.post( login_url, data=form_data, headers=dict(referer=login_url) ) url = "http://mydy.dypatil.edu/rait/my/" result = session_requests.get( url, headers = {"Cache-Control": "no-store, no-cache, must-revalidate, post-check=0, pre-check=0", "Connection": "Keep-Alive", "Content-Language": "en", "Content-Length": "427", "Content-Type": "text/html; charset=utf-8", "Keep-Alive": "timeout=5, max=98", "Location": "http://mydy.dypatil.edu/rait/", "Pragma": "no-cache", "Server": "Apache/2.4.6 (CentOS) PHP/5.4.16", "X-Powered-By": "PHP/5.4.16"} ) tree = html.fromstring(result.content) print(tree.text) # subjects = tree.xpath('//*[@class="launchbutton"/@href]') # # for subject in subjects: # print(subject) This does not show any error. Also when i check status code it shows 200 Ok. But in reponse print(tree.text) it shows couple of bank line. Can you correct me anywhere..
score: 0
answer count: 1
tagged with: lxml
has answer: http://stackoverflow.com/a/49017837
tagged with: python
has title: couln't get response of webpage in requests
type: UnansweredQuestion
tagged with: web-scraping
tagged with: request

http://stackoverflow.com/q/49093971
has title: use regular expression to replace extra quote inside json
has comment: http://stackoverflow.com/comment/85194992
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/48817143
has answer: http://stackoverflow.com/a/49095348
has answer: http://stackoverflow.com/a/49094332
accepted answer: http://stackoverflow.com/a/49094332
has body: I got an unexpected quote in my json string that make json.loads(jstr) fails. json_str = '''{"id":"9","ctime":"2018-02-13","content":"abcd: "efg.","hots":"103b","date_sms":"2017-11-22"}''' So I'd like to use the regular expression to match and delete the quote inside the value of "content". I tried something in other solution: import re json_str = '''{"id":"9","ctime":"2018-02-13","content":"abcd: "efg.","hots":"103b","date_sms":"2017-11-22"}''' pa = re.compile(r'(:\s+"[^"]*)"(?=[^"]*",)') pa.findall(json_str) [out]: [] Is there any way to fix the string?
tagged with: regex
upvote count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/49095348
downvote count: 2
tagged with: python
tagged with: regular-language
score: 2
has comment: http://stackoverflow.com/comment/85193200
type: AnsweredQuestion

http://stackoverflow.com/a/49087055
answers question: http://stackoverflow.com/q/49086962
has comment: http://stackoverflow.com/comment/85179497
upvote count: 1
score: 1
has body: Trust in Python's concept of simplicity: a = np.asarray([0.1, 0.2, 0.3, 0.4]) df1 *= a #output A B C D 0 0.1 0.4 0.9 1.6 1 0.5 2.0 4.5 8.0 2 1.0 4.0 9.0 16.0 This re-calculates the values in your data frame as desired because it utilises numpy broadcasting. As @Alex mentioned in the comments, you don't need a numpy array as factor a, a Python list will work equally well. And the concept can of course be extended, you don't need to apply it to the whole data frame: b = [0.3, 0.7] df1"A", "D" += b
has comment: http://stackoverflow.com/comment/85179449
has comment: http://stackoverflow.com/comment/85180002
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85178893
has text: Give a [**Minimal, Complete, Verifiable** Example](https://stackoverflow.com/help/how-to-ask) in your question. In your case some rows from `input_csv` would help.
comment on: http://stackoverflow.com/q/49086707
type: Comment
type: QuestionComment
score: 1

performance-testing
tags question: http://stackoverflow.com/q/48998314
tag name: performance-testing
type: Tag

http://stackoverflow.com/comment/86756988
type: AnswerComment
score: 0
has text: Thanks, I added the import clauses in the message.
comment on: http://stackoverflow.com/a/49048153
type: Comment

http://stackoverflow.com/q/48981022
has comment: http://stackoverflow.com/comment/84967591
has body: I want to make dilated convolution on a feature. In tensorflow I found tf.nn.convolution and tf.nn.conv2d. But tf.nn.conv2d doesn't seem to support dilated convolution. So I tried using tf.nn.convolution. Do the 2 formulations below give the same result? tf.nn.conv2d(x, w, strides=[1, 1, 2, 2], padding='SAME',data_format='NCHW') tf.nn.convolution(x, w, strides=[1, 1, 2, 2], padding='SAME',data_format='NCHW')
score: 2
has comment: http://stackoverflow.com/comment/84967404
has comment: http://stackoverflow.com/comment/84967990
tagged with: tensorflow
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84967710
tagged with: neural-network
downvote count: 0
has answer: http://stackoverflow.com/a/54447128
has answer: http://stackoverflow.com/a/48981142
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/84967751
has title: what is the difference between tf.nn.convolution and tf.nn.conv2d?
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/85191964
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49093410
has text: Search it online ?

http://stackoverflow.com/comment/84947928
comment on: http://stackoverflow.com/a/48971352
type: AnswerComment
score: 0
has text: yes that's a good call. I have never played with the `monitor` param. May be it does support `callable`. Anyway if your query is resolved please mark as answer so that others searching for something similar will be able to find the help. Otherwise, post the answer yourself in case you have figured it out and mark it
type: Comment

http://stackoverflow.com/comment/85117135
comment on: http://stackoverflow.com/q/49056200
score: 1
has text: Well, for starters you're dealing with lists. Arrays are a separate data type that can't change size dynamically. However, even with lists you can't access elements beyond the list size, so you probably change the assignment to `... .apppend(m)`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84936380
type: Comment
has text: Alright. Is there any way better suited than a while loop for trying to get around this? :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48965249

http://stackoverflow.com/q/49018087
score: 0
has comment: http://stackoverflow.com/comment/85041975
has comment: http://stackoverflow.com/comment/85042423
has comment: http://stackoverflow.com/comment/85042397
has body: I'm doing a 'side project' in school that quizzes users and then saves their results into a report (csv file). So far, I've made one report where the 'customer' I'm making the quiz for (Fergus) can search for a specific user and see their progress in quizzes they've done and that's gone fine, but I'm struggling with the second report. For the second report, Fergus has to enter the topic of a certain subject (maths, english, science, etc) and a difficulty level (easy, hard, etc) and it SHOULD spit out a report stating the average score achieved on this quiz. I tried to find the average via adding up all of the individual scores and then diving it by the amount of times people have taken that particular quiz, but there seems to be an issue when reading the file as it is just reading all the results as zero. Meaning that when the overall score is about to be divided by the number of times the quiz has been taken, it shows up with an error saying I tried to divide by zero. def quizReport(): overall=0 amount=0 subjectInput=input("\nPlease enter the subject name of the quiz(zes) you wish to view: ") difficultyInput=input("Please enter the difficulty level of the quiz(zes) you wish to view: ") with open ('reportForFergusTwo.csv') as quizzReport: quizReportReader=csv.reader(quizzReport) for column in quizReportReader: if subjectInput == column[0]: if difficultyInput == column[1]: if ('0') == column[2]: amount=amount+1 if ('1') == column[2]: overall=overall+1 amount=amount+1 if ('2') == column[2]: overall=overall+2 amount=amount+1 if ('3') == column[2]: overall=overall+3 amount=amount+1 if ('4') == column[2]: overall=overall+4 amount=amount+1 if ('5') == column[2]: overall=overall+5 amount=amount+1 if ('6') == column[2]: overall=overall+6 amount=amount+1 if ('7') == column[2]: overall=overall+7 amount=amount+1 if ('8') == column[2]: overall=overall+8 amount=amount+1 if ('9') == column[2]: overall=overall+9 amount=amount+1 if ('10') == column[2]: overall=overall+10 amount=amo…
has comment: http://stackoverflow.com/comment/85042787
has comment: http://stackoverflow.com/comment/85042320
has comment: http://stackoverflow.com/comment/85042311
has comment: http://stackoverflow.com/comment/85041610
has comment: http://stackoverflow.com/comment/85042090
type: Question
has comment: http://stackoverflow.com/comment/85041421
has comment: http://stackoverflow.com/comment/85042817
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85043010
accepted answer: http://stackoverflow.com/a/49018356
has comment: http://stackoverflow.com/comment/85042845
has comment: http://stackoverflow.com/comment/85042424
has comment: http://stackoverflow.com/comment/85043269
has comment: http://stackoverflow.com/comment/85043305
has comment: http://stackoverflow.com/comment/85043394
has comment: http://stackoverflow.com/comment/85042923
answer count: 1
has comment: http://stackoverflow.com/comment/85042194
has comment: http://stackoverflow.com/comment/85042780
has comment: http://stackoverflow.com/comment/85043186
has comment: http://stackoverflow.com/comment/85042375
has comment: http://stackoverflow.com/comment/85042711
has comment: http://stackoverflow.com/comment/85041517
has comment: http://stackoverflow.com/comment/85043137
has comment: http://stackoverflow.com/comment/85041718
has comment: http://stackoverflow.com/comment/85042831
has comment: http://stackoverflow.com/comment/85042150
has comment: http://stackoverflow.com/comment/85042496
has answer: http://stackoverflow.com/a/49018356
has title: Creating a report via reading from a csv file
has comment: http://stackoverflow.com/comment/85041868
has comment: http://stackoverflow.com/comment/85042438
tagged with: python
has comment: http://stackoverflow.com/comment/85041785
has comment: http://stackoverflow.com/comment/85043489
has comment: http://stackoverflow.com/comment/85042668
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85042716
has comment: http://stackoverflow.com/comment/85043299

http://stackoverflow.com/comment/85229075
type: QuestionComment
has text: Try [`^\d{4}[A-Z]{2}[a-z]{2}_filename_\d{8}_\d{6}\.csv$`](https://regex101.com/r/ZIXrLM/1)
comment on: http://stackoverflow.com/q/49112001
score: 0
type: Comment

http://stackoverflow.com/q/49001510
has comment: http://stackoverflow.com/comment/85008087
tagged with: matrix
tagged with: python
type: AnsweredQuestion
score: -4
accepted answer: http://stackoverflow.com/a/49002303
type: Question
has comment: http://stackoverflow.com/comment/85007975
tagged with: matrix-multiplication
has title: Python Matrix multiplication solve Ax <=b
tagged with: numpy
downvote count: 4
upvote count: 0
answer count: 1
favorite count: 0
has body: not sure how to solve this problem with Python Have a 3x3 matrix which is A 3x1 matrix (unknown) which is X and b which is known How can I find all the solutions which is Ax &lt;= b? Thanks in advance
has answer: http://stackoverflow.com/a/49002303

http://stackoverflow.com/q/48974103
has comment: http://stackoverflow.com/comment/84953468
has body: I have been writing a short piece of python code to download a data file from a website and write it to a text file (which it does successfully). Now I want to take that text file and convert it to CSV format. I have been using the responses from questions like "How to convert from txt to csv" but still come to the same end, which is that the CSV file is created successfully and the code executes without error, only the CSV file is empty, short of the column titles I have defined. import csv import requests res = requests.get('https://www.physics.rutgers.edu/~saurabh/mlcs2k2/vectors_R.dat') res.status_code = requests.codes.ok textfile = open("textfile.txt","w") textfile.write(res.text) with open('textfile.txt', 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line.split(",") for line in stripped if line) with open('csvfile.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerow(('Phase', 'M^0_R', 'P_R', 'Q_R')) #Prints correctly writer.writerows(lines)
score: 0
has comment: http://stackoverflow.com/comment/84953174
has answer: http://stackoverflow.com/a/48974270
answer count: 1
has comment: http://stackoverflow.com/comment/84953225
has title: Empty file after converting from text to CSV
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/84953348
type: Question

http://stackoverflow.com/a/48972623
accepted answer of: http://stackoverflow.com/q/48972271
answers question: http://stackoverflow.com/q/48972271
has comment: http://stackoverflow.com/comment/84953115
type: Answer
has comment: http://stackoverflow.com/comment/84952994
has body: Try this aggregation pipeline to partition the prices and calculate average for each partition, replace all 2 to 10, to partition by 10 db.avgs.aggregate([ {$sort : {_id : 1}}, {$group : {_id : null, prices : {$push : "$price"}}}, {$project : { _id : 0, average : { $map : { input : {$range : [0, {$ceil : {$divide : [{$size : "$prices"},2]}}]}, as : "r", in : {$avg : {$slice : ["$prices", {$multiply : ["$$r", 2]}, 2]}} } }}} ]).pretty() result { "average" : [ 15, 5, 10 ] }
score: 0
has comment: http://stackoverflow.com/comment/84952965
type: AcceptedAnswer

get
tags question: http://stackoverflow.com/q/48998664
tags question: http://stackoverflow.com/q/49017670
tags question: http://stackoverflow.com/q/48964776
type: Tag
tag name: get
tags question: http://stackoverflow.com/q/49113616

http://stackoverflow.com/q/48979759
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84964952
has comment: http://stackoverflow.com/comment/84964728
tagged with: matplotlib
linked to: http://stackoverflow.com/q/27694221
type: Question
has title: How to make comparative two-way bar graphs on matplotlib?
has comment: http://stackoverflow.com/comment/84964909
has body: Two way bar chart this is a link to the image for a two way bar chart. I am having a hard time making the lengths of the bars relative to one another and making the bars face different directions on matplotlib like the one shown above.
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85073749
has text: We can't solve the problem in your code if you don't show us the code.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49034457

http://stackoverflow.com/q/49061465
score: 0
has answer: http://stackoverflow.com/a/49061492
has body: I would like to return the string values of m &amp; t from my message function to use in cipher function to perform a while loop and once false print the message reverse. The error message I am receiving is "NameError: name 'm' is not defined", but 'm' has been defined in message which i am attempting to return for use in cipher along with 't'. def main(): message() cipher(m, t) def message(): m = input("Enter your message: ") t = '' return m, t def cipher(m, t): i = len(m) - 1 while i &gt;= 0: t = t + m[i] i -= 1 print(t) if __name__ == '__main__': main()
tagged with: return-value
has comment: http://stackoverflow.com/comment/85128063
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49061492
has title: function not returning string values
type: Question
tagged with: function
answer count: 1

http://stackoverflow.com/a/64939034
upvote count: 11
has body: OR df_train[(df_train["fold"]==1) | (df_train["fold"]==2)] AND df_train[(df_train["fold"]==1) & (df_train["fold"]==2)]
score: 11
has comment: http://stackoverflow.com/comment/116544394
downvote count: 0
answers question: http://stackoverflow.com/q/48978550
type: Answer

http://stackoverflow.com/comment/85065186
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49009871
has text: @khelwood well if you want to go further into this, I would welcome another answer :) I have not looked at all the possible use cases or dug into the actual C implementation myself

http://stackoverflow.com/comment/85137585
comment on: http://stackoverflow.com/q/49066293
type: Comment
type: QuestionComment
score: 9
has text: How did you create your dictionary? Did you put the same list into it multiple times?

http://stackoverflow.com/comment/85103367
comment on: http://stackoverflow.com/q/49049391
score: 0
type: Comment
type: QuestionComment
has text: could be how can I do that?

http://stackoverflow.com/q/49096512
answer count: 1
has comment: http://stackoverflow.com/comment/85199362
tagged with: ascii
tagged with: python-2.7
score: 0
has body: Problem sketch: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128) I'm trying to write a simple python program that can auto-complete the blank units with data appeared in the same column above. Since there're Chinese characters in the file, I've thought of the issue of ASCII, so I tried to change it into UTF-8. Codes shown below: #!/usr/bin/python # -*- coding:utf-8 -*- from xlrd import open_workbook from xlwt import Workbook from xlutils.copy import copy rb = open_workbook('data.xls', 'utf-8') wb = copy(rb) sh = wb.get_sheet(0) s = rb.sheet_by_index(0) cols = s.ncols rows = s.nrows temp = 0 for cx in range(cols): for rx in range(rows): if s.cell_value(rowx = rx, colx = cx).encode('utf-8') != "": temp = s.cell_value(rowx = rx, colx = cx).encode('utf-8') print(temp) #to verify else: sh.write(rx, cx, temp) wb.save('data.xls') However, the issue still happened. Result in terminal: ZishengdeMacBook-Pro:Downloads zisheng$ python form.py (printed result ignored, and it looked good) Traceback (most recent call last): File "form.py", line 41, in &lt;module&gt; wb.save('data.xls') File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/Workbook.py", line 710, in save doc.save(filename_or_stream, self.get_biff_data()) File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/Workbook.py", line 674, in get_biff_data shared_str_table = self.__sst_rec() File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/Workbook.py", line 636, in __sst_rec return self.__sst.get_biff_record() File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/BIFFRecords.py", line 77, in get_biff_record self._add_to_sst(s) File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/BIFFRecords.py", line 92, in _add_to_sst u_str = upack2(s, self.encoding) File "/Users/zisheng/anaconda/lib/python2.7/site-packages/xlwt/UnicodeUtils.py", line 50, in upack2 us = unicode(s, encoding) UnicodeDecodeError: 'ascii' codec can't decode byt…
tagged with: utf-8
has answer: http://stackoverflow.com/a/49097858
tagged with: python
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85200856
accepted answer: http://stackoverflow.com/a/49097858
type: Question
has title: Python 2: ASCII issue when writing in Excel files

http://stackoverflow.com/comment/85034291
type: QuestionComment
comment on: http://stackoverflow.com/q/49014214
has text: Hello. Do you know exactly what line cause an error?
score: 0
type: Comment

http://stackoverflow.com/q/49081369
favorite count: 0
tagged with: python-3.x
has title: How to combine variable length arguments with keyword arguments in python?
has body: def addv(a,b,*args): sum = a + b for x in args: sum += x return sum addv(b = 1,a = 2) # This is valid addv(args = (1,2,3,4,5,6,7,8),b = 9, a = 10) #This is giving me unexpected keyword argument. I learned that keyword arguments are essentially passed as tuples. So, in an attempt to combine both keyword and variable arguments, I did the above experiment. Is there any way to do such a kind of thing or all variable arguments must be passed to the end while calling a function.
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85168223
has answer: http://stackoverflow.com/a/49081384
score: 1
accepted answer: http://stackoverflow.com/a/49081384
has comment: http://stackoverflow.com/comment/85168209
type: Question
tagged with: function
upvote count: 1
answer count: 1
downvote count: 0
tagged with: keyword-argument

http://stackoverflow.com/comment/88766433
type: AnswerComment
score: 0
type: Comment
has text: Just try to make your code work with `dynamic_rnn`. Can I pm you via email?
comment on: http://stackoverflow.com/a/49786336

http://stackoverflow.com/a/48970978
has body: I think you should try this it works for me, run in CMD python -m pip install pillow --trusted-host='pypi.python.org'
accepted answer of: http://stackoverflow.com/q/48970914
has comment: http://stackoverflow.com/comment/84947264
has comment: http://stackoverflow.com/comment/84947281
has comment: http://stackoverflow.com/comment/84947298
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48970914
has comment: http://stackoverflow.com/comment/84947354
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84947503
has comment: http://stackoverflow.com/comment/84947421
has comment: http://stackoverflow.com/comment/84947275

http://stackoverflow.com/a/49001144
has body: Images with transparency have to be converted with convert_alpha instead of the convert method. You could also use convert and then set_colorkey, but as far as my experience goes, surfaces that are converted with convert_alpha are blitted a lot faster.
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49000860
answers question: http://stackoverflow.com/q/49000860
has comment: http://stackoverflow.com/comment/85084082
upvote count: 3

http://stackoverflow.com/comment/85187716
score: 0
has text: However, the answer is short: JDK is the complete toolkit of Java (all executables Java offers, like a compiler, the JVM itself, some anaylze tools, ...). The JVM is just the virtual machine, which is the program that can read Java byte code and actually executes it. So the JVM is the core of Java, it interprets Java and executes the statements. Be aware that StackOverflow expects you to do research before you ask questions. So a question like this would probably get down-voted due to lack of research since a quick google search would clarify the difference between both terms.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49090811

http://stackoverflow.com/comment/85111533
has text: Yes, exactly that's what it is @DemetriP
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49052934

http://stackoverflow.com/comment/85237912
score: 0
comment on: http://stackoverflow.com/q/49116215
type: Comment
type: QuestionComment
has text: You can pass a string to `parser.parse_args` in `argparse` instead of using the cmd line. Alternatively look at the `shlex` module.

http://stackoverflow.com/a/49037236
upvote count: 4
downvote count: 0
has body: I was able to solve the issue by removing the gnupg library: pip uninstall gnupg and installing the phyton-gnupg one pip install python-gnupg Docs: python-gnupg - A Python wrapper for GnuPG
type: Answer
score: 4
answers question: http://stackoverflow.com/q/48998930

http://stackoverflow.com/q/49044398
score: 3
upvote count: 3
type: Question
tagged with: loss-function
has title: Is there any difference between cross entropy loss and logistic loss?
has comment: http://stackoverflow.com/comment/85093744
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras
has body: I want to use a logistic loss cost function for my deep learning model to solve a binary classification problem. I am using keras to build the model. However, keras doesn't have any pre-defined logistic loss function. While reading about loss functions I came across confusing statements about cross entropy loss and logistic loss. In this wikipedia article, there is a separate section for logistic loss and cross entropy loss. However in this wikipedia article, its mentioned that: The logistic loss is sometimes called cross-entropy loss. Additionally, this sklearn page starts with: Log loss, aka logistic loss or cross-entropy loss. Any help would be appreciated.
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49044499

http://stackoverflow.com/q/48964454
upvote count: 2
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48964580
tagged with: python
tagged with: filereader
has title: Reading multiple files in python
score: 1
has comment: http://stackoverflow.com/comment/84934807
type: Question
has body: I have a dataset of more than 300k files which I need to read and append to dictionary. corpus_path = "data" article_paths = [os.path.join(corpus_path,p) for p in os.listdir(corpus_path)] doc = [] for path in article_paths: dp = pd.read_table(path, header=None, encoding='utf-8', quoting=3, error_bad_lines=False) doc.append(dp) Is there a faster way to do this, as the current method takes more than an hour.

http://stackoverflow.com/q/49113289
tagged with: number-theory
answer count: 2
linked to: http://stackoverflow.com/q/6800193
has comment: http://stackoverflow.com/comment/85232311
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85232064
tagged with: mathematical-lattices
tagged with: python
has title: Generating Pythagorean triples using Gaussian (complex) integers
has body: I have only just recently found out about a way of generating Pythagorean triples through this video explaining it, involving the use of Gaussian (complex) integers. I have so far managed to write a function returning a list of Pythagorean triples generated by every Gaussian integer where the imaginary part is less than the real part. def pyt(max_real): t = [] real = 2 imag = 1 while real &lt;= max_real: z = complex(real, imag)**2 t.append((z.real, z.imag, abs(z))) if imag + 1 == real: real += 1 imag = 1 else: imag += 1 return t The problem with this is that some triplets (such as {9, 12, 15}) are not generated through the initial step in the video that the function has been based on, and I'm unsure of how to generate those. &gt;&gt;&gt; for i in pyt(4): print(i) (3.0, 4.0, 5.0) (8.0, 6.0, 10.0) (5.0, 12.0, 13.0) (15.0, 8.0, 17.0) (12.0, 16.0, 20.0) (7.0, 24.0, 25.0) &gt;&gt;&gt; # missing: (9, 12, 15), possibly others How would I go about generating every possible triplet, somehow using the ones I already have or otherwise?
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85232365
has comment: http://stackoverflow.com/comment/85232259
score: 3
tagged with: math
tagged with: complex-numbers
has comment: http://stackoverflow.com/comment/85231987
has answer: http://stackoverflow.com/a/49114240
has answer: http://stackoverflow.com/a/76294521
type: Question

http://stackoverflow.com/q/48983314
linked to: http://stackoverflow.com/q/4015417
type: AnsweredQuestion
has body: What is difference between both class naming conventions, both resulting in the same output? class class_name: def func(): print('1st class') class class_name(): def func(): print('2nd class')
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84971645
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48983383
has answer: http://stackoverflow.com/a/48983585
tagged with: class
has answer: http://stackoverflow.com/a/48983383
possible better answer: http://stackoverflow.com/a/48983585
upvote count: 1
has comment: http://stackoverflow.com/comment/84971509
favorite count: 0
tagged with: python-3.x
has title: difference between different type of class naming
tagged with: python

http://stackoverflow.com/comment/85145672
has text: @thileepan - And `string`s are processes like `True`s - [link](https://stackoverflow.com/a/20420996/2901002)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49069644
type: Comment

http://stackoverflow.com/a/49057432
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49057171
has body: You are calling is_valid on the User object, but that's not a method you've defined on the User (or that exists already on AbstractUser). If you take a closer look at your tutorial, they're actually calling it on the UserForm. Forms have a built-in is_valid method used to make sure all the form data submitted is valid (what valid means can differ based on your use case... maybe you're making sure everything's filled in, or that something's a real email address, or that a date is more than six months in the future). Your code says: form1=User(request.POST or None) if form1.is_valid(): form1.save() It looks like you meant to define form1 as a form object (otherwise that's maybe the worst variable name ever). You probably have something called UserForm (or similar) in your forms.py. You'll want to import that, and instantiate it like: form1 = UserForm(request.POST, instance=request.user) https://docs.djangoproject.com/en/2.0/ref/forms/validation/ (side note: When you come back to your code in a year, will you remember what form1 was supposed to mean? Try to name your variable something that explains itself--user_form or something similar)
answers question: http://stackoverflow.com/q/49057171
upvote count: 5
score: 5
type: AcceptedAnswer

python-2.7
tags question: http://stackoverflow.com/q/49068223
tags question: http://stackoverflow.com/q/49073298
tags question: http://stackoverflow.com/q/49002427
tags question: http://stackoverflow.com/q/49080776
tags question: http://stackoverflow.com/q/49063730
tags question: http://stackoverflow.com/q/48990886
tags question: http://stackoverflow.com/q/49007929
tags question: http://stackoverflow.com/q/49026570
tags question: http://stackoverflow.com/q/49072656
tags question: http://stackoverflow.com/q/49105056
tags question: http://stackoverflow.com/q/48997840
tags question: http://stackoverflow.com/q/49059461
tags question: http://stackoverflow.com/q/49057888
tags question: http://stackoverflow.com/q/49071153
tags question: http://stackoverflow.com/q/49099520
tags question: http://stackoverflow.com/q/49083920
tags question: http://stackoverflow.com/q/49119039
tags question: http://stackoverflow.com/q/48980048
tags question: http://stackoverflow.com/q/49029473
tags question: http://stackoverflow.com/q/49101962
tags question: http://stackoverflow.com/q/49067258
tags question: http://stackoverflow.com/q/49110185
tags question: http://stackoverflow.com/q/48997695
tags question: http://stackoverflow.com/q/49031748
tags question: http://stackoverflow.com/q/49064611
tags question: http://stackoverflow.com/q/49098987
tags question: http://stackoverflow.com/q/49095860
tags question: http://stackoverflow.com/q/49046972
tags question: http://stackoverflow.com/q/48980187
tags question: http://stackoverflow.com/q/49106946
tags question: http://stackoverflow.com/q/49080555
tags question: http://stackoverflow.com/q/48990715
tags question: http://stackoverflow.com/q/49098726
tags question: http://stackoverflow.com/q/48969754
tags question: http://stackoverflow.com/q/48974176
tags question: http://stackoverflow.com/q/48991909
tags question: http://stackoverflow.com/q/49026183
tags question: http://stackoverflow.com/q/49039985
tags question: http://stackoverflow.com/q/48997207
tags question: http://stackoverflow.com/q/49112853
tags question: http://stackoverflow.com/q/49113676
tags question: http://stackoverflow.com/q/49023711
tags question: http://stackoverflow.com/q/49096654
tags question: http://stackoverflow.com/q/49019136
tags question: http://stackoverflow.com/q/49077132
tags question: http://stackoverflow.com/q/48973087
tags question: http://stackoverflow.com/q/48995891
tags question: http://stackoverflow.com/q/49107938
tags question: http://stackoverflow.com/q/49092363
tags question: http://stackoverflow.com/q/49044835
tags question: http://stackoverflow.com/q/49011058
tags question: http://stackoverflow.com/q/49085548
tags question: http://stackoverflow.com/q/49084733
tags question: http://stackoverflow.com/q/48968251
tags question: http://stackoverflow.com/q/49028418
tags question: http://stackoverflow.com/q/49107378
tags question: http://stackoverflow.com/q/49056702
tags question: http://stackoverflow.com/q/49014412
tags question: http://stackoverflow.com/q/49029853
tags question: http://stackoverflow.com/q/49005803
tags question: http://stackoverflow.com/q/49091089
tags question: http://stackoverflow.com/q/48976184
tags question: http://stackoverflow.com/q/49001370
tags question: http://stackoverflow.com/q/49083909
tags question: http://stackoverflow.com/q/49120765
tags question: http://stackoverflow.com/q/48967660
tags question: http://stackoverflow.com/q/49013846
tags question: http://stackoverflow.com/q/49079081
tags question: http://stackoverflow.com/q/48963751
tags question: http://stackoverflow.com/q/49035087
tags question: http://stackoverflow.com/q/49085244
tags question: http://stackoverflow.com/q/49043922
tags question: http://stackoverflow.com/q/49050788
tags question: http://stackoverflow.com/q/49019469
tags question: http://stackoverflow.com/q/49119668
tags question: http://stackoverflow.com/q/49007215
tags question: http://stackoverflow.com/q/49098778
tags question: http://stackoverflow.com/q/49115628
tags question: http://stackoverflow.com/q/49022752
tags question: http://stackoverflow.com/q/49056911

http://stackoverflow.com/a/49088000
has body: Try: def between(): print ("Please enter a number between 1 and 100.") number=0 try: number = int(input()) except: print ("ERROR! You have entered an invalid value. Please try again using numerical values only.") exit(1) if number &gt;= 1 and number &lt;= 100: print ("Thank you! You entered",number,"which is within the 1 and 100 range.") between() else: print ("OOPS! You entered",number,"Please enter a number between 1 and 100.") between() between() Note: why you use eval and input together? I don't think that's right, correct me if I'm wrong
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49087841
has comment: http://stackoverflow.com/comment/85181587

http://stackoverflow.com/q/49018135
has comment: http://stackoverflow.com/comment/85041515
linked to: http://stackoverflow.com/q/8548030
score: 0
has answer: http://stackoverflow.com/a/49018259
has comment: http://stackoverflow.com/comment/85057698
accepted answer: http://stackoverflow.com/a/49018281
possible better answer: http://stackoverflow.com/a/49018259
linked to: http://stackoverflow.com/q/17271319
tagged with: installation
tagged with: pip
tagged with: python
type: AnsweredQuestion
has body: I am coding on Python 2.7. I want a large list of words to have access to. Looking around, I have found that nltk has what I'm looking for. However, every time I try and install it I get a syntax error. I have tried doing the commands in the shell and in files. I have no true understanding of how pip, install, and download commands work. I am on a mac, which other threads have said could affect things. I have tried... sudo pip2 install nltk Which gives: SyntaxError: invalid syntax When importing, I get import nltk Traceback (most recent call last): File "&lt;pyshell#4&gt;", line 1, in &lt;module&gt; import nltk ModuleNotFoundError: No module named 'nltk' nltk.download Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; nltk.download NameError: name 'nltk' is not defined and a few other suggestions from other threads, but nothing works. Please help.
type: Question
has answer: http://stackoverflow.com/a/49018281
has comment: http://stackoverflow.com/comment/85041501
has comment: http://stackoverflow.com/comment/85041486
answer count: 2
has title: SyntaxError when pip install install NLTK
has comment: http://stackoverflow.com/comment/85063457
tagged with: nltk

http://stackoverflow.com/a/48997408
downvote count: 0
score: 1
has body: Is this what you need ? (df.id &gt; 40) &amp; (df.value.isin(['a', 'g'])) Out[2059]: 0 False 1 False 2 True 3 False 4 True dtype: bool
answers question: http://stackoverflow.com/q/48997373
upvote count: 1
type: Answer

http://stackoverflow.com/q/49054950
favorite count: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49055161
type: AnsweredQuestion
has body: Is there any way to create an object in a model using a ManyToManyField? Here are the models: class Booking(models.Model): tour_ref = models.CharField(max_length=30) customers = models.ManyToManyField(Customer) class Customer(models.Model): name = models.CharField(max_length=40) email = models.EmailField() The task is to create a new Booking object. But how do I do this using specific customers from the Customer table? (I would be identifying them by email). (Obviously more than one customer would be likely). Many thanks!
has comment: http://stackoverflow.com/comment/85114846
score: 1
upvote count: 1
type: Question
has title: Django / Python - Using ManyToMany field In Object Creation
tagged with: django-models
has answer: http://stackoverflow.com/a/49055161
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/6996176

http://stackoverflow.com/comment/85120024
score: 0
type: Comment
type: QuestionComment
has text: _Any_ is such a strong word.
comment on: http://stackoverflow.com/q/49037669

http://stackoverflow.com/q/49010335
upvote count: 3
has answer: http://stackoverflow.com/a/51721129
has title: Subtract values of columns from two different data frames in PySpark to find RMSE
type: Question
score: 3
tagged with: pyspark
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/49010493
answer count: 2
tagged with: apache-spark
has body: I am not able to figure it out. I am trying to calculate the RMSE between test and prediction data. test col1 col2 a 2 b 3 prediction col1 col2 a 4 b 5 I am trying to do this test(col2)-prediction(col2). That is 2-4 =-2 3-5 =-2 I tried test.select("col2").subtract(prediction.select("col2")) But I am not getting the required result. I am trying to obtain this result to find the RMSE. Is there a built in function in spark to find the RMSE? Thank you.
downvote count: 0
favorite count: 0
tagged with: python
tagged with: rdd
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49010493
possible better answer: http://stackoverflow.com/a/51721129

http://stackoverflow.com/a/49117204
downvote count: 1
has body: For this case it would probably be better to use applymap if you need to apply a custom function pdf[arb_cols] = pdf[arb_cols].applymap(lambda x : 99 if x == 2 else x)
answers question: http://stackoverflow.com/q/49116988
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84980203
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48987882
has text: "some2" has a list as value
type: Comment

http://stackoverflow.com/comment/85021325
score: 0
type: AnswerComment
type: Comment
has text: So it is! That makes perfect sense if I actually think about it. Will edit that out. ( I suppose technically `list(chain(*c.items()))` is shorter still, but not as readable to my mind)
comment on: http://stackoverflow.com/a/49007278

http://stackoverflow.com/comment/85246003
comment on: http://stackoverflow.com/q/49118967
type: Comment
type: QuestionComment
has text: You’re trying to train such a simple function. It should be possible to represent it with just a single weight. What are the initial values for your weights? It’s odd that they all end up approximately equal. I’d expect a lot of nodes to die leaving a single "x2" node.
score: 0

http://stackoverflow.com/comment/85130317
type: Comment
comment on: http://stackoverflow.com/a/49061211
score: 0
type: AnswerComment
has text: This is almost correct but it doesnt display the underscore '_' in the abc token instead of not printing that at all

http://stackoverflow.com/q/48998848
upvote count: 2
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49009352
tagged with: recurrent-neural-network
has title: Text input with Tensorflow
tagged with: numpy
downvote count: 0
answer count: 1
has body: I am playing with Tensorflow and trying to build a RNN language model. I am struggling with how to read raw text input file. Tensorflow guide mentioned a few approaches, including: tf.data.Dataset.from_tensor_slices() - which assumes my data is available in memory (np.array？) tf.data.TFRecordDataset (no idea how to use this) tf.data.TextLineDataset (what's the difference with 2? the API page are almost identical) Confused with 2 and 3, I can only try approach 1, but facing the following issues: what if my data is too big to fit in memory? TF requires a fix-length, padded format, how do I do it? - Do I: Decide on a fix-length value (e.g. 30), read each line into a list, truncate the list to 30 if it is longer then 30, fill '0's to to make each line at least 30 long, append the list to a numpy array/matrix ? I am sure these are such common problems that tensorflow much have provided built-in functions!
tagged with: tensorflow-datasets
favorite count: 0
accepted answer: http://stackoverflow.com/a/49009352
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/53624169
answers question: http://stackoverflow.com/q/49097715
has body: Go to PyCharm → Preferences → Python Interpreter. Select the Use Conda Package Manager symbol (green circle). After it refreshes, select the Install (^N) symbol. Search for the installed package
score: 0
type: Answer

http://stackoverflow.com/q/49079134
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85164728
tagged with: math
score: -1
has answer: http://stackoverflow.com/a/49079431
has answer: http://stackoverflow.com/a/49079366
tagged with: eulers-number
answer count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: input
tagged with: python
has title: I need help finding the natural log of user generated input
has body: how do I use python to find the natural log of a user's input? import math def log_e(power_of_e): math.log = power_of_e exponent = math.log return exponent my_number = float(input('Enter a number and I will give you it\'s natural logarithm:')) print (log_e(my_number))
upvote count: 0
has comment: http://stackoverflow.com/comment/85169488

http://stackoverflow.com/q/49120965
has title: Unable to set-up Pyspark
tagged with: apache-spark
has answer: http://stackoverflow.com/a/49121188
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have installed Pyspark and Findspark using conda environment and added their paths to environment variables. I execute following code: import findspark import pyspark findspark.find() I get the output as: 'C:/Users/myname/AppData/Local/Continuum/anaconda3/Scripts' Then I execute: findspark.init("C:/Users/myname/AppData/Local/Continuum/anaconda3/Scripts") The output I get is:
tagged with: installation
downvote count: 1
type: Question
upvote count: 0
tagged with: pyspark
score: -1

http://stackoverflow.com/comment/84969074
has text: `binascii.hexlify(b64decode(nonce))` or in Python3, `b64decode(nonce).hex()`.
comment on: http://stackoverflow.com/q/48981946
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49100088
upvote count: 4
has title: Test Application Keys for Twilio Authy Client
has body: I am using Python Client for Twilio Authy API (https://github.com/authy/authy-python). To create a new Connection Instance the following is used: from authy.api import AuthyApiClient authy_api = AuthyApiClient('#your_api_key') For testing purposes, are test Application Keys available that do not necessarily send the OTP to phone but gives the appropriate responses? Where or how do I get this test Application Key?
has comment: http://stackoverflow.com/comment/85312486
has comment: http://stackoverflow.com/comment/85250293
type: Question
downvote count: 0
score: 4
tagged with: verification
tagged with: rest
favorite count: 0
tagged with: twilio
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85224978
has comment: http://stackoverflow.com/comment/85213976
tagged with: django
tagged with: python

http://stackoverflow.com/q/49025038
has body: In python-docx there is a Paragraph method for inserting a paragraph before another one: p2 = p.insert_paragraph_before("hello", style='Normal') Supposing the case we already have a saved docx document with a table in it, and we want to insert a paragraph before the table, e.g. an explanation. It is fairly easy to find tables with: for table in document.tables: ... Unfortunately, a Table object does not have an insert_paragraph_before method. How could one implement that?
has answer: http://stackoverflow.com/a/62661441
type: Question
has title: python-docx: Inserting a paragraph before a table
score: 3
answer count: 2
downvote count: 0
tagged with: python-docx
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49048153
upvote count: 3

http://stackoverflow.com/comment/85000198
comment on: http://stackoverflow.com/a/48997269
has text: Another thing to keep in mind, the reference to `data` is passed to this function. When you alter `data` in-place like I'm doing in my answer, you don't have to return `data` back, because I altered the object passed to it
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48974662
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84973741
has comment: http://stackoverflow.com/comment/84973593
has body: I'm uploading a file and additionally some data like file's id and file's title to the server. I have the view below to handle the request and I want to save the file to a dynamic path like upload/user_id/thefile.txt. With code the below the file will be saved in and upload folder directly and also my product_video table will create a new record with the related id and the title. Now I don't have any idea how can I save the file in a dynamically generated directory like: upload/user_id/thefile.txt and how to save the produced path to the database table column video_path? view class: class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): if request.method == 'POST' and request.FILES['file']: myfile = request.FILES['file'] serilizer = VideoSerializer(data=request.data) if serilizer.is_valid(): serilizer.save() fs = FileSystemStorage() fs.save(myfile.name, myfile) return Response("ok") return Response("bad") and serializer clas: class VideoSerializer(ModelSerializer): class Meta: model = Product_Video fields = [ 'p_id', 'title', 'video_length', 'is_free', ] and related model class: def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Product_Video(models.Model): p_id = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_video') title = models.CharField(max_length=120, null=True,blank=True) video_path = models.FileField(null=True, upload_to=user_directory_path,storage=FileSystemStorage) video_length = models.CharField(max_length=20, null=True, blank=True) is_free = models.BooleanField(default=False)
has answer: http://stackoverflow.com/a/48984975
score: 0
answer count: 1
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/48984975
has comment: http://stackoverflow.com/comment/84973313
has title: save upload file to dynamic directory and get the path for store in db
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85109982
type: QuestionComment
type: Comment
score: 1
has text: @Kyrylo No, they are not. Only `workspace.xml` is specific for each user.
comment on: http://stackoverflow.com/q/49052653

http://stackoverflow.com/a/49068420
has comment: http://stackoverflow.com/comment/103278595
has comment: http://stackoverflow.com/comment/85167959
has body: To find all loggers and their corresponding names execute: logging.Logger.manager.loggerDict.keys() Try to set it explicitly by getting the noisy logger instance: import logging noisyLogger = logging.getLogger("autobahn") # adjust logger name # noisyLogger.getEffectiveLevel() # indicates the current effective level noisyLogger.setLevel(logging.INFO)
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49063649
downvote count: 0

http://stackoverflow.com/comment/85204308
type: AnswerComment
type: Comment
has text: In the example above, `my_list` has a type of `list`. It is a [built-in data structure in Python](https://docs.python.org/3/library/stdtypes.html#list) and because of that you shouldn't ever use `list` as a variable name. You can create a list in a bunch of ways, `list('123')`, `list(range(5))`, `[x**2 for x in range(5)]`, `[1, 2, 3]`, etc. For more information, you can try looking at the official [Python tutorial](https://docs.python.org/3/tutorial/introduction.html#lists).
comment on: http://stackoverflow.com/a/49099216
score: 0

http://stackoverflow.com/q/49108331
has title: Django objects get deletes after a while automatically on heroku server
has comment: http://stackoverflow.com/comment/85221468
downvote count: 0
has comment: http://stackoverflow.com/comment/85222657
score: 1
favorite count: 0
type: Question
answer count: 2
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85221652
upvote count: 1
has answer: http://stackoverflow.com/a/64719650
has answer: http://stackoverflow.com/a/74002274
tagged with: heroku
has comment: http://stackoverflow.com/comment/85222552
has comment: http://stackoverflow.com/comment/85222111
has comment: http://stackoverflow.com/comment/85223045
has comment: http://stackoverflow.com/comment/85223223
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85223015
has body: Does anyone know why my django saved objects getting deleted automatically after a while ' this happened like most of the times that i check my website and see's one of my files get's delete automatically from the server also the deleted objects are not the last saved objects but 3rd last or sometime's maybe 2nd last objects... and i don't think it's a problem with my written code because this doesn't happens on local development server where usually i keep running the development server for more than 4-5 hours sometime's whole day.. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
linked to: http://stackoverflow.com/q/16868451

http://stackoverflow.com/q/49035495
tagged with: logging
has comment: http://stackoverflow.com/comment/85099102
tagged with: qt
has comment: http://stackoverflow.com/comment/85280669
has comment: http://stackoverflow.com/comment/85379372
has comment: http://stackoverflow.com/comment/85120210
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: multithreading
has comment: http://stackoverflow.com/comment/85093559
has comment: http://stackoverflow.com/comment/85078315
type: Question
has body: Setup I am working on an application using Qt and Python with threads and experiance occational core dumps. I stripped down my code to a minimum working example and would like to know, what might be causing the core dumps. My application has the following goals: I need to handle a compuational expensive task in a separat thread. I am using the python threading module for the thread creation. The logging that occurs in that thread should be visualized in the GUI The thread should send data to the GUI that should also be visualized My setup is as follows: Logging I created a new logging handler that is attached to the logger and sends the log message via a queue to the main thread: class TextEditHandler(logging.Handler): def __init__(self, queue): super(TextEditHandler, self).__init__(logging.INFO) self.queue = queue def emit(self, record): self.queue.put(self.format(record)) GUI I am using a QDialog for the GUI that is created from the main window of my application. The QDialog has the following tasks: It holds the QTextEdit which displays the log messages and data It creates the log queue and attaches the TextEditHandler to the logger and passes the log queue to the TextEditHandler It creates a QTimer that triggers in a fixed intervall and checks the log queue as well as the thread queue for new log messages/data. It creates the thread as well as a thread queue in which the data is sent from the thread. In code terms it looks like this: class Dialog(QtGui.QDialog): def __init__(self): super(Dialog, self).__init__() self.logWidget = QtGui.QTextEdit() self.logWidget.setReadOnly(True) layout = QtGui.QHBoxLayout() layout.addWidget(self.logWidget) self.setLayout(layout) self.loggingQueue = Queue.Queue() self.loggingHandler = TextEditHandler(self.loggingQueue) logging.getLogger().addHandler(self.loggingHandler) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.TimerCallback) self.timer.start(1) self.threadQueue = Queue.Queue() self.thread = threading.Thread(tar…
tagged with: pyside
has comment: http://stackoverflow.com/comment/85255756
linked to: http://stackoverflow.com/q/21071448
has comment: http://stackoverflow.com/comment/85097202
upvote count: 1
has comment: http://stackoverflow.com/comment/85092622
favorite count: 0
has comment: http://stackoverflow.com/comment/85090498
has title: Where does the core dump in python threaded Qt application come from?
tagged with: python
has comment: http://stackoverflow.com/comment/85092592

http://stackoverflow.com/comment/85100310
has text: The URL is in the messages, try manual download
comment on: http://stackoverflow.com/q/49047990
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49034651
tagged with: gevent
type: Question
has title: How to lock running some block of code within specific thread in Gevent?
answer count: 1
downvote count: 0
has body: Simplified code looks like import gevent from requests import get from gevent.monkey import patch_all; patch_all() def f1(): print("Thread 1 start") x = get('https://www.google.com') print("Thread 1 end") def f2(): print("Thread 2") gevent.joinall([ gevent.spawn(f1), gevent.spawn(f2) ]) And the output is expected: Thread 1 start Thread 2 Thread 1 end I need to lock calling of the get request. So, I need to get the following output: Thread 1 start Thread 1 end Thread 2 How achieve such get request locking?
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/56320457

http://stackoverflow.com/a/49066597
accepted answer of: http://stackoverflow.com/q/49066476
has body: You are filtering out the __init__ method: attrs = ((name, value) for name, value in class_attr.items() if not name.startswith('__')) attrs are all the attributes that do not start with __. You then uppercase those attrs and use those for the class you create, so __init__ is never used for the new class. Because the resulting Bar class has no __init__ method, object.__init__ is used, and that method doesn't take parameters: &gt;&gt;&gt; sorted(vars(Base)) ['BAR', '__dict__', '__doc__', '__module__', '__weakref__'] &gt;&gt;&gt; Base.__init__ &lt;slot wrapper '__init__' of 'object' objects&gt; Include all attributes, do not filter, but only uppercase those without __: class UpperAttrMetaClass(type): # to uppercase all attrs def __new__(mcs, class_name, class_parents, class_attr): attrs = {name if name.startswith('__') else name.upper(): value for name, value in class_attr.items()} return super().__new__(mcs, class_name, class_parents, attrs) I used a dictionary comprehension here; note the name if name.startswith('__') else name.upper() conditional expression, which produces an uppercase attribute name when the name does not start with __. I also used the 0-argument form of super(), this is Python 3 after all. Now the metaclass works correctly and Base.__init__ exists: &gt;&gt;&gt; sorted(vars(Base)) ['BAR', '__dict__', '__doc__', '__init__', '__module__', '__weakref__'] &gt;&gt;&gt; t = Base(1) &gt;&gt;&gt; t.BAR 12 &gt;&gt;&gt; t.params 1
upvote count: 1
answers question: http://stackoverflow.com/q/49066476
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85138462

http://stackoverflow.com/a/48965565
has body: This line ap.add_argument("--image", "-i", required = True, help = "Path to input image") says that your program is expecting the user to put something like --image ~/Home/Desktop/face-detector/myimage.png on the command line after the name of the program when the program is run. You're clearly not doing that, which is why you are getting an error message. While you are testing you can put a default value in to save typing the --image command line parameter every time: ap.add_argument("--image", "-i", required = True, help = "Path to input image", default="~/Home/Desktop/face-detector/myimage.png") but that is clearly not sensible except for testing.
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48964757
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48964757

http://stackoverflow.com/a/49024578
answers question: http://stackoverflow.com/q/49022546
has body: Only thing that comes to mind is something like this: import asyncio _running = list() # set would be better if you have hashable values def create_unique_task(coro_func, *args, **kwargs): loop = asyncio.get_event_loop() uid = (args, kwargs) if uid not in _running: task = loop.create_task(foo(*args, **kwargs)) _running.append(uid) task.add_done_callback(lambda _: _running.remove(uid)) else: print('skipped') return return task async def foo(a, b): print("{} {}".format(a, b)) await asyncio.sleep(0.5) async def main(): create_unique_task(foo, "one", "two") create_unique_task(foo, "three", "four") await asyncio.sleep(0.2) create_unique_task(foo, "one", "two") create_unique_task(foo, "three", "four") await asyncio.sleep(0.4) create_unique_task(foo, "one", "two") create_unique_task(foo, "three", "four") await asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() Output: one two three four skipped skipped one two three four
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/85173967
score: 0
type: Comment
type: AnswerComment
has text: They are not the same. The activate command also (possibly) sets several environment variables, and runs any post-activation hook scripts that packages may have installed to change the environment on environment activation. Only for very simple cases are they the same.
comment on: http://stackoverflow.com/a/49083195

http://stackoverflow.com/q/49120374
type: Question
tagged with: sockets
upvote count: 1
tagged with: python
answer count: 1
tagged with: unix-socket
accepted answer: http://stackoverflow.com/a/49120591
downvote count: 0
type: AnsweredQuestion
score: 1
favorite count: 0
has title: Python unix socket server recieves same data from client multiple times
tagged with: ruby
has answer: http://stackoverflow.com/a/49120591
has body: I am trying to communicate between ruby and python through unix sockets, and i need multithreaded python server to respond to many ruby clients. All work fine except 1 thing, that i send message from client only once, but the server recieves it 2 times somehow. What maybe the problem? Here's my python server code: import socket import os import threading import time import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create a file handler handler = logging.FileHandler('python_server.log') handler.setLevel(logging.DEBUG) # create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # add the handlers to the logger logger.addHandler(handler) class ThreadedServer(object): def __init__(self, socket_path): if os.path.exists(socket_path): os.remove(socket_path) logger.info("Opening socket...") self.server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind(socket_path) def listen(self): size = 1024 logger.info("Listening...") try: while True: datagram, address = self.server.recvfrom(1024) threading.Thread(target = self.listenToClient,args = (self.server, datagram, address, logger)).start() finally: logger.info("Shutting down...") self.server.close() os.remove("/tmp/python_socket_server") logger.info("Done") def listenToClient(self, server, datagram, address, logger_obj): while True: try: if datagram: logger_obj.info('Recieved message from client %s', address) time.sleep(5) server.sendto(bytes("I hear you buddy", 'UTF-8'), address) logger_obj.info('Responded to client %s', address) else: raise ValueError('Client disconnected') except: return False if __name__ == "__main__": socket_path = "/tmp/python_socket_server" ThreadedServer(socket_path).listen() My ruby client: require "socket" SERVER_SOCKET = "/tmp/python_socket_server" threads = [] 5.times do threads &lt;&lt; Thread.new d…

http://stackoverflow.com/q/49079464
accepted answer: http://stackoverflow.com/a/49079829
has comment: http://stackoverflow.com/comment/85165074
has comment: http://stackoverflow.com/comment/85165282
tagged with: http://stackoverflow.com/tag/csv
has body: I have three lines that I need to save as header of my csv files. They should look like this: title = "dataset test" variables = "X", "Y", "Z", "V" zone t = "Data Field", i = 134, j = 293, k = 5, f=point I am using the following code to create the pandas dataframe: info = pd.DataFrame(['title = "dataset test"', 'variables = "X", "Y", "Z", "V"', 'zone t = "Data Field", i = 134, j = 293, k = 5, f=point']) And using the following code to write the csv file: with open(fpath, 'w') as myfile: info.to_csv(myfile, header=None, index=False) However the output in the csv file is as: "title = ""dataset test""" "variables = ""X"", ""Y"", ""Z"", ""V""" "zone t = ""Data Field"", i = 134, j = 293, k = 5, f=point" Below this header there are three columns of number which will be add afterward; the final output should be like this: title = "dataset test" variables = "X", "Y", "Z", "V" zone t = "Data Field", i = 134, j = 293, k = 5, f=point 6.1961335E+06 2.3218804E+06 1.3564390E+03 6.1961547E+06 2.3218672E+06 1.3473630E+03 6.1961759E+06 2.3218540E+06 1.3382290E+03 6.1961972E+06 2.3218408E+06 1.3322720E+03 which I do it using df.to_csv(myfile, header=None, index=False, sep='\t',float_format='%.7E')
tagged with: python
has comment: http://stackoverflow.com/comment/85165227
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85165125
type: Question
has answer: http://stackoverflow.com/a/49079829
tagged with: dataframe
has comment: http://stackoverflow.com/comment/85164961
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85165307
answer count: 1
has title: Handling mixed string with double quotations and numbers to save in csv

http://stackoverflow.com/q/49039294
has title: Simple PySpark BigDL test: Optimizer fails
has body: Running BigDL example at: https://bigdl-project.github.io/0.4.0/#ProgrammingGuide/optimization/ in PySpark local node: from bigdl.nn.layer import Linear from bigdl.util.common import * from bigdl.nn.criterion import MSECriterion from bigdl.optim.optimizer import Optimizer, MaxIteration import numpy as np sc = SparkContext(appName="simple",conf=create_spark_conf()) init_engine() model = Linear(2, 1) samples = [ Sample.from_ndarray(np.array([5, 5]), np.array([2.0])), Sample.from_ndarray(np.array([-5, -5]), np.array([-2.0])), Sample.from_ndarray(np.array([-2, 5]), np.array([1.3])), Sample.from_ndarray(np.array([-5, 2]), np.array([0.1])), Sample.from_ndarray(np.array([5, -2]), np.array([-0.1])), Sample.from_ndarray(np.array([2, -5]), np.array([-1.3])) ] train_data = sc.parallelize(samples, 1) optimizer = Optimizer(model, train_data, MSECriterion(), MaxIteration(100), 4) optimizer.optimize() model.get_weights()[0] Results in the following exception. Other then BigDL tests work in PySpark. Environment: openjdk version "1.8.0_141, Python 3.5.3 (default, Jan 19 2017, 14:11:04) [GCC 6.3.0 20170118] on linux Any ideas? Is BigDL a live project, actively maintained? Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). 2018-02-28 22:40:20 WARN NativeCodeLoader:62 - Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 2018-02-28 22:40:20 WARN Utils:66 - Your hostname, dk resolves to a loopback address: 127.0.1.1; using 10.0.2.15 instead (on interface enp0s3) 2018-02-28 22:40:20 WARN Utils:66 - Set SPARK_LOCAL_IP if you need to bind to another address 2018-02-28 22:40:24 WARN SparkContext:66 - Using an existing SparkContext; some configuration may not take effect. cls.getname: com.intel.analytics.bigdl.python.api.Sample BigDLBasePickler registering: bigdl.util.common Sample cls.getname: com.intel.analytics.bigdl.python.api.EvaluatedResult BigDLBasePickler r…
tagged with: bigdl
type: Question
has answer: http://stackoverflow.com/a/61369678
tagged with: pyspark
has answer: http://stackoverflow.com/a/49052755
score: 0
answer count: 2
tagged with: apache-spark
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/74959896
answers question: http://stackoverflow.com/q/48977649
has body: I write a special conversion because sometimes in Excel, it is possible these percentages are melted with true strings or numbers in the same columns, and sometimes with or without decimal. Examples : "12%", "12 %", "Near 20%", "15.5", "15,5%", "11", "14.05%", "14.05", "0%"; "100%", "no result", "100" And I want keep the percentage symbol from true Excel percentage values, keeping decimals, without change the other values: import re df[field] = (df[field].apply(lambda x: str(round(float(x) * 100, 2)).rstrip('0').rstrip('.') + ' %' if re.search(r'^0\.\d+$|^0$|^1$',x) else x)) It works, but remains one problem: if a cell contains a true number between 0 and 1, so it becomes a percentage: "0.3" becomes "30%" But this is a special case, when the Excel file is wrong builded, revealing a true error. So I just add special alerts to manage this special cases.
score: 0
type: Answer

http://stackoverflow.com/q/49011306
has body: I want to use Pre-trained models such as Xception, VGG16, ResNet50, etc for my Deep Learning image recognition project to quick train the model on the training set with high accuracy. I am having trouble to find an exact code to implement my model. Firstly, as per the requirement of the VGG16 model, I modified the input shape of training data from (256,256,3) to (224,224,3). I have used keras programming environment. My model codes are as follows train_x = np.expand_dims(train_X, axis=2) train_y = np.expand_dims(train_Y, axis=2) print(train_X.shape) # output - (670, 224, 224, 3) print(train_Y.shape) # output - (670, 224, 224, 1) print(train_x.shape) # output - (670, 224, 1, 224, 3) print(train_y.shape) # output - (670, 224, 1, 224, 1) def vgg16_(IMG_WIDTH=224,IMG_HEIGHT=224,IMG_CHANNELS=3): inputs = Input(shape=(len(train_x[0]), 1)) x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(inputs) x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x) # Block 2 x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x) x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x) # Block 3 x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x) x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x) x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x) # Block 4 x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x) x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x) x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x) # Block 5 x = Conv2D(512, (3, 3), ac…
answer count: 2
tagged with: machine-learning
tagged with: python
has title: Developing Deep Learning image recognition system using Pre-trained models
has answer: http://stackoverflow.com/a/49011626
score: 0
has answer: http://stackoverflow.com/a/49011474
tagged with: tensorflow
type: UnansweredQuestion
tagged with: keras
type: Question
tagged with: deep-learning

http://stackoverflow.com/comment/85209385
type: QuestionComment
comment on: http://stackoverflow.com/q/49102057
has text: @ScottBoston Thanks for your comment. Please see my edit.
score: 0
type: Comment

http://stackoverflow.com/comment/85020586
comment on: http://stackoverflow.com/q/48978698
score: 0
type: Comment
type: QuestionComment
has text: I have included the data as you indicated.

http://stackoverflow.com/comment/85188447
comment on: http://stackoverflow.com/a/49086365
score: 0
type: AnswerComment
type: Comment
has text: Okay, I was originally using your code to try and give you a reason why the return error was happening. The current errors you are getting are a result of that. The error_reply, error_perm, and error_temp exceptions don't exist, so I just took them out. I edited my code to make a better example.

http://stackoverflow.com/q/49042335
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49042942
type: Question
possible better answer: http://stackoverflow.com/a/49042443
answer count: 2
has answer: http://stackoverflow.com/a/49042443
has title: User Input For List of Floats Not Repeating
accepted answer: http://stackoverflow.com/a/49042942
has body: So I'm writing some code for my class and have to have a list of floats that are input by a user and print them out with normal iteration and reverse iteration, and I have basically all of it done. But when it should ask multiple times for the user input, it only asks one time then prints everything out and finishes without asking multiple times. Any help would be appreciated as to why it isnt asking multiple times for input even though I have a for loop? Is there an easier way to get a list of floats from user input that I don't know about? Thanks emptyList = [] userInput = high = low = total = float(input("Input a float &gt; ")) emptyList.append(userInput) for y in range(len(emptyList)-1): userInput = float(input("Input a float &gt; ")) emptyList.append(userInput) total += emptyList if userInput &gt; high: high = userInput if userInput &lt; low: low = userInput avg = total / len(emptyList) above_avg = below_avg = 0 for y in range(len(emptyList)): if emptyList[y] &gt; avg: above_avg += 1 if emptyList[y] &lt; avg: below_avg += 1

http://stackoverflow.com/comment/85031521
type: QuestionComment
type: Comment
has text: @KuldeepYadav The static block is unavailable in selenium
score: 0
comment on: http://stackoverflow.com/q/49005382

http://stackoverflow.com/comment/85072835
has text: Thank you very much, both for your code and time.But I thought we may have different understanding of the c# code.Which is I think (the original executable binary) may use the 'm_owner' property (which is in a instance of ComponentOfCar) to find which car installed it.
comment on: http://stackoverflow.com/a/49031084
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84964272
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48979608
has text: sorry but i edited what i asked, i want to have the whole column A and not only foo so in the case the one with index 5 should also be included but it should assume that i don't know what the column has i just want it all.

http://stackoverflow.com/a/49059552
type: AcceptedAnswer
has body: If I'm understanding what you're asking, you're looking for something along the lines of Chai JS. Fortunately, someone has written a python library that approximates it, also called Chai. Your testcase would look something like this: FormatFilesCheck(files): expect(formatter.status).equals(installed) for prep in prework: do prep expect(prep).equals(what_prep_should_look_like) for file in files: format file expect(file).equals(what_file_should_look_like) clean up work # your expect/assert statements to make sure everything was cleaned up
type: Answer
accepted answer of: http://stackoverflow.com/q/49058338
answers question: http://stackoverflow.com/q/49058338
has comment: http://stackoverflow.com/comment/85125232
score: 0

http://stackoverflow.com/comment/85196051
comment on: http://stackoverflow.com/a/49085825
score: 0
type: AnswerComment
has text: If I want to the same for 2 different string values? like for `'<Media omitted>'` and `thisstringtoo` ? I tried with an or operator, but it didn't work.
type: Comment

http://stackoverflow.com/q/48986956
tagged with: axis
answer count: 1
has comment: http://stackoverflow.com/comment/85000950
favorite count: 0
has title: Correctly setting the axes limits in 3d plots
type: UnansweredQuestion
tagged with: python
score: 11
duplicate of: http://stackoverflow.com/q/16488182
has body: I'm having an issue with setting limits for my 3d plots in matplotlib; I'm finding that no matter how I set my limits for the x,y, and z axes, the plotting routine for 3dplots adds an extra buffer. from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt fig = plt.figure() ax = fig.add_subplot(111,projection='3d') ax.axes.set_xlim3d(left=0, right=10) ax.axes.set_ylim3d(bottom=0, top=10) ax.axes.set_zlim3d(bottom=0, top=10) plt.show() This produces the following plot: As you can see, the limits are supposed to be at x, y, z = {0, 10} however the 3D plotting always adds a little bit of a buffer to each edge. Does anyone know a way to turn this effect off? I've also used plt.xlims(); and ax.axes.set_xlims() but they produce the same effect.
tagged with: mplot3d
downvote count: 0
tagged with: matplotlib
linked to: http://stackoverflow.com/q/8920436
has answer: http://stackoverflow.com/a/48992758
type: Question
tagged with: matplotlib-3d
linked to: http://stackoverflow.com/q/16488182
upvote count: 11

http://stackoverflow.com/q/49101541
answer count: 1
tagged with: python
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: metaclass
has comment: http://stackoverflow.com/comment/85209462
has answer: http://stackoverflow.com/a/49102152
has comment: http://stackoverflow.com/comment/85209447
upvote count: 1
type: AnsweredQuestion
has title: Python3 using Metaclass to create classes defined in a JSON file
tagged with: http://stackoverflow.com/tag/json
tagged with: metaprogramming
type: Question
accepted answer: http://stackoverflow.com/a/49102152
has body: I´m currently creating a program which will be able to create classes at runtime. What I want is to load a json file into the script and from there create classes and inherited classes. In this file the class names will come as strings, this is why I need a solution that takes a string "A" and converts it into class A(metaclass=Metaclass) .I have learned a bit of metaclasses and understand some of it, however, I failed to create classes due to the fact that I´m not able to declare the name of the class. I came to a clumsy solution by using globals(). However, I was wondering if there is a more pythonic solution. class MetaFoo(type): def __new__(cls,name,bases,attr): print(f"{name} is invoking {cls.__name__}") return super().__new__(cls,name,bases,attr) def creator(name,bases,attr): globals()[name] = type(name,bases,attr) class Foo(metaclass=MetaFoo): pass class SubFoo1(Foo): pass class SubFoo2(Foo): pass class InheritFoo(SubFoo1,SubFoo2): pass print("-"*30) MetaFoo.creator("Z",(Foo,),{}) The output would be: Foo is invoking MetaFoo SubFoo1 is invoking MetaFoo SubFoo2 is invoking MetaFoo InheritFoo is invoking MetaFoo ------------------------------ Z is invoking MetaFoo Now I can create subclasses of Foo with creator(), however, I understand I'm having the wrong approach and my code is not able to produce directly subclasses of MetaFoo. So here are my three questions. How can I create classes from Metaclass using a string loaded externally? Not using metaclass type() like I did because if I were to use type() to create classes there would be no point to create a custom metaclass. I need to use metaclass not only because it lets you create new classes dinamically, but becuase it offers many functionalities like that I need in my program. I´m going to be dealing with big data, probably some millions of SQLite3 lines. Each line corresponds to a purchase and each class to a category, subcategory, etc. Performance wise, ¿Is having million of active objects, in this case, …
linked to: http://stackoverflow.com/q/12101958
downvote count: 0

http://stackoverflow.com/a/49121453
accepted answer of: http://stackoverflow.com/q/49118967
score: 1
upvote count: 1
has body: Moved answer from OP's question Turns out I never dealt with my training data properly. The input vector: [[0.0], [1.0], [2.0], [3.0]] was normalised, I divided this vector by the max value in the input which was 3, and thus I got [[0.0], [0.3333], [0.6666], [1.0]] And for the input Y training vector I had [[0.0], [2.0], [4.0], [6.0]] and I foolishly decided to do the same with this vector,but with the max of Y 6: [[0.0], [0.333], [0.666], [1.0]] So basically I was saying "hey network, mimic my input". This was my first error. The second error came as a result of more misunderstanding of the scaling. Although 1 was 0.333, and 0.333*2 = 0.666, which I then multiplied by the max of y (6) 6*0.666 = 2, if I try this again with a different set of data say: [[2.0], [3.0], [4.0], [5.0]] 2 would be 2/5 = 0.4 and 0.4*2 = 0.8, which times 5 would be 2, however in the real world we would have no way of knowing that 5 was the max output of the dataset, and thus I thought maybe it would have been the max of the Y training, which was 6 so instead of 2/5 = 0.4, 0.4*2 = 0.8 * 5, I done 2/5 = 0.4, 0.4*2 = 0.8 * 6 = 4.8. So then I got some strange behaviours of the biases and weights as a result. So after essentially getting rid of the normalisation, I was free to tweak the hyperparameters and now as an output for the base training data: input: X: [[0.] [1.] [2.] [3.]] I get this output: shape: (4, 1) [[0.30926124] [2.1030826 ] [3.89690395] [5.6907253 ]] and for the extra testing data (not trained on): shape: (4, 1) [[2.] [3.] [4.] [5.]] I get this output: shape: (4, 1) [[3.89690395] [5.6907253 ] [7.48454666] [9.27836801]] So now I'm happy. I also changed my activation to a leaky relu as it should fit a linear equation better (I think.). I'm sure with more testing data and more tweaking of the hyperparameters it would be a perfect fit. Thanks for the help everyone. Trying to explain my problem really put things into perspective.
answers question: http://stackoverflow.com/q/49118967
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/49073803
type: UnansweredQuestion
tagged with: python
tagged with: excel
has body: So I have two workbooks: One workbook is called "merged.xlsx" and this has data that is the result of a Python script. The other workbook is Action_Log.xlsm and I run the macro in order to get the data from merged.xlsx into Action_Log.xlsm. The very first thing my macro needs to do is run the Python script in order to update the merged.xlsx file: 'run python script to update merged workbook ret_value = Shell("C:\Python34\python-3.4.4.amd64\python.exe " &amp; "G:\Data\Shared\Action Logs\ActionLogAppend4py.py", vbNormalFocus) However, when I run the macro my merged file doesn't update (which of course means that the Python script didn't run even though it seems like it did because the rest of the macro continues and runs and hence no error on this line). When I run the Python script from Spyder my merged file updates just fine. So I don't know what the issue could be? Any help will be appreciated.
type: Question
has answer: http://stackoverflow.com/a/49073963
linked to: http://stackoverflow.com/q/8902022
has title: When I run Python script from VBA it doesn't work but when I run it from Spyder it does work, how do I fix this?
score: 0
answer count: 1
tagged with: vba

http://stackoverflow.com/q/49033116
score: 0
has comment: http://stackoverflow.com/comment/85071677
has comment: http://stackoverflow.com/comment/85071575
tagged with: parent
answer count: 1
has comment: http://stackoverflow.com/comment/85071428
has title: Class variable vs reference to parent in python
tagged with: reference
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85071784
has answer: http://stackoverflow.com/a/49033782
has comment: http://stackoverflow.com/comment/85070966
has body: I have a style question. Is it a bad idea to use a reference of a "manager object" to manage shared variables between objects? class Profile_Line: def __init__(self, parent, line): self.parent = parent self.line = line def get_results(self): image = self.parent.image # Is this a good idea? profile_line = self.get_profile_line(image, self.line) return profile_line def get_profile_line(self,img,line): return [1,2,3,4] #not real function class Profile_Line_Manager(): def __init__(self, image): self.image = image self.p_lines = [] # a list of Profile Line objects def add_profile_line(self, line): self.p_lines.append(Profile_Line(self, line)) def get_results(self): for pl in self.p_lines: print(pl.get_results()) So there is a class Profile Line, which calculates some values with its own parameters as well with the image, which it gets through the manager. The image is the same for all profile lines, which belong to the same manager. So a class variable cant be used, since all profile_line objects would have the same image, even if they don't belong together. Is it a good idea to pass the parent object to the profile line objects, which belong to that manager? It feels kind of weird. Or is there a better way of doing this, e.g. integrating both classes into one.
has comment: http://stackoverflow.com/comment/85071310
type: Question
has comment: http://stackoverflow.com/comment/85071369
tagged with: variables
tagged with: class

http://stackoverflow.com/a/49074357
downvote count: 0
has comment: http://stackoverflow.com/comment/85155010
answers question: http://stackoverflow.com/q/49074117
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85154801
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49074117
has body: Checking the next element against the length of the list doesn't help; you need to check the next index ... ... and do this before you access the elements. You need to to keep it from going out of bounds. A list of length k has indices 0:(k-1), but your test allows i+1 to run to the value of k, which causes your access to be out of bounds. New check: note the change from &lt;= to &lt;, and reversing the order. if i + 1 &lt; len(n) and n[i] == n[i+1]: "Short-circuiting" ensures that if the first condition is false, the second will no be evaluated. You can do this more easily with a for loop, which helps keep your idex in bounds: if len(n) &gt;= 2: for i in range(len(n)-1): if n[i] == n[i + 1]: return True # Exit early if you find a pair return False

http://stackoverflow.com/q/49055790
has comment: http://stackoverflow.com/comment/85133932
has body: I have googled for a long time and I could'nt find a solution to my problem. I am trying to create a window in which you can display multiple instances of another widget, just like you can see in the picture. The widgets are supposed to be different uploads you can manage with them. This is the code I wrote and self.UploadArea.addWidget(uic.loadUi('gui_files/module.ui')) is supposed to open the Widget inside a QWidget called "UploadArea" it probably is coded like garbage and does not make any sense but it would be nice if you could tell me an elegant answer to my problem. class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args): super(MainWindow, self).__init__(*args) uic.loadUi('gui_files/mainWindow.ui', self) self.upload.clicked.connect(self.buttonClicked) def buttonClicked(self): print("Test") self.UploadArea.addWidget(uic.loadUi('gui_files/module.ui')) app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) Widget and MainWindow How it is supposed to look Thank you for your help Lennard
score: 0
tagged with: qt-designer
tagged with: pyqt
answer count: 1
has comment: http://stackoverflow.com/comment/85117180
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49066615
type: UnansweredQuestion
tagged with: python
has title: Insert a Widget into another Window
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/85117345

http://stackoverflow.com/comment/85207054
type: Comment
has text: Yeah, it's a pretty specific problem. I can iterate through the lists of objects and save each as a row with the attributes as individual columns, but am basically wondering if it's possible to just save each list as a cell.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49099694

http://stackoverflow.com/a/48981370
downvote count: 1
answers question: http://stackoverflow.com/q/48981294
upvote count: 0
score: -1
has body: I would use a combination of defaultdict, enumerate, and Counter: &gt;&gt;&gt; from collections import Counter, defaultdict &gt;&gt;&gt; data = '''abcd a5c1 b51d ''' &gt;&gt;&gt; poscount = defaultdict(Counter) &gt;&gt;&gt; for line in data.split(): for i, character in enumerate(line): poscount[i][character] += 1 &gt;&gt;&gt; ''.join([poscount[i].most_common(1)[0][0] for i in sorted(poscount)]) 'a5cd' Here's how it works: The defaultdict() creates new entries when it sees a new key. The enumerate() function returns both the character and its position in the line. The Counter counts the occurences of individual characters Combining the three makes a defaultdict whose keys are the column positions and whose values are character counters. That gives you one character counter per column. The most_common() method returns the highest frequency (character, count) pair for that counter. The [0][0] extracts the character from the list of (character, count) tuples. The str.join() method combines the results back together.
type: Answer

http://stackoverflow.com/q/49039518
has answer: http://stackoverflow.com/a/49039611
type: UnansweredQuestion
has title: angle between vectors - only length-1 arrays can be converted to Python scalars
has comment: http://stackoverflow.com/comment/85084397
favorite count: 0
score: -1
type: Question
tagged with: angle
tagged with: python
answer count: 1
downvote count: 1
has body: I have two 2D vectors v0L and v1L. def magnitude(v1): return(np.sqrt(v1[0]**2 +v1[1]**2)) def angle(v1, v2): return acos(np.dot(v1, v2) / (magnitude(v1) * magnitude(v2))) angle(v0L,v1L) Why is this giving me a " only length-1 arrays can be converted to Python scalars" error? Thank you so much in advance!
tagged with: vector
upvote count: 0

http://stackoverflow.com/a/49047038
upvote count: 6
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49046554
answers question: http://stackoverflow.com/q/49046554
type: Answer
has comment: http://stackoverflow.com/comment/85115335
has comment: http://stackoverflow.com/comment/85133101
has body: s += i is just sugar for s = s + i.* This means you assign a new value to the variable s (instead of mutating it in place). When you assign to a variable, Python assumes it is local to the function. However, before assigning it needs to evaluate s + i, but s is local and still unassigned -> Error. In the second case s[0] += i you never assign to s directly, but only ever access an item from s. So Python can clearly see that it is not a local variable and goes looking for it in the outer scope. Finally, a nicer alternative (in Python 3) is to explicitly tell it that s is not a local variable: def foo(n): s = n def bar(i): nonlocal s s += i return s return bar (There is actually no need for s - you could simply use n instead inside bar.) *The situation is slightly more complex, but the important issue is that computation and assignment are performed in two separate steps.
has comment: http://stackoverflow.com/comment/85099562
score: 6
has comment: http://stackoverflow.com/comment/85099143
has comment: http://stackoverflow.com/comment/85099733
type: AcceptedAnswer

numpy
tags question: http://stackoverflow.com/q/48977332
tags question: http://stackoverflow.com/q/49038780
tags question: http://stackoverflow.com/q/49111504
tags question: http://stackoverflow.com/q/48991077
tags question: http://stackoverflow.com/q/48975594
tags question: http://stackoverflow.com/q/48979197
tags question: http://stackoverflow.com/q/49073355
tags question: http://stackoverflow.com/q/49085469
tags question: http://stackoverflow.com/q/49050974
tags question: http://stackoverflow.com/q/49019281
tags question: http://stackoverflow.com/q/49047279
tags question: http://stackoverflow.com/q/49099861
tags question: http://stackoverflow.com/q/48976415
tags question: http://stackoverflow.com/q/49061864
tags question: http://stackoverflow.com/q/49011508
tags question: http://stackoverflow.com/q/49068020
tags question: http://stackoverflow.com/q/49029808
tags question: http://stackoverflow.com/q/49046757
tags question: http://stackoverflow.com/q/48978803
tags question: http://stackoverflow.com/q/49058472
tags question: http://stackoverflow.com/q/48978004
tags question: http://stackoverflow.com/q/49054927
tags question: http://stackoverflow.com/q/49032941
tags question: http://stackoverflow.com/q/49072378
tags question: http://stackoverflow.com/q/49101716
tags question: http://stackoverflow.com/q/49110691
tags question: http://stackoverflow.com/q/49085832
tags question: http://stackoverflow.com/q/48998086
tags question: http://stackoverflow.com/q/49059594
tags question: http://stackoverflow.com/q/49096771
tags question: http://stackoverflow.com/q/49054728
tags question: http://stackoverflow.com/q/49003447
tags question: http://stackoverflow.com/q/49112552
tags question: http://stackoverflow.com/q/49094026
tags question: http://stackoverflow.com/q/49036853
tags question: http://stackoverflow.com/q/49016589
tags question: http://stackoverflow.com/q/48999970
tags question: http://stackoverflow.com/q/49024042
tags question: http://stackoverflow.com/q/49061921
tags question: http://stackoverflow.com/q/49015697
tags question: http://stackoverflow.com/q/49038659
tags question: http://stackoverflow.com/q/48984978
tags question: http://stackoverflow.com/q/48972133
tags question: http://stackoverflow.com/q/49021027
tags question: http://stackoverflow.com/q/49058191
tags question: http://stackoverflow.com/q/49049535
tags question: http://stackoverflow.com/q/49096695
tags question: http://stackoverflow.com/q/49065459
tags question: http://stackoverflow.com/q/49102009
tags question: http://stackoverflow.com/q/49069186
tags question: http://stackoverflow.com/q/48988038
tags question: http://stackoverflow.com/q/49116676
tags question: http://stackoverflow.com/q/49021841
tags question: http://stackoverflow.com/q/49068615
tags question: http://stackoverflow.com/q/49093729
tags question: http://stackoverflow.com/q/49106371
tags question: http://stackoverflow.com/q/48986004
tags question: http://stackoverflow.com/q/49050166
tags question: http://stackoverflow.com/q/48990847
tags question: http://stackoverflow.com/q/49052588
tags question: http://stackoverflow.com/q/49065627
tags question: http://stackoverflow.com/q/49074194
tags question: http://stackoverflow.com/q/48998246
tags question: http://stackoverflow.com/q/49042340
tags question: http://stackoverflow.com/q/48970702
tags question: http://stackoverflow.com/q/49028608
tags question: http://stackoverflow.com/q/49011681
tags question: http://stackoverflow.com/q/49080613
tags question: http://stackoverflow.com/q/49045804
tags question: http://stackoverflow.com/q/49114732
tags question: http://stackoverflow.com/q/49101544
tags question: http://stackoverflow.com/q/49049852
tags question: http://stackoverflow.com/q/49012118
tags question: http://stackoverflow.com/q/49083643
tags question: http://stackoverflow.com/q/48966101
tags question: http://stackoverflow.com/q/49001510
tags question: http://stackoverflow.com/q/49054538
tags question: http://stackoverflow.com/q/49050287
tags question: http://stackoverflow.com/q/48968251
tags question: http://stackoverflow.com/q/49074363

http://stackoverflow.com/q/49012761
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/61680944
linked to: http://stackoverflow.com/q/2081640
has title: Using exec to load module variables, using a file path
accepted answer: http://stackoverflow.com/a/49012866
has comment: http://stackoverflow.com/comment/85030367
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85030627
has comment: http://stackoverflow.com/comment/85070894
favorite count: 0
linked to: http://stackoverflow.com/q/67631
has body: A textbook suggests I should be able to do this: d = {} exec("C://Users//Dave//Desktop//Bot//bot_config_data.py", globals(), d) File "&lt;string&gt;", line 1 C://Users//Dave//Desktop//Bot//bot_config_data.py ^ SyntaxError: invalid syntax I can do this: d = {} exec('from bot_config_data import price_data', globals(), d) But, I would like to do the former. I'm trying to write a method which overrides config data from various files. Am I completely off base here? Update The book was quite misleading. It posted part of the code, the result of the complete code block, and then gave the remainder. As I was referencing, rather than working through it cover to cover, I tripped over myself. This is the code I now have: data = {} file = 'C:\\Users\\Dave\\Desktop\\Bot\\bot_config_data.py' with open(file) as f: code = compile(f.read(), file, "exec") exec(code, globals(), data) price_data = data["price_data"] Update2 Using Mad Physicist's answer below, my code would be: from importlib.util import spec_from_loader, module_from_spec from importlib.machinery import SourceFileLoader filepath = 'C:\\Users\\Dave\\Desktop\\Bot\\bot_config_data.py' module_data = os.path.basename(filepath) spec = spec_from_loader(module_data, SourceFileLoader(module_data, filepath)) bot_config_data = module_from_spec(spec) spec.loader.exec_module(bot_config_data) price_data = bot_config_data.price_data
has answer: http://stackoverflow.com/a/49012866
tagged with: python
has comment: http://stackoverflow.com/comment/85039713
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85030607
has answer: http://stackoverflow.com/a/61680944
score: 1

http://stackoverflow.com/q/49102112
has title: Removing Spaces in Python not working
tagged with: removing-whitespace
tagged with: palindrome
answer count: 6
has answer: http://stackoverflow.com/a/49102151
possible better answer: http://stackoverflow.com/a/49102129
accepted answer: http://stackoverflow.com/a/49102131
has answer: http://stackoverflow.com/a/49102213
has answer: http://stackoverflow.com/a/49102223
favorite count: 0
has answer: http://stackoverflow.com/a/49102131
has answer: http://stackoverflow.com/a/49102182
tagged with: python
has answer: http://stackoverflow.com/a/49102129
type: AnsweredQuestion
upvote count: 2
has body: I am trying to remove spaces. I have tried everything from previous threads including re.sub Code: wordinput = (input("Input:\n")) wordinput = wordinput.lower() cleanword = wordinput.replace(" ","") cleanword = wordinput.replace(",","") cleanword = wordinput.replace(".","") revword = cleanword [::-1] print(cleanword) print(revword) print("Output:") if (cleanword == revword): print('"The word ' + wordinput + ' is a palindrome!"') else: print('"Unfortunately the word ' + wordinput + ' is not a palindrome. :(') Output: Input: mr owl ate my metal worm mr owl ate my metal worm mrow latem ym eta lwo rm Output: "Unfortunately the word mr owl ate my metal worm is not a palindrome. :(
score: 1
tagged with: spaces
has comment: http://stackoverflow.com/comment/85209419
downvote count: 1
type: Question

http://stackoverflow.com/a/49060712
score: -1
downvote count: 2
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49060671
has body: The error you are getting is most likely a TypeError coming from line 38. From what I can see, it is because you have left out the parameters on the creation of the book object (book = Book()). In your class definition, you have made it so that you need to pass a list of books, which you haven't included in the creation of the object.

http://stackoverflow.com/comment/84991672
score: 0
type: Comment
type: QuestionComment
has text: Any error of the type `TypeError: must be ..., not NoneType` usually means that you're using the return value of a function that didn't return anything. If you look in `getButton` I think you'll find the problem.
comment on: http://stackoverflow.com/q/48992680

http://stackoverflow.com/q/48972569
has answer: http://stackoverflow.com/a/48972628
upvote count: 2
has answer: http://stackoverflow.com/a/48972624
tagged with: python
possible better answer: http://stackoverflow.com/a/48972628
type: AnsweredQuestion
score: 2
type: Question
accepted answer: http://stackoverflow.com/a/48972624
downvote count: 0
has body: I am an experienced c programmer trying to come to terms with Python. location is tuple and I can print with the following print(" %s %s" % (date_time, model)) print("Lat: %-.4f, Lon: %-.4f" % (location)) I tried to combine this into a single print, but get error TypeError: must be real number, not tuple with the following print("%s %s Lat: %-.4f, Lon: %-.4f" % (date_time, model, location)) I have tried several variations, without success. I can think of several ways of working around this (which I would do if I had to deliver a working program) but would like to understand an elegant method an experienced Python programmer would use.
answer count: 2
has title: I print a tuple on its own, but not with other variables
favorite count: 0
tagged with: python-3.x
tagged with: tuples

http://stackoverflow.com/a/49051757
type: AcceptedAnswer
has body: So, basically does this mean that if my base class's metaclass is not ABCMeta(or derived from it), the class does not behave like an abstract class even though I have an abstract method in it? Correct. All abstractmethod does is mark the method with __isabstractmethod__ = True. ABCMeta does all the real work. Here is the code for abstractmethod: def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj
downvote count: 0
answers question: http://stackoverflow.com/q/49051638
type: Answer
upvote count: 11
score: 11
accepted answer of: http://stackoverflow.com/q/49051638

http://stackoverflow.com/a/49029425
has comment: http://stackoverflow.com/comment/85063479
downvote count: 0
score: 11
has comment: http://stackoverflow.com/comment/85064669
accepted answer of: http://stackoverflow.com/q/49029019
upvote count: 11
has comment: http://stackoverflow.com/comment/137373264
answers question: http://stackoverflow.com/q/49029019
has comment: http://stackoverflow.com/comment/85064159
has comment: http://stackoverflow.com/comment/85063646
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85063721
has comment: http://stackoverflow.com/comment/85063577
type: Answer
has body: Exponentiation in python has higher precedence than the negative operator. Thus -1000**(1/3) is equivalent to -(1000**(1/3)). When you doing this operation inside the loop you get (-1000)**(1/3). This equal to 10 * (-1**(1/3)) which a complex number. Now the array you have, uses a default data type since you did not define any that is determined according to the documentation as follows: dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method. So it is probably np.int16. Putting all the information together, we can conclude that your array is not equipped with the appropriate dtype attribute to be able to hold the result of (-1000)**(1/3) even though the result exists. This does not happen outside arrays since there, no dtype is assumed. Fix \ Workaround: &gt;&gt;&gt; a = np.array([-1000, 1], dtype=np.complex) &gt;&gt;&gt; for i in a: ... print(i**(1/3.)) ... (5+8.66025403784j) (1+0j)

http://stackoverflow.com/q/49012294
upvote count: 0
downvote count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85029162
has body: I have a .txt file than I read with python. I want to replace all words that contain a dash '-' and are less then 4 characters with a whitespace. Does anyone know how to do this? I have this for now: with open('text.txt', 'r') as file: filedata = file.read() filedata = filedata.replace('bla', '') with open('new text.txt', 'w') as file: file.write(filedata)
tagged with: text
score: -5
has title: Python - replace words in .txt file that contain '-' and are less than 4 characters
tagged with: replace
type: Question
tagged with: hyphenation
has comment: http://stackoverflow.com/comment/85029169
has comment: http://stackoverflow.com/comment/85029188
has comment: http://stackoverflow.com/comment/85029336
has answer: http://stackoverflow.com/a/49013028
answer count: 1
tagged with: regex
has comment: http://stackoverflow.com/comment/85029352
favorite count: 0

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/48969813

http://stackoverflow.com/q/49053285
has body: I'm developing a Python tool which uses a sqlite3 virtual table with FTS5 (Full Text Search). I would like to know how to properly install from a tarball (or any other means) the needed requirements for my tool to work so I can pack them for portability. Currently, I managed to install the latest release tarball of sqlite. However, when I execute: python3 -c "import sqlite3; print(sqlite3.sqlite_version)" # or python2 -c "import sqlite3; print(sqlite3.sqlite_version)" I get 3.11.0, while sqlite3 --version returns: 3.22.0 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2alt1 The system version sqlite3 3.22 does support FTS5, as I do pragma compile_options; and get: COMPILER=gcc-5.4.0 20160609 ENABLE_DBSTAT_VTAB ENABLE_FTS4 **ENABLE_FTS5** ENABLE_JSON1 ENABLE_RTREE ENABLE_STMTVTAB ENABLE_UNKNOWN_SQL_FUNCTION HAVE_ISNAN THREADSAFE=1 But, the python version, using this script returns this: [(u'ENABLE_COLUMN_METADATA',), (u'ENABLE_DBSTAT_VTAB',), (u'ENABLE_FTS3',), (u'ENABLE_FTS3_PARENTHESIS',), (u'ENABLE_JSON1',), (u'ENABLE_LOAD_EXTENSION',), (u'ENABLE_RTREE',), (u'ENABLE_UNLOCK_NOTIFY',), (u'ENABLE_UPDATE_DELETE_LIMIT',), (u'HAVE_ISNAN',), (u'LIKE_DOESNT_MATCH_BLOBS',), (u'MAX_SCHEMA_RETRY=25',), (u'OMIT_LOOKASIDE',), (u'SECURE_DELETE',), (u'SOUNDEX',), (u'SYSTEM_MALLOC',), (u'TEMP_STORE=1',), (u'THREADSAFE=1',)] Hence, my questions are: Is there any way I could make a linux portable package for my app with sqlite3 FTS5 support in both python and linux system? Is there any way to link the python module sqlite3 to an specific sqlite3 path? I tried all of this in an Ubuntu 16.04 LTS, but I would like to work as well on CentOS 7. Thank you very much in advance. More details about the installation from the tarball that I did: wget "https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release" -O sqlite.tar.gz tar -xzvf sqlite.tar.gz cd sqlite ./configure --enable-fts5 make sudo make install
type: Question
linked to: http://stackoverflow.com/q/36655777
score: 4
has answer: http://stackoverflow.com/a/49288829
tagged with: fts5
answer count: 3
tagged with: sqlite
tagged with: full-text-search
favorite count: 0
tagged with: linux
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/49134262
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/49134262
has title: Properly install sqlite3 with FTS5 support
has answer: http://stackoverflow.com/a/49230893
accepted answer: http://stackoverflow.com/a/49230893

http://stackoverflow.com/q/49006391
tagged with: machine-learning
has body: I have a data set X and labels y for training and scoring a sklearn.SVC model. The data is split into X_train and X_test. I run a for-loop to find the best possible value combination (i.e. best score) for two SVC parameters: C and gamma. I can print out the highest score, but how do I print the C and gamma values that were used for this particular score? for C in np.arange(0.05, 2.05, 0.05): for gamma in np.arange(0.001, 0.101, 0.001): model = SVC(kernel='rbf', gamma=gamma, C=C) model.fit(X_train, y_train) score = model.score(X_test, y_test) if score &gt; best_score: best_score = score print('Highest Accuracy Score: ', best_score)
type: Question
has answer: http://stackoverflow.com/a/49006463
score: 0
answer count: 2
has title: Python for-loop to find the best values for SVC (C and gamma)
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85017694
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49006474
tagged with: svc

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

http://stackoverflow.com/q/49120963
tagged with: pandas
has body: I'm having a strange problem with the Pandas .isin() method. I'm doing a project in which I need to identify bad passwords by length, common word/password lists, etc (don't worry, this is from a public source). One of the ways is to see if someone is using part of their name as a password. I'm using .isin() to determine if that is the case, but it's giving me weird results. To show: # Extracting first and last names into their own columns users['first_name'] = users.user_name.str.extract('(^.+)(\.)', expand = False)[0] users['last_name'] = users.user_name.str.extract('\.(.+)', expand = False) # Flagging the users with passwords that matches their names users['uses_name'] = (users['password'].isin(users.first_name)) | (users['password'].isin(users.last_name)) # Looking at the new data print(users[users['uses_name']]'password','user_name','first_name','last_name','uses_name'.head()) The output of this is: password user_name first_name last_name uses_name 7 murphy noreen.hale noreen hale True 11 hubbard milford.hubbard milford hubbard True 22 woodard jenny.woodard jenny woodard True 30 reid rosanna.reid rosanna reid True 58 golden rosalinda.rodriquez rosalinda rodriquez True Mostly it's good; milford.hubbard is using 'hubbard' as the password, etc. But then we have several examples like the first one. Noreen Hale is being flagged, despite her password being "murphy", which shares only a single letter with her name. I can't for the life of me figure out what is causing this. Does anyone know why this is happening, and how to fix it?
favorite count: 0
tagged with: python
tagged with: regex
upvote count: 5
downvote count: 0
possible better answer: http://stackoverflow.com/a/49121074
has answer: http://stackoverflow.com/a/49121074
accepted answer: http://stackoverflow.com/a/49121004
type: AnsweredQuestion
has title: Odd issue with .isin() and strings (Python/Pandas)
has answer: http://stackoverflow.com/a/49121004
type: Question
answer count: 2
score: 5

http://stackoverflow.com/comment/85281568
comment on: http://stackoverflow.com/a/49116850
has text: Thanks. It works better. Could you explain the meaning of "sep='\s{2,}' "? Why using it makes it work?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49099032
type: AnsweredQuestion
score: 1
favorite count: 0
has title: Differences between performance measurement techniques for a single method in Python
linked to: http://stackoverflow.com/q/1622943
tagged with: measure
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/7370801
tagged with: timeit
has answer: http://stackoverflow.com/a/49099360
upvote count: 2
has body: I am trying to figure out how long does it take for my LDA classifier to predict the class of a single 1080 dimensional vector. I read these threads: Measure time elapsed in Python? timeit versus timing decorator How do I get time of a Python program&#39;s execution? and found out there are several ways to do this. I tested few of them but they produced very different results. time module: import time start = time.time() lda.predict(sample) end = time.time() print(str((end-start)*10**6), 'µs') &gt;&gt;&gt; 1452.9228210449219 µs timeit module's default_timer: from timeit import default_timer as timer start = timer() lda.predict(sample) end = timer() print(str((end-start)*10**6), 'µs') &gt;&gt;&gt; 979.6129997994285 µs iPython %timeit magic function: %timeit lda.predict(sample) &gt;&gt;&gt; 52 µs ± 873 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) Am I doing something ridiculous here or is there some other explanation for the differences? Which one to trust? Thank you in advance.
answer count: 1
downvote count: 1
tagged with: performance
accepted answer: http://stackoverflow.com/a/49099360
linked to: http://stackoverflow.com/q/1557571

http://stackoverflow.com/a/48985839
score: 1
has body: In my opinion you need one level of abstraction above that of working with sockets. Something like entity that handles sending and receiving response. Then you go and make specialization of it, that creates socket, sends data, receives response, etc. That one you use in real scenarios. However, to have something that is good for unit tests, you go and mock this entity to have dummy methods that do nothing and return what you want them to. Now you apparently think, well this is not testing anything. And you are right. However, I don't think you should unit test socket communication, but methods and functions that process data that is sent/received. Other approach is to create localhost server on desired port that will respond with data given in advance. But that is nothing more than above mentioned approach but with more overhead of creating server side, defining protocol etc., and all of that just for unit test.
has comment: http://stackoverflow.com/comment/84976612
type: Answer
has comment: http://stackoverflow.com/comment/84976164
upvote count: 1
answers question: http://stackoverflow.com/q/48985330
has comment: http://stackoverflow.com/comment/84976258
downvote count: 0

http://stackoverflow.com/q/49035644
has title: Sentiment analysis using pyspark
downvote count: 0
has answer: http://stackoverflow.com/a/49604585
type: UnansweredQuestion
score: 1
type: Question
tagged with: python
favorite count: 0
has body: Since I am all new to pyspark, can anyone help me with the pyspark implementation of sentiment analysis. I have done the Python implementation. Can anyone tell me what changes are to be made? import nltk import sys reload(sys) sys.setdefaultencoding("utf-8") from nltk.classify import NaiveBayesClassifier def format_sentence(sent): return({word: True for word in nltk.word_tokenize(sent)}) #print(format_sentence("The cat is very cute")) pos = [] with open("./pos_tweets.txt") as f: for i in f: pos.append([format_sentence(i), 'pos']) neg = [] with open("./neg_tweets.txt") as fp: for i in fp: neg.append([format_sentence(i), 'neg']) # next, split labeled data into the training and test data training = pos[:int((.8)*len(pos))] + neg[:int((.8)*len(neg))] test = pos[int((.8)*len(pos)):] + neg[int((.8)*len(neg)):] classifier = NaiveBayesClassifier.train(training) example1 = "no!" print(classifier.classify(format_sentence(example1)))
upvote count: 1
answer count: 1
tagged with: pyspark

http://stackoverflow.com/comment/85052294
score: 0
has text: I don't think it is possible to "reorder" it like this
type: Comment
comment on: http://stackoverflow.com/q/49023711
type: QuestionComment

http://stackoverflow.com/comment/85049352
type: AnswerComment
has text: It is a terrible idea, I will mention this to be clear.
type: Comment
comment on: http://stackoverflow.com/a/49021934
score: 0

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

http://stackoverflow.com/a/54304196
upvote count: 1
answers question: http://stackoverflow.com/q/49071121
has body: Same problem on my Mac. Maybe it got broken when I updated to Mojave? Who knows. Resolved with a brew install of Python 2: brew install python2 This now takes over from my factory-installed Python 2.7 and gives me a new virtualenv that works: $ which virtualenv /usr/local/bin/virtualenv
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/48967207
answer count: 1
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has title: Convert Time with AM/PM and +UCT (Python)
has answer: http://stackoverflow.com/a/48967278
has body: I'm trying to convert '11/09/2011 11:33:00 PM +0000' (object) into a datetime variable using Pandas' pd.to_datetime(): df['Datetime'] = pd.to_datetime(df['Datetime'],format = '%d/%m/%Y %I:%M:%S %p', utc=True) however getting a error back: "duplicate columns &amp; possible reduce dimensionality" Any suggestions?
downvote count: 0
accepted answer: http://stackoverflow.com/a/48967278
tagged with: pandas
type: AnsweredQuestion
tagged with: datetime

http://stackoverflow.com/q/49028611
downvote count: 1
type: Question
upvote count: 80
has answer: http://stackoverflow.com/a/49033954
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/20971619
tagged with: pytest
has comment: http://stackoverflow.com/comment/85063114
answer count: 2
has comment: http://stackoverflow.com/comment/85071283
accepted answer: http://stackoverflow.com/a/49033954
favorite count: 0
score: 79
has comment: http://stackoverflow.com/comment/85064213
has body: I am following the pytest good practices or at least I think I am. However, pytest cannot find my module. It seems not to include the current directory in its PYTHONPATH. The source file: def add(x, y): return x + y The test file: import pytest from junk.ook import add def test_add_true(): assert add(1, 1) == 2 And the shell output with a Python 3 virtual environment called "p3". p3; pwd /home/usr/tmp/junk p3; ls total 0 0 junk/ 0 tests/ p3; ls junk total 4.0K 4.0K ook.py 0 __init__.py p3; ls tests total 4.0K 4.0K test_ook.py 0 __pycache__/ p3; pytest ============================= test session starts ============================== platform linux -- Python 3.4.5, pytest-3.4.1, py-1.5.2, pluggy-0.6.0 rootdir: /home/usr/tmp/junk, inifile: collected 0 items / 1 errors ==================================== ERRORS ==================================== ______________________ ERROR collecting tests/test_ook.py ______________________ ImportError while importing test module '/home/usr/tmp/junk/tests/test_ook.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: tests/test_ook.py:2: in <module> from junk.ook import add E ImportError: No module named 'junk' !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!! =========================== 1 error in 0.08 seconds ============================ def test_add_true(): assert add(1, 1) == 2 However, running the following does work fine. p3; python -m pytest tests/ ============================= test session starts ============================== platform linux -- Python 3.4.5, pytest-3.4.1, py-1.5.2, pluggy-0.6.0 rootdir: /home/usr/tmp/junk, inifile: collected 1 item tests/test_ook.py . [100%] =========================== 1 passed in 0.02 seconds =========================== What am I doing wrong?
tagged with: python
has title: pytest cannot find module
has comment: http://stackoverflow.com/comment/132849570
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49029629
has comment: http://stackoverflow.com/comment/85061548
has comment: http://stackoverflow.com/comment/85061653
has answer: http://stackoverflow.com/a/49029629

http://stackoverflow.com/a/49085781
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85177019
has comment: http://stackoverflow.com/comment/85180809
answers question: http://stackoverflow.com/q/49085756
has comment: http://stackoverflow.com/comment/85176898
type: Answer
has body: You can try this: import re mylist=["'one'","{two}","'three'","four","{{{five}}}","s*ix"] new_list = list(map(lambda x:re.sub('^[^a-z]|[^a-z]$', '', x), mylist)) Output: ['one', 'two', 'three', 'four', '{{five}}', 's*ix'] Edit: to remove elements containing a special character, you can try this: new_list = list(filter(lambda x:not re.findall('^[^a-z]|[^a-z]$', x), mylist)) Output: ['four', 's*ix']
has comment: http://stackoverflow.com/comment/85176880
has comment: http://stackoverflow.com/comment/85177612
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49085756
has comment: http://stackoverflow.com/comment/85177223
score: 3
has comment: http://stackoverflow.com/comment/85177121
has comment: http://stackoverflow.com/comment/85177092
has comment: http://stackoverflow.com/comment/85177165
has comment: http://stackoverflow.com/comment/85176924
has comment: http://stackoverflow.com/comment/85177214

http://stackoverflow.com/comment/85138888
comment on: http://stackoverflow.com/q/49066266
type: QuestionComment
score: 1
has text: is this a `socket.socket` object, from the `socket` standard library module?
type: Comment

http://stackoverflow.com/a/49099105
answers question: http://stackoverflow.com/q/49098987
has comment: http://stackoverflow.com/comment/85268715
has comment: http://stackoverflow.com/comment/85393692
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85260058
has comment: http://stackoverflow.com/comment/85393608
has body: With a bit of list comprehension, .split(), .strip() and .join() you can build that output like: Code: text = [l.strip() for l in content.text.split('\n') if l.strip()] print('\n'.join(' '.join(l) for l in zip(text[::2], text[1::2]))) Test Code: import urllib, urllib2, re, HTMLParser, os from bs4 import BeautifulSoup import os pg_source = '' req = urllib2.Request('http://rushmore.tv/schedule') req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36') try: response = urllib2.urlopen(req) pg_source = response.read().decode('utf-8', 'ignore') response.close() except: pass content = [] soup = BeautifulSoup(pg_source) content = BeautifulSoup(soup.find('ul', {'id': 'myUL'}).prettify()) text = [l.strip() for l in content.text.split('\n') if l.strip()] print('\n'.join(' '.join(l) for l in zip(text[::2], text[1::2]))) Results: 21:00 - 23:00 NCAAB: Pepperdine vs Saint Mary's - Channel 03 21:30 - 00:00 AFL: Gold Coast vs. Geelong - Channel 47 22:00 - 00:00 A-League: Western Sydney Wanderers vs Perth Glory - BT Sport 1 22:45 - 03:00 Ski Classic: Mora - Channel 93 23:00 - 00:30 Freestyle Skiing WC: Ski Cross - Channel 106

http://stackoverflow.com/comment/84962848
score: 0
type: Comment
type: QuestionComment
has text: If you want to be helpful, you should post a reply with suggestions to fix the issue... instead of just trying to point out what is wrong. `root.after(0, MouseCounter().count()` runs after `root.mainloop()` and it is working. It calls the method `count()` and inside the method there is `root.after(1, self.count)` which calls itself so it keeps running which is my desired functionality so the program is constantly looking for mouse clicks. It is replacing a while loop I had. If you would like to respond, please be specific in what to change and why. Thank you.
comment on: http://stackoverflow.com/q/48977312

http://stackoverflow.com/q/49078127
has title: Function call to self with return statement works ...but why?
has comment: http://stackoverflow.com/comment/85196114
score: -1
tagged with: sorting
linked to: http://stackoverflow.com/q/11693819
has comment: http://stackoverflow.com/comment/85162400
answer count: 2
has comment: http://stackoverflow.com/comment/85195787
upvote count: 0
has answer: http://stackoverflow.com/a/49078271
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85162343
tagged with: recursion
has answer: http://stackoverflow.com/a/49079023
has comment: http://stackoverflow.com/comment/85162334
has body: I am trying to get my head around Python having only really ever coded in Java in the past. I need some help understanding some code if someone can help, or point me in the direction of a good (simple) resource please? I have written a Binary sort in Python from some pseudocode, it works but I don't understand how. The function would make sense to me if the code below didn't have a return statement on the line: return findData( data, criteria, first, mid -1 ) Or if I set up a while loop and just modified the start or end index variable based on which half of the list I needed to reference. But with this code I don't understand where the function is being returned to, or why the code fails if i remove them?? It makes sense that I return -1 as no match and 'mid' to reference the list position of a match, but the return statement passing data, criteria, first and last should surly cause a syntax error as there is no call to such a function? Thanks in advance to anyone who can explain how what I have written works. My code is below. Mr.D # Binary Search def findData( data, criteria, first, last ): if( last &lt; first ): return -1 else: mid = ( last + first ) // 2 if( criteria == data[mid] ): return mid elif ( criteria &gt; data[mid] ): print( "Currently looking at", data[mid], "in array poition", mid ) return findData( data, criteria, mid +1, last ) elif( criteria &lt; data[mid] ): print( "Currently looking at", data[mid], "in array poition", mid ) return findData( data, criteria, first, mid -1 ) Data = [15, 21, 29, 32, 37, 40, 42, 43, 48, 50, 60, 64, 77, 81, 90, 98] Criteria = 98 Location = -1 Location = findData( Data, Criteria, 0, len( Data ) -1 ) if( Location &lt; 0 ): print( Criteria, "is not located in the array." ) else: print( Criteria, "is located in array position ", Location )
downvote count: 1
type: Question

http://stackoverflow.com/q/49053729
has comment: http://stackoverflow.com/comment/85114782
has title: in __init__ word=self.search_box.text AttributeError: 'NoneType' object has no attribute 'text'
has answer: http://stackoverflow.com/a/49055542
score: 0
answer count: 1
has body: I am making an application.as far as I know I am doing thingd correctly but still getting this error word=self.search_box.text AttributeError: 'NoneType' object has no attribute 'text' I have checked for typos and other common mistakes still its not working. heres the code- import kivy kivy.require('1.10.0') from kivy.uix.stacklayout import StackLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.app import App from kivy.uix.popup import Popup from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.properties import ObjectProperty from kivy.uix.textinput import TextInput from kivy.properties import StringProperty import json Builder.load_file('VocabularyJournal.kv') class MenuPage(Screen): pass class DisplayPage(Screen): search_box= ObjectProperty() label_maening=StringProperty() label_synonym=StringProperty() label_ant=StringProperty() label_sentence=StringProperty() def __init__(self, **kwargs): super(DisplayPage,self).__init__(**kwargs) with open('vocab_words.json') as rfile: data=json.load(rfile) word=self.search_box.text #the error occurred here for value in data: if value['word']==word: self.label_maening=value['meaning'] self.label_synonym=value['synonym'] self.label_ant=value['antonyms'] self.label_sentence=value['sentence'] class WordInsertPage(Screen): pass class NewWordPage(Screen): word_box = ObjectProperty() meaning_box = ObjectProperty() synonym_box = ObjectProperty() ant_box = ObjectProperty() sentence_box = ObjectProperty() def saving_data(self): with open('vocab_words.json') as rfile: data=json.load(rfile) entry={'word': self.word_box.text, 'meaning': self.meaning_box.text, 'synonym': self.synonym_box.text, 'antonyms': self.ant_box.text, 'sentence': self.sentence_box.text} data.append(entry) with open('vocab_words.json','w') as wfile: json.dump(data,wfile,indent=4) class FlashCard(Screen): pass class WordGroups(Screen): pass c…
tagged with: python
accepted answer: http://stackoverflow.com/a/49055542
tagged with: kivy
has comment: http://stackoverflow.com/comment/85112241
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85115327

http://stackoverflow.com/q/49005963
tagged with: pyqt
has body: I'm trying to make my app support multi threading in connection with GUI , I'm trying to connect to method inside GUI from threading outside GUI, I have inspired this idea from Simplest way for PyQT Threading and it was marked as working solution , where is my fault Below is the error. class Communicate(QtCore.QObject): myGUI_signal = QtCore.pyqtSignal(str) def myThread(callbackFunc): # Setup the signal-slot mechanism. mySrc = Communicate() mySrc.myGUI_signal.connect(callbackFunc) # Endless loop. You typically want the thread # to run forever. while(True): # Do something useful here. msgForGui = 'This is a message to send to the GUI' mySrc.myGUI_signal.emit(msgForGui) FORM_CLASS, _ = loadUiType(os.path.join(os.path.dirname('__file__'), "main.ui")) class MainApp(QMainWindow, FORM_CLASS): # QMainWindow refere to window type used in ui file # this is constructor def __init__(self, parent=None): super(MainApp, self).__init__(parent) QMainWindow.__init__(self) self.setupUi(self) self.ui() self.actions() def ui(self): self.setFixedSize(848, 663) def actions(self): self.pushButton.clicked.connect(self.startTheThread) def theCallbackFunc(self, msg): print('the thread has sent this message to the GUI:') print(msg) print('---------') def startTheThread(self): # Create the new thread. The target function is 'myThread'. The # function we created in the beginning. t = threading.Thread(name = 'myThread', target = myThread, args =(self.theCallbackFunc)) t.start() def main(): app = QApplication(sys.argv) window = MainApp() # calling class of main window (first window) window.show() # to show window app.exec_() # infinit loop to make continous show for window if __name__ == '__main__': main()
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49017756
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/85017649
tagged with: python
linked to: http://stackoverflow.com/q/37252756
type: AnsweredQuestion
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/49017756
type: Question
has comment: http://stackoverflow.com/comment/85017775
score: 0
has title: Python GUI with PyQt5 Multi Threading

http://stackoverflow.com/comment/85223878
type: Comment
has text: This, this, this! Thanks - @mhawke !
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49107679

http://stackoverflow.com/comment/85124036
comment on: http://stackoverflow.com/q/49059421
type: Comment
has text: Without knowing more about your data, I guess they are the raw values that SAS exports and it just applies an `int` filter when it displays them to you. Is there a way to explore the cars.sas7bdat file in a text editor?
score: 0
type: QuestionComment

http://stackoverflow.com/a/49011415
has comment: http://stackoverflow.com/comment/85039868
has comment: http://stackoverflow.com/comment/85042612
has comment: http://stackoverflow.com/comment/85038812
upvote count: 2
has comment: http://stackoverflow.com/comment/85040488
downvote count: 1
has comment: http://stackoverflow.com/comment/85040830
has comment: http://stackoverflow.com/comment/85042550
answers question: http://stackoverflow.com/q/49001152
type: Answer
has body: <a href="https://tio.run/##fY@xbsMwDER3f8Uhk@W0hp12qY1m6x90C4JCsNTWQC0KEoM6CPLtLtXYGTKEE3FHviP9kb/JbaapHzwFhtFsuR9s9kkBdvSE3mEM2n3ZHPUGqskgpfEqBotUoSgug6rFKLLGI@oWUdoFVl6bA3eOfnPVfoidy7zQZ7iGSoh3Y39Y312WgNjCh/8DVqeqwRYv5rw7xD2it44TdeePT3swyRx1NsabtLp6W5/qpto@m3MKXpXy8KAFmLxUKOZbymg7ciZivQhD3wVaVPUwvw@VTdMf" rel="nofollow noreferrer" title="Python 2 implements range( a ) by first generating the list-representation of all the range()-defined values ... [MEMORY ERROR] next terminates efforts beyond the reach of the underlying resources on some operating systems or freezes the system at all on other ...">Call x in range( a ) slow? ( Notice py2 hidden RISK if using range() ... ) 23[us] spent in [py2] to process ( x in range( 10E+0000 ) ) 4[us] spent in [py2] to process ( x in range( 10E+0001 ) ) 3[us] spent in [py2] to process ( x in range( 10E+0002 ) ) 37[us] spent in [py2] to process ( x in range( 10E+0003 ) ) 404[us] spent in [py2] to process ( x in range( 10E+0004 ) ) 4433[us] spent in [py2] to process ( x in range( 10E+0005 ) ) 45972[us] spent in [py2] to process ( x in range( 10E+0006 ) ) 490026[us] spent in [py2] to process ( x in range( 10E+0007 ) ) 2735056[us] spent in [py2] to process ( x in range( 10E+0008 ) ) MemoryError A syntax of in range( a ) constructor is not only slow in [TIME]-domain, having --at best-- O(log N), if done smarter, than a pure sequential search through the enumerated domain of list-ed values, but in py2, the native range() always has also a composite add-on O( N ) costs of both the [TIME]-domain costs ( a time to build ) and also the [SPACE]-domain costs ( allocating the space to store + spending more time to put all those data through ... ) of such a range-based memory-representation construction. Let's benchmark a safe, O( 1 ) scaled approach ( +always do benchmark ) &gt;&gt;&gt; from zmq import Stopwatch &gt;&gt;&gt; aClk = Stopwatch() &gt;&gt;&gt; a = 123456789; x = 123456; aClk.start(); _ = ( 0 &lt;= x &lt; a );aClk.stop() 4L &gt;&…
score: 1

http://stackoverflow.com/q/49059916
accepted answer: http://stackoverflow.com/a/49063113
answer count: 1
favorite count: 0
has body: I'm trying to plot a networkx graph with bokeh using bokeh's from_networkx function with the nx.spring_layout argument. I'm trying to define my graph and its attributes in a pandas dataframe as much as possible. I would like to initialize positions of my nodes; how do I pass these positions to the spring_layout? (If it is passed into the nx.spring_layout(...), I'm not getting the format correct.) Any direction would be helpful. Put another way, for bokeh.from_networkx(G, networkx.spring_layout...), how to I pass arguments to spring_layout as I would when not using bokeh (e.g., networkx.spring_layout(G, dim=2, k=None, pos=None...)) Simple example: import networkx as nx import pandas as pd from bokeh.models import Plot, ColumnDataSource, Range1d, from_networkx, Circle,MultiLine from bokeh.io import show, output_file from bokeh.palettes import Viridis #define graph source = ['A', 'A', 'A','a','B','B','B','b'] target = ['a', 'B','b','b','a','b','A','a'] weight = [1,-1000,1,1,1,1, -1000, 1] df = pd.DataFrame([source,target,weight]) df = df.transpose() df.columns = ['source','target','weight'] G=nx.from_pandas_dataframe(df, 'source', 'target', ['weight']) #set node attributes node_color = {'A':Viridis[10][0], 'B':Viridis[10][9],'a':Viridis[10][4],'b':Viridis[10][4]} node_size = {'A':50, 'B':40,'a':10,'b':10} node_initial_pos = {'A':(-0.5,0), 'B':(0.5,0),'a':(0,0.25),'b':(0,-0.25)} nx.set_node_attributes(G, 'node_color', node_color) nx.set_node_attributes(G, 'node_size', node_size) nx.set_node_attributes(G, 'node_initial_pos', node_initial_pos) #source with node color, size and initial pos (perhaps ) source = ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in G.nodes(data=True)}, orient='index')) plot = Plot(plot_width=400, plot_height=400, x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) graph_renderer = from_networkx(G, nx.spring_layout, scale=0.5, center=(0,0)) #style graph_renderer.node_renderer.data_source = source graph_renderer.node_renderer.glyph = Circle…
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Python How to pass networkx layout arguments through Bokeh's from_networkx
tagged with: bokeh
has answer: http://stackoverflow.com/a/49063113
tagged with: networkx
type: Question
downvote count: 0

http://stackoverflow.com/comment/85082437
has text: I upvoted your answer. Well done! finding the solution to your own problem :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49038339
type: Comment

shutil
tags question: http://stackoverflow.com/q/49039323
tag name: shutil
tags question: http://stackoverflow.com/q/49011058
tags question: http://stackoverflow.com/q/49005470
type: Tag

http://stackoverflow.com/a/49090794
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: sorted does a stable sort. That means for ties, the order of items will be the same as the order they appear in the original input. Since your Counter is unordered, the input to sorted is in some undefined order. If you want you can sort by the key, and then the value: sorted(sorted(c.items(), key=lambda x:x[0], reverse=True), key = lambda x:x[1] , reverse=True) Or (probably better) have your sort function return a tuple as the sort key: sorted(c.items(), key=lambda x:(x[1], x[0]), reverse=True) An (even better!) version utilizing operator.itemgetter: sorted(c.items(), key=itemgetter(1,0), reverse=True)
has comment: http://stackoverflow.com/comment/85187176
answers question: http://stackoverflow.com/q/49090690

http://stackoverflow.com/comment/85192278
type: AnswerComment
type: Comment
has text: Thank you! By the .save() method I mean the one used with commit=True, ultimately saving the form (form.save())
comment on: http://stackoverflow.com/a/49093501
score: 0

http://stackoverflow.com/q/48983860
has body: I have two Dictionaries with the same keys but the values are different intergers. They both look like: Dict 1 Dict2 SEQ|1|,0 SEQ|1|,4 SEQ|2|,9 SEQ|2|,7 I need to identify those keys values which are 0 if the same key value in another Dict has an int higher than 1 (Or not 0). So in this case I would like to report SEQ|1|,0 from Dict1 Thanks. Note: The dicts have exactly the same Keys.
downvote count: 1
has comment: http://stackoverflow.com/comment/84972533
type: Question
has comment: http://stackoverflow.com/comment/84972343
has comment: http://stackoverflow.com/comment/84972442
has comment: http://stackoverflow.com/comment/84972367
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48984540
has comment: http://stackoverflow.com/comment/84972527
has comment: http://stackoverflow.com/comment/84972388
favorite count: 0
has comment: http://stackoverflow.com/comment/84972816
type: UnansweredQuestion
has title: Python: Compare two dictionaries with the same keys, identify the keys with 0 as value if the other dictionary value is more than 0
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84972542
has answer: http://stackoverflow.com/a/48984303

http://stackoverflow.com/a/49022571
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49022511
has body: If you've installed both PIL and Pillow then you need to uninstall one of them. Because they cannot co-exist in the same environment. Reference can be found here.

http://stackoverflow.com/comment/84972307
comment on: http://stackoverflow.com/q/48983819
has text: Use double quotes, not single
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85036393
comment on: http://stackoverflow.com/q/49015697
score: 0
type: Comment
type: QuestionComment
has text: @MohsinBukhari,yes and it's a he,have to update the name

http://stackoverflow.com/a/49040693
answers question: http://stackoverflow.com/q/49039956
type: AcceptedAnswer
upvote count: 3
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49039956
score: 3
has body: Suppose you have a function tokenize that transforms the strings to a list of words. Then you can flatMap documents to get an RDD of tuples (word, document id): flattened_docs = documents.flatMap(lambda x: [(word, x[0]) for word in tokenize(x[1])]) Then joining with words will give you (word, (document id, vector)) tuples, and you can drop the words at this point: doc_vectors = flattened_docs.join(words).values Note that this is an inner join, so you're throwing away an words that do not have embeddings. Since you presumably want to count those words in your average, a left join is likely more appropriate and you'll then have to replace any resulting Nones with the zero vector (or whatever vector of your choice). We can group by document id to get an rdd of (document id, [list of vectors]) and then average (I'll assume you have a function called average). final_vectors = doc_vectors.groupByKey().mapValues(average) (Please excuse my Scala-influenced Python. It's been a while since I've used pyspark and I haven't checked if it's flatMap or flat_map and so on.)

data-manipulation
tags question: http://stackoverflow.com/q/48976646
type: Tag
tags question: http://stackoverflow.com/q/49071571
tag name: data-manipulation

http://stackoverflow.com/q/49050858
tagged with: python
downvote count: 4
has body: Im using this to get the number of email messages in my inbox print("There are: {0}" .format(myEmailInfo)) It works sort of but what it returns is There Are (2,217715) Any ideas why? Thanks in Advance
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49051639
tagged with: formatting
type: Question
has comment: http://stackoverflow.com/comment/85106074
has answer: http://stackoverflow.com/a/49051639
has title: Issue with Python .format()
has comment: http://stackoverflow.com/comment/85106190
has comment: http://stackoverflow.com/comment/85106105
has comment: http://stackoverflow.com/comment/85106131
answer count: 1
has comment: http://stackoverflow.com/comment/85107488
favorite count: 0
upvote count: 0
score: -4

http://stackoverflow.com/comment/85124722
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49059576
has text: No problem, `zip` is sometimes a bit "non-linear".
type: AnswerComment

http://stackoverflow.com/q/48977607
linked to: http://stackoverflow.com/q/5942402
tagged with: python
has comment: http://stackoverflow.com/comment/84960441
accepted answer: http://stackoverflow.com/a/48977873
has body: I have over a Million times snapshots files that I need to merge and create a single file/db for analysis. My attempt to do this in the code below. first, I read a small csv from a list of URLs, takes a few columns, parse date field from text to date and writes it to a sqlite database. while this code works well enough over a small subset of files, is too slow to iterate over a million CSVs. I'm not sure how to increase performance or even whether Python is the right tool for the job or not. any help in improving this code or suggestions will be much appreciated. import pandas as pd from sqlalchemy import create_engine import datetime import requests import csv import io csv_database2 = create_engine('sqlite:///csv_database_test.db') col_num = [0,8,9,12,27,31] with open('url.csv','r') as line_list: reader = csv.DictReader(line_list,) for line in reader: data = requests.get(line['URL']) df = pd.read_csv(io.StringIO(data.text), usecols=col_num, infer_datetime_format=True) df.columns.values[0] = 'DateTime' df['ParseDateTime'] = [datetime.datetime.strptime(t, "%a %b %d %H:%M:%S %Y") for t in df.DateTime] df.to_sql('LineList', csv_database2, if_exists='append')
has title: Python: reading over 1M small csv files and writing to a db
has answer: http://stackoverflow.com/a/48977873
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84960419
has comment: http://stackoverflow.com/comment/84961216
has comment: http://stackoverflow.com/comment/84960413
type: Question
favorite count: 0
upvote count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: sql
answer count: 1

http://stackoverflow.com/comment/85157235
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49074706
has text: See my answer to the top question. No, I'm not saying you should eliminate the second class.

http://stackoverflow.com/comment/85201095
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49097886
type: Comment
has text: @FooBar Sorry, copied some code I was testing to check something. Updated accordingly. And bigbounty What do you mean? Can you explain further?

http://stackoverflow.com/a/49003382
type: Answer
has body: xml.etree module only supports limited subset of XPath 1.0, which doesn't include contains(). So you'll need to do the 'contains' check in python: columnfind = twbroot.findall('data/column') for col in columnfind: if '(group)' in col.get('name'): print col.get('name') or alternatively : cols = [e.get('name') for e in root.findall("data/column") if '(group)' in e.get('name')] print(cols) eval.in demo If you can afford to use lxml, it has full XPath 1.0 support, so you'll be able to do the check in XPath directly : cols = [e.get('name') for e in root.xpath("data/column[contains(@name,'(group)')]")] print(cols)
accepted answer of: http://stackoverflow.com/q/49002831
downvote count: 0
answers question: http://stackoverflow.com/q/49002831
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85011630

http://stackoverflow.com/q/49065803
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85136863
has comment: http://stackoverflow.com/comment/85136625
favorite count: 0
type: Question
tagged with: python
tagged with: destructor
accepted answer: http://stackoverflow.com/a/49066227
tagged with: reference
has comment: http://stackoverflow.com/comment/85137575
upvote count: 7
has title: Python: Delete Objects and Free Up Space
answer count: 1
downvote count: 1
has body: Python documentation said that an object is considered deleted if the reference counts to the object is zero and the difference between del and __del__ is that: del reduces the reference count to an object by one __del__ executes when the reference count to an object is zero That means if we keep delete the reference to an object until the reference count to zero. It would executes __del__ to delete the object to free up memory. However, what is troubling me is that: If I create an object and bind the object to the name ObjectX. It would increase the reference count by 1, right? If I create a list with the name ListY and I append the ListY with ObjectX. It means that it would increase the reference count to 2, right? Now, if I delete ObjectX and ListY, would the reference count to the object is still remains as 1 and the object is still remaining sitting there in hard disk waiting for some kind soul to come and kill it? Any comments and thoughts are welcomed.... By the way, if what is happening is really what I understand about deleting object in Python. Is there any good suggestion for how to delete an object that is appended into a list and free up the memory space? class Slave: def __init__(self): self.name="" def __del__(self): print("SLAVE DEAD") def sequence(): SlaveX=Slave() slaveList=list() slaveList.append(SlaveX) del SlaveX print("I AM NOT DEAD YET") del slaveList
has comment: http://stackoverflow.com/comment/85136722
tagged with: object
has comment: http://stackoverflow.com/comment/85136814
has comment: http://stackoverflow.com/comment/85137986
has comment: http://stackoverflow.com/comment/85137055
has comment: http://stackoverflow.com/comment/85136633
score: 6
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49066227
has comment: http://stackoverflow.com/comment/85136753

http://stackoverflow.com/a/49042846
downvote count: 0
type: Answer
score: 1
has body: You don't. The behavior you desire is completely unexpected and somewhat bizarre. Calling A() is expected to return an instance of A. Doing anything else is confusing and unintuitive, which makes it difficult to read and understand any code invoking it. Alternative If you really need this behavior, create a factory method: def make_thing(a, b): if 0 == b: return int(a) else: return A(a, b) Obviously, you need a better name than make_thing, but without any context, I can't give you any suggestions. Avoid the problem if possible Since A is not a number and is generally not compatible with int, it is also somewhat strange to store both int and A in the same variable. If all you're doing is converting to a string, then you don't need a class at all. A simple method outside of a class is the better alternative: def a_and_b_to_string(a, b): if b == 0: return str(int(a)) else: return str(a) + ":" + str(b) If you're doing more than that, your calling code will probably end up looking something like this: x = make_thing(input1, input2) if isinstance(x, A): result = x.some_method_from_a() # Or some other calculation requiring an A else: result = 5 * x # Or some other calculation requiring an `int` This is somewhat silly: you write a method to choose the data type and then have to write specialized code for each possible result. You're not getting any benefits from having a function that returns the separate types here. I can think of two simpler alternatives: Just move the check to the calling code: if input2 == 0: temp = A(input1, input2) result = temp.some_method_from_a() # Or some other calculation requiring an A else: result = 5 * int(input1) # Or some other calculation requiring an int If you go this route, you should also modify A.__init__ to throw a ValueError if b == 0, since that would be an invalid state for an A to be in. Modify A so that it works properly regardless of whether b is 0: class A(object): def __init__(self,a,b): self.a = a self.b = b def some_method_f…
upvote count: 1
answers question: http://stackoverflow.com/q/49038098

http://stackoverflow.com/comment/92311275
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48982339
has text: yes i asked a new question i posted question link in above comment. what i need is if we use `!ping` command bot posts a message or embed with `Pong` and that embed should come with reactions added.

pymongo
tags question: http://stackoverflow.com/q/48969350
tags question: http://stackoverflow.com/q/48970898
type: Tag
tag name: pymongo
tags question: http://stackoverflow.com/q/48972932
tags question: http://stackoverflow.com/q/49014697
tags question: http://stackoverflow.com/q/49046987
tags question: http://stackoverflow.com/q/49060924

http://stackoverflow.com/q/49099436
tagged with: pandas
answer count: 1
has title: Unable to read from object of type: <class 'numpy.ndarray'>
accepted answer: http://stackoverflow.com/a/49100208
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49100208
has body: I have the following python code which I am trying to output to a directory based on timestamp. import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import uuid data = {'date': ['2018-03-04T14:12:15.653Z', '2018-03-03T14:12:15.653Z', '2018-03-02T14:12:15.653Z', '2018-03-05T14:12:15.653Z'], 'battles': [34, 25, 26, 57], 'citys': ['london', 'newyork', 'boston', 'boston']} df = pd.DataFrame(data, columns=['date', 'battles', 'citys']) df['date'] = df['date'].map(lambda t: pd.to_datetime(t, format="%Y-%m-%dT%H:%M:%S.%fZ")) df.groupby(by=['citys']) dst_path = "logs/year=" + df['date'].dt.year.astype('str').unique() + "/month=" + df['date'].dt.month.astype('str').unique() + "/day=" + df['date'].dt.day.astype('str').unique() + "/" + str(uuid.uuid4()) + ".parq" table = pa.Table.from_pandas(df) pq.write_table(table, dst_path) but i am seeing the following error: python3 test.py Traceback (most recent call last): File "test.py", line 15, in &lt;module&gt; pq.write_table(table, dst_path) File "/usr/local/lib/python3.6/site-packages/pyarrow/parquet.py", line 943, in write_table **kwargs) File "/usr/local/lib/python3.6/site-packages/pyarrow/parquet.py", line 286, in __init__ **options) File "pyarrow/_parquet.pyx", line 837, in pyarrow._parquet.ParquetWriter.__cinit__ (/Users/travis/build/BryanCutler/arrow-dist/arrow/python/build/temp.macosx-10.6-intel-3.6/_parquet.cxx:14606) File "pyarrow/io.pxi", line 835, in pyarrow.lib.get_writer (/Users/travis/build/BryanCutler/arrow-dist/arrow/python/build/temp.macosx-10.6-intel-3.6/lib.cxx:59078) TypeError: Unable to read from object of type: &lt;class 'numpy.ndarray'&gt; how can i create a directory from pandas timestamp?
type: Question
score: 0

http://stackoverflow.com/a/48987027
has body: your first loop only stores the filenames, without the root directory. After that, using realpath (or abspath) doesn't solve anything: the directory path information is already lost. You don't need recursion, since you break at first iteration, so the best way would be to use os.listdir and append the path (and use abspath to convert to absolute path): the_dir = "Samples" paths = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir)] alternative with glob.glob: import glob paths = glob.glob(os.path.abspath("Samples/*")) also note that instead of abspath/realpath, most of the time the Samples directory is relative to your python file. In that case, just do: the_dir = os.path.join(os.path.dirname(__file__),"Samples") and drop all absolute/real path conversion. The advantage is that you can change directory/run the app from another directory and the "resource" files are still reachable.
has comment: http://stackoverflow.com/comment/84979096
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48986753
answers question: http://stackoverflow.com/q/48986753
type: Answer

http://stackoverflow.com/comment/85126074
comment on: http://stackoverflow.com/a/49059794
has text: Thanks for this, very helpful, it drops the rows as required. When I next sort the dataframe using `df.sort_values(by=['date'])` the rows stay in the previous order, i.e. with no obvious sorting from before, row 0 is Jan 1, row 1 is Feb 1, etc., and I'm hoping to sort into row 0 is Jan 1, row 1 is Jan 2, etc. Can this be rectified to allow for a more sortable date column?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49018980
answer count: 1
has title: Check if two numpy array rows simultaneously satisfy a proposition
accepted answer: http://stackoverflow.com/a/49019425
score: 1
has comment: http://stackoverflow.com/comment/85043682
tagged with: python-3.x
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85043562
linked to: http://stackoverflow.com/q/48978144
has answer: http://stackoverflow.com/a/49019425
type: Question
tagged with: numpy
has body: This is a follow-up post to a previous question of mine: Check whether numpy array row is smaller than the next Suppose i have the following numpy array: a=np.reshape(np.array(79,np.nan,87,77,92,133,99,121,103,118,126, 133,131,67),(7,2)) In [1]: a Out[1]: array([[ 79., nan], [ 87., 77.], [ 92., 133.], [ 99., 121.], [ 103., 118.], [ 126., 133.], [ 131., 67.]]) I would like to create a new column or array which will be a True/False indicator testing the following proposition: a[-1, 0] &lt; a[1:, 0] and a[-1, 1] &gt; a[1:, 1] The result that i expect is the following: False (because the first value of column 1 is nan) False True True False True False I have tried different variations of the solutions described in my previous post, but so far i have been unsuccessful. EDIT: The idea is to test whether 87&lt;92 and at the same time 77>133 which is False. Then 92&lt;99 and 133>121 which is True etc.
tagged with: arrays
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/49071496
downvote count: 0
score: 1
has body: Use operator.methodcaller: def prime(self, key): operator.methodcaller(key, "Good")(self)
upvote count: 1
answers question: http://stackoverflow.com/q/49070653
type: Answer

http://stackoverflow.com/comment/84945630
type: QuestionComment
has text: Not sure exactly what the problem is, but have you tried using the requests library? http://docs.python-requests.org/en/master/ I've had good luck with it
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48970059

http://stackoverflow.com/comment/84990210
comment on: http://stackoverflow.com/a/48992440
has text: you can comment when you are facing challenges.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49022220
favorite count: 0
has comment: http://stackoverflow.com/comment/85049616
has comment: http://stackoverflow.com/comment/85049541
tagged with: python
has answer: http://stackoverflow.com/a/49022386
accepted answer: http://stackoverflow.com/a/49022386
type: AnsweredQuestion
has body: I would like to take an html document and traverse the part of the document with its children. I see lots of examples to get a subtree via xpath or tag name but this doesn't seem to give the children. import lxml from lxml import html, etree html3 = " test page title some text " root = lxml.html.fromstring(html3) tree = etree.ElementTree(root) for el in root.iter(): # do something print(el.text, tree.getpath(el)) This will output None /html None /html/head test /html/head/title None /html/body page title /html/body/h1 some text /html/body/p I would like only page title /html/body/h1 some text /html/body/p Any help gratefully received.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85049611
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49022403
has comment: http://stackoverflow.com/comment/85049559
tagged with: lxml
upvote count: 1
has answer: http://stackoverflow.com/a/49022403
has title: How do I use lxml and python to traverse the of a html document along with its children

http://stackoverflow.com/comment/84943262
has text: Add some prints to each of those functions and observe inputs and outputs to find the source of the problem.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48968242
type: QuestionComment

http://stackoverflow.com/q/48996450
tagged with: python-3.5
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84998341
accepted answer: http://stackoverflow.com/a/48996536
has comment: http://stackoverflow.com/comment/84998554
tagged with: python
tagged with: regex
favorite count: 0
tagged with: parsing
has answer: http://stackoverflow.com/a/48996536
upvote count: 2
has comment: http://stackoverflow.com/comment/84998288
has title: Python regex. Removing all characters after ':' (including at the end of line and except for a specific string)
type: AnsweredQuestion
score: 2
has body: I'm parsing info and layout data from a log file. Say I have some lines that look like this: Book: 190 Checked Out By: ABCD-1234-E5F6, Status: LATE Return: 02.20.2018 I'm trying to remove the info specific to the line like numbers, serial, date, etc. However, say the 'Status: LATE' should stay. I want output like: Book Checked Out By, Status: LATE Return (This example is made up. It makes a little more sense with the actual data and task.) Currently I have: re.sub(':\s.*?(?=[^A-Z\d\-.])','', str) to remove all characters following ': ' that are not a capital letter, a number, and a '.' or a '-' (it stops at anything else like whitespace, a-z, etc). However my output is leaving the last bit in the line and removes the Status. Book Checked Out By, Status: Return: 10.20.2018 How can I specify to remove all capital letters following a ': ' except for the word 'LATE' What is missing that would remove the numbers at the end of a line too?
has comment: http://stackoverflow.com/comment/84998675
type: Question
has comment: http://stackoverflow.com/comment/84998912

http://stackoverflow.com/comment/85733805
comment on: http://stackoverflow.com/q/49118216
score: 0
type: QuestionComment
has text: The messages are broken up into segments and the header points to the start of each segment. The one that contains the relevant data is about 30Kb but yes, I'd have to step through them and read each one until I found the data. If I went the unpacking route, I'd have to read each segment and then generate the format string based on the size of each segment. I've been playing with that route and it feels messy.
type: Comment

http://stackoverflow.com/a/49097858
type: Answer
accepted answer of: http://stackoverflow.com/q/49096512
answers question: http://stackoverflow.com/q/49096512
score: 0
type: AcceptedAnswer
has body: Problem solved. To solve this, we can add UTF-8 notation in the writing process: sh.write(rx, cx, unicode(temp, 'utf-8'))

http://stackoverflow.com/comment/85213188
comment on: http://stackoverflow.com/a/49103181
score: 0
type: AnswerComment
type: Comment
has text: I'm glad you were able to do it. And hopefully learning something in the process :D

http://stackoverflow.com/q/49017818
has title: Slice lists at different indices at the same time in python
has answer: http://stackoverflow.com/a/49018034
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/18272160
has answer: http://stackoverflow.com/a/49018616
has comment: http://stackoverflow.com/comment/85040932
possible better answer: http://stackoverflow.com/a/49018616
accepted answer: http://stackoverflow.com/a/49018034
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85041004
tagged with: python
has comment: http://stackoverflow.com/comment/85041223
downvote count: 1
has comment: http://stackoverflow.com/comment/85041125
type: AnsweredQuestion
has body: How can I check if two lists have same values at specific index, using slice? L1 = ['X00013', 9654123, 4.1, 'No', 'No', 1.83, 3.8, 0.01, 90.01] L2 = ['X00014', 2021230, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 0.00001] I know how to check if L1[3] == L2[3]: print("YES") but I do not know how to check for multiple locations/indices at the same time: I'm looking for something like checking both lists at indices 3,4 and 7 at the same time. I can use operator and itemgetter: itemgetter(3,4,7)(L1) == itemgetter(3,4,7)(L2) but I would like the simple direct solution slicing the lists. Thank you for your help.
score: 1
has comment: http://stackoverflow.com/comment/85041086
has comment: http://stackoverflow.com/comment/85040803
has comment: http://stackoverflow.com/comment/85041067

http://stackoverflow.com/q/49060724
has answer: http://stackoverflow.com/a/49060905
tagged with: python
has answer: http://stackoverflow.com/a/49060939
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49060905
has title: Select "corner" elements of a 2D NumPy array
upvote count: 3
has body: I am trying to extract the four corner elements of a NumPy 2D array: import numpy as np data = np.arange(16).reshape((4, -1)) #array([[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11], # [12, 13, 14, 15]]) The expected output is either [[0,3],[12,15]] or [0,3,12,15] (anything goes). True 2D fancy indexing delivers only the ends of the main diagonal: data[[0,-1],[0,-1]] #array([ 0, 15]) Pseudo-2D fancy indexing (first row-wise, then column-wise) delivers the right answer, but looks awkward: data[[0,-1]][:,[0,-1]] #array([[ 0, 3], # [12, 15]]) Is there a way to use true fancy indexing, such as data[XXX,YYY], where XXX and YYY are lists/arrays/slices, to extract all four corners?
type: Question
linked to: http://stackoverflow.com/q/17937699
tagged with: indexing
score: 3
duplicate of: http://stackoverflow.com/q/17937699
accepted answer: http://stackoverflow.com/a/49060939
tagged with: numpy
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48995422
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49001136
has title: Python 3.5 virtualenv : pip3 installing tensorflow fails
tagged with: tensorflow
type: Question
score: 0
answer count: 1
has body: I am running Mac OS 10.5 (Yosemite) and I just setup a virtualenv with python 3.5 to play a little bit with tensorflow. The virtualenv is setup correctly. However, I cannot install tensorflow. I always get the following error messages: (tensorflow) Tom@MBP:~/tensorflow$ pip3 install --upgrade tensorflow Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow or this error: (tensorflow) Tom@MBP:~/tensorflow$ pip3 install --upgrade \ &gt; https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.5.0-py2-none-any.whl tensorflow-1.5.0-py2-none-any.whl is not a supported wheel on this platform. I actually do not understand what is happening here. Any help is appreciated. Thanks

http://stackoverflow.com/comment/85155004
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49048342
type: Comment
has text: I have the `dbms.connectors.default_listen_address` line commented, but `dbms.connector.bolt.listen_address=0.0.0.0:7687` and `dbms.connector.http.listen_address=0.0.0.0:7474` Doesn't this do the same thing?

http://stackoverflow.com/comment/85134582
has text: Please format as code
comment on: http://stackoverflow.com/q/49064817
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84992520
type: Comment
has text: @ZoltanDeWitt I have updated your answer but still in review process.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48993130

http://stackoverflow.com/q/48998936
favorite count: 0
type: UnansweredQuestion
score: 3
tagged with: nltk
has answer: http://stackoverflow.com/a/48999607
has comment: http://stackoverflow.com/comment/85004976
tagged with: named-entity-recognition
type: Question
answer count: 1
downvote count: 0
has body: I essentially want to use the nltk StanfordNERTagger in order to purify a list of names (eg. there are organizations in there I want to remove) and I stumbled on weird issue. It seems the tag results of one sentence depend on what other sentences are given, which isn't very intuitive. Here is how to reproduce: from nltk.tag import StanfordNERTagger tagger = StanfordNERTagger('/path/to/english.all.3class.distsim.crf.ser.gz','/path/to/stanford-ner-2017-06-09/stanford-ner.jar',encoding='utf-8') things_to_tag = ["Star Trek".split(), "Star Jones".split(), "Star Wars".split()] # tagging using tag_sents print tagger.tag_sents( things_to_tag ) # tagging using tag for t in things_to_tag: print tagger.tag(t) Output: [[(u'Star', u'ORGANIZATION'), (u'Trek', u'ORGANIZATION')], [(u'Star', u'ORGANIZATION'), (u'Jones', u'ORGANIZATION')], [(u'Star', u'ORGANIZATION'), (u'Wars', u'ORGANIZATION')]] [(u'Star', u'O'), (u'Trek', u'O')] [(u'Star', u'PERSON'), (u'Jones', u'PERSON')] [(u'Star', u'O'), (u'Wars', u'O')] I also tried removing Star Wars from the list, and again the results change ('Trek' becomes Person, and 'Star' becomes O). I looked into nltk/tag/stanford.py and it's not really clear why this would happen. I was hoping someone could lend a hand in identifying what the issue might be, or at least confirm I'm not the only one seeing this. nltk version 3.2.5 python version 2.7.13
upvote count: 3
tagged with: python
has title: nltk tag tag_sents give different results

http://stackoverflow.com/q/48971448
type: AnsweredQuestion
has title: PyQt - How to link specific dialog with class
has answer: http://stackoverflow.com/a/48971778
has comment: http://stackoverflow.com/comment/84948085
type: Question
has comment: http://stackoverflow.com/comment/84948149
has comment: http://stackoverflow.com/comment/84948693
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/84948119
score: 0
tagged with: pyqt
answer count: 1
has body: I have created a PyQt MainWindow app and I have also created 2 PyQt dialogs in PyQt designer, then a "calling" .pyw program, problem is that when I try open the different dialogs, it only opens one dialog. how do I explicitly set/link a dialog to a class: import sys from MainApp import * from Dialog1 import * from Dialog2 import * from PyQt4 import Qt, QtGui class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.pushButton1, QtCore.SIGNAL('clicked()'), self.openDialog1) QtCore.QObject.connect(self.ui.pushButton2, QtCore.SIGNAL('clicked()'), self.openDialog2) def openDialog1(self): editDialog = Dialog1() editDialog.exec_() def openDialog2(self): editDialog = Dialog2() editDialog.exec_() class Dialog1(QtGui.QDialog): isEdit = False def __init__(self, studentId=0, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) class Dialog2(QtGui.QDialog): isEdit = False def __init__(self, studentId=0, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Dialog() self.ui.setupUi(self) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_()) Be default it loads Dialog2, If I comment out this line: from Dialog2 import ** Then it loads Dialog1, I want to explicitly set which dialog it loads Github link
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/48971778

http://stackoverflow.com/q/49045348
tagged with: django
tagged with: python
has title: Django dynamic objectlist in for loop
score: 0
has comment: http://stackoverflow.com/comment/85095409
has comment: http://stackoverflow.com/comment/85099916
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85100335
has body: I have a nested for loop in which the inner loop's object list is to filled in by the outerloop Template {% for currency in currencies %} {% for transaction in transactions_{{currency}} %} //content here {% endfor %} {% endfor %} View.py currencies = ['usd', 'inr'] context['currencies'] = currencies for currency in currencies: context['transactions_'+currency] = access.listtransactions(self.request.user.username) What i need is the inner loop to translate as follows {% for currency in currencies %} // {{currency}} iterates to usd {% for transaction in transactions_usd %} currently i am receiving the following error TemplateSyntaxError at /transaction/ Could not parse the remainder: '{{currency}}' from 'transactions_rcv_{{currency}}' Is there anything i missed or alternative function? Any guidance would be appreciated.

http://stackoverflow.com/q/49088927
score: 0
has answer: http://stackoverflow.com/a/49088983
has body: I have to whip up a text editor (spin off of Adventures into Zork) game for my summative project. This is my decision for the first zone. second = True while second: firstLog = input("&gt;") This is where I am having problems, as when I input "Inside" or "In" the script gets terminated. if firstLog = "Inside" or "In" or "Space Ship": print("There is a small " color.Bold + "console " + color.End + "in front of you.") print("You can " + color.Bold + "input " + color.End + "or" + color.Bold + "Exit" + color.End) second = False Also if I enter anything else it terminates as well instead of printing this and restarting the loop. else: "Not valid." second = True
has title: Why isn't my Python 3 code working?
has comment: http://stackoverflow.com/comment/85183373
has comment: http://stackoverflow.com/comment/85183456
linked to: http://stackoverflow.com/q/15112125
accepted answer: http://stackoverflow.com/a/49088983
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85183387
has comment: http://stackoverflow.com/comment/85183305
tagged with: python-3.x
type: Question
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/85183385

http://stackoverflow.com/comment/85195716
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49092491
has text: I have made an edit to the question as per your request :)
score: 0

http://stackoverflow.com/a/48964393
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84937522
downvote count: 0
score: 1
has body: In order for the images field to be populated, the item has to go through the images pipeline. This means the images pipeline has to be used before your checking one. To achieve this, give the images pipeline the higher priority (lower order) in your settings: ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline': 100, 'scraper.pipelines.ImageCheckPipeline': 200, } Also, to avoid KeyError, you will have to rewrite your code like so (checking for the existence of a key, instead of its value): if 'images' not in item: spider.logger.error('Images not found', {'item': item}) raise DropItem
accepted answer of: http://stackoverflow.com/q/48964030
answers question: http://stackoverflow.com/q/48964030
has comment: http://stackoverflow.com/comment/84938022
upvote count: 1

http://stackoverflow.com/a/49090992
downvote count: 0
has comment: http://stackoverflow.com/comment/85187616
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49090986
type: Answer
has body: Is it typo? Command should be sudo easy_install pip

http://stackoverflow.com/q/49092405
favorite count: 0
tagged with: core-foundation
upvote count: 2
tagged with: python
has body: I am writing a Python script that uses the PyObjC bindings for AppKit. The script registers an observer with the shared NSWorkspace's notificationCenter and then calls AppKit.CFRunLoopRun() in order for the notifications to be processed: from __future__ import print_function from AppKit import * import signal shared_workspace = NSWorkspace.sharedWorkspace() def on_did_activate_application(notification): print('on_did_activate_application(notification = %s)' % notification) notification_center = shared_workspace.notificationCenter() did_activate_application_observer = notification_center.addObserverForName_object_queue_usingBlock_( NSWorkspaceDidActivateApplicationNotification, None, None, on_did_activate_application) def handle_interrupt(signum, frame): notification_center.removeObserver_(did_activate_application_observer) CFRunLoopStop(CFRunLoopGetCurrent()) signal.signal(signal.SIGINT, handle_interrupt) CFRunLoopRun() The problem I am experiencing (reproducible with the above MCVE) is that, when I press Ctrl+C on the terminal window running the script, handle_interrupt() is not executed immediately, but rather it executes the next time a NSWorkspaceDidActivateApplicationNotification notification is handled. How do I respond to Ctrl+C / SIGINT just as soon as it occurs?
score: 2
type: AnsweredQuestion
has title: How to register a SIGINT handler that will run as soon as Ctrl+C is pressed?
type: Question
has answer: http://stackoverflow.com/a/49101235
linked to: http://stackoverflow.com/q/11886812
tagged with: runloop
tagged with: signals
linked to: http://stackoverflow.com/q/13377773
downvote count: 0
linked to: http://stackoverflow.com/q/30172428
tagged with: pyobjc
answer count: 1
accepted answer: http://stackoverflow.com/a/49101235

http://stackoverflow.com/a/49059981
downvote count: 0
has comment: http://stackoverflow.com/comment/85126205
accepted answer of: http://stackoverflow.com/q/49059938
upvote count: 8
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/85129448
has comment: http://stackoverflow.com/comment/85126352
has comment: http://stackoverflow.com/comment/85125565
has comment: http://stackoverflow.com/comment/85129465
has body: new_list = [my_list[i:i + 5] for i in xrange(0, len(my_list), 5)] What's happening here is that takes chunks of data from 0 - 5, 5 - 10, etc. to create sub lists
answers question: http://stackoverflow.com/q/49059938
has comment: http://stackoverflow.com/comment/85125487
type: AcceptedAnswer

http://stackoverflow.com/comment/85230848
has text: What have you tried so far? What step are you getting stuck on?
score: 2
comment on: http://stackoverflow.com/q/49112788
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49050769
downvote count: 0
type: Answer
has body: If want use your original solution add fillna with cast to int: testdf = g.join(pd.get_dummies(g['accession'].apply(pd.Series).stack()).sum(level=0)).drop('accession', 1) testdf = testdf.fillna(0).astype(int) But better solution is use get_dummies and then set max per index and per columns (in sample not necessary, in real data maybe): df1['accession'] = df1['gene'].map(df2.set_index('gene')['accession']) df1 = pd.get_dummies(df1.set_index('genome')['accession']).max(level=0).max(level=0, axis=1) Or use crosstab, clip_upper and add missing categories by reindex: df1 = (pd.crosstab(df1['genome'], df1['accession']) .clip_upper(1) .reindex(df1['genome'].unique(), fill_value=0)) Or: df1 = (df1.groupby(['genome', 'accession']) .size() .clip_upper(1) .unstack(fill_value=0) .reindex(df1['genome'].unique(), fill_value=0)) print (df1) accession1 accession2 accession3 accession4 accession5 genome genome1 1 1 1 0 0 genome2 1 0 0 1 1 genome3 0 0 0 0 0 genome4 0 0 0 0 0 and last for write to file: df1.to_csv(outName, sep='\t')
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49050710
answers question: http://stackoverflow.com/q/49050710
score: 2
type: AcceptedAnswer

http://stackoverflow.com/a/49001219
has body: batch size is another param affect training time: higher size will help reduce time each epoch, but will require more epoch to have the same effiency like size=1 And if your network is deep (using CNN, etc), you should run on GPU
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48995577

http://stackoverflow.com/comment/85194597
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49094035
type: QuestionComment
has text: Possible duplicate of [How to select lines between two patterns?](https://stackoverflow.com/questions/38972736/how-to-select-lines-between-two-patterns)

http://stackoverflow.com/comment/84972036
comment on: http://stackoverflow.com/q/48983480
score: 1
type: Comment
type: QuestionComment
has text: The ~ is on the n in both strings in the question source code: https://i.sstatic.net/zoPYO.png. stack overflow just seems to show it wrong ( https://i.sstatic.net/zwSPG.png )

http://stackoverflow.com/comment/85069144
comment on: http://stackoverflow.com/q/49032171
type: QuestionComment
has text: For your code, `{{ post.autor }}` and `{{ post.category }}` should show the string representations of the related user and category. If that's not working, you should explain what you are getting and what you expect.
type: Comment
score: 0

http://stackoverflow.com/a/49060795
has comment: http://stackoverflow.com/comment/85126854
has comment: http://stackoverflow.com/comment/85126983
has comment: http://stackoverflow.com/comment/85126766
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49060645
has comment: http://stackoverflow.com/comment/85127012
has comment: http://stackoverflow.com/comment/85126906
has comment: http://stackoverflow.com/comment/85126783
answers question: http://stackoverflow.com/q/49060645
has comment: http://stackoverflow.com/comment/85126810
type: Answer
has comment: http://stackoverflow.com/comment/85126965
has body: If you are starting with a list-of-lists, you can use plain Python to accomplish this easily and it will be performant. Indeed, you are using numpy with object dtype, so I suspect you are gaining very little in performance using the built-in routines, since you lose data-locality (and are essentially left with the equivalent of crappy Python list objects). Instead, you can accomplish this in linear time (not counting an initial sort of the data, which will be O(n*logN), but it will be using Python's timsort, so it will effectively be very fast), doing only a couple passes on the data: In [1]: data = [[1, 1, 1, 'a', 1], ...: [0, 1, 1, 'b', 1], ...: [0, 3, 1, 'c', 4], ...: [3, 1, 1, 'd', 1], ...: [4, 3, 1, 'e', 4]] ...: In [2]: from operator import itemgetter In [3]: group_key = itemgetter(1,2,4) In [4]: data.sort(key=group_key) Then simply: In [6]: first = itemgetter(0) In [7]: result = [] In [8]: from itertools import groupby ...: for _, g in groupby(data, group_key): ...: result.append(min(g, key=first)) ...: In [9]: result Out[9]: [[0, 1, 1, 'b', 1], [0, 3, 1, 'c', 4]] An alternative approach builds an auxiliarry data-structure using a defaultdict. This is the idiomatic way to group non-sorted data. This might be useful if you want to be able to keep these values grouped: In [10]: from collections import defaultdict In [11]: grouper = defaultdict(list) In [12]: data = [[1, 1, 1, 'a', 1], ...: [0, 1, 1, 'b', 1], ...: [0, 3, 1, 'c', 4], ...: [3, 1, 1, 'd', 1], ...: [4, 3, 1, 'e', 4]] In [13]: for row in data: ...: _,x,y,_, z = row ...: grouper[(x,y,z)].append(row) ...: In [14]: grouper Out[14]: defaultdict(list, {(1, 1, 1): [[1, 1, 1, 'a', 1], [0, 1, 1, 'b', 1], [3, 1, 1, 'd', 1]], (3, 1, 4): [[0, 3, 1, 'c', 4], [4, 3, 1, 'e', 4]]}) In [15]: first = itemgetter(0) In [16]: [min(group, key=first) for group in grouper.values()] Out[16]: [[0, 1, 1, 'b', 1], [0, 3, 1, 'c', 4]]
downvote count: 0
has comment: http://stackoverflow.com/comment/85126798
has comment: http://stackoverflow.com/comment/85127007
has comment: http://stackoverflow.com/comment/85126838
has comment: http://stackoverflow.com/comment/85126729
has comment: http://stackoverflow.com/comment/85126831
has comment: http://stackoverflow.com/comment/85126986
score: 3

http://stackoverflow.com/q/48982092
tagged with: neural-network
tagged with: keras
score: 0
tagged with: linux
answer count: 1
has answer: http://stackoverflow.com/a/48982330
has title: ImportError: No module named yaml in Keras (neural network)
type: UnansweredQuestion
tagged with: python
has body: I have successfully installed Keras API and other requirements for python for using on TensorFlow but when i import it gives the below error. Traceback (most recent call last): File "facenet.py", line 1, in &lt;module&gt; from keras import backend as K File "build/bdist.linux-x86_64/egg/keras/__init__.py", line 3, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/keras/utils/__init__.py", line 25, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/keras/utils/training_utils.py", line 7, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/keras/layers/__init__.py", line 4, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/keras/engine/__init__.py", line 3, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/keras/engine/topology.py", line 10, in &lt;module&gt; ImportError: No module named yaml
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/85066431
type: Comment
comment on: http://stackoverflow.com/q/49030196
has text: @QM_42 Try adding the following in between your `write` and `sleep` commands to see what happens. first `print(s.outwaiting)` and then `s.flushOutput()`
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85214871
comment on: http://stackoverflow.com/a/49081304
score: 0
type: AnswerComment
has text: Thanks for your help and efforts! But here groups means i want to show different groups in the above pictures that i have posted in question.
type: Comment

http://stackoverflow.com/a/48985763
has body: Thank you everyone, I've managed to answer my problem with the use of itertool's groupby Here is my working prototype: from itertools import groupby from operator import itemgetter def merge(data): out_data = [] for key, group in groupby(data, key=itemgetter('name','time')): id_temp = 0 dep_temp=0 dict_temp={} for t in group: dict_temp=t if t["deposit_id"] &lt; id_temp: dict_temp['deposit_id']=id_temp else: id_temp=dict_temp['deposit_id'] dep_temp+=dict_temp['deposit'] dict_temp['deposit'], dict_temp['deposit_id'] = dep_temp, id_temp out_data.append(dict_temp) return out_data a = [{'name':'John','time':1234,'deposit':16.7,'deposit_id':1115}, {'name':'John','time':1234,'deposit':24.3,'deposit_id':1116}, {'name':'John','time':1234,'deposit':65.3,'deposit_id':1117}, {'name':'John','time':1235,'deposit':95.3,'deposit_id':1118}, {'name':'Lisa','time':1235,'deposit':95.3,'deposit_id':1119}] b=merge(a) for t in b: print t Output {'deposit_id': 1117, 'deposit': 106.3, 'name': 'John', 'time': 1234} {'deposit_id': 1118, 'deposit': 95.3, 'name': 'John', 'time': 1235} {'deposit_id': 1119, 'deposit': 95.3, 'name': 'Lisa', 'time': 1235}
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48981651

http://stackoverflow.com/comment/85027511
has text: Welcome to [so]! Unfortunately, this platform is not well-suited to brainstorming, and so these kinds of questions are off-topic. To get an answerable question, you first need to start working on actual code, and keep going until you get stuck. I would recommend running `help("str")` in python, to get more information about what Python supports natively.
score: 0
comment on: http://stackoverflow.com/q/48996879
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49035483
score: 0
has body: os.scandir is useful for stuff like this. def find_my_cousin(me, cousin_name): """Find a file or directory named `cousin_name`. Start searching at `me`, and traverse directly up the file tree until found.""" if not os.path.isdir(me): parent_folder = os.path.dirname(me) else: parent_folder = me folder = None removed = -1 while folder != parent_folder: # Stop if we hit the file system root folder = parent_folder removed += 1 with os.scandir(folder) as ls: for f in ls: if f.name == cousin_name: print( "{} is your cousin, {} times removed, and she lives at {}" "".format(f.name, removed, f.path) ) return f.path parent_folder = os.path.normpath(os.path.join(folder, os.pardir))
answers question: http://stackoverflow.com/q/49034576
type: Answer

http://stackoverflow.com/comment/85123791
has text: My apologies for the quality of the question. I've been frustrated on this for several hours and just needed some assistance. The problem was fixed thanks to kriss, should I delete the thread? Obviously very new to SO
comment on: http://stackoverflow.com/q/49058919
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/84990351
has text: @R4PH43L: AFAIK this has not changed in the last decade or two, and is the same on all platforms. I don't currently have a windows box that I can test on so I can't say definitively that this behavior is the same on modern versions of windows. It would surprise me if it were different.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48992537

http://stackoverflow.com/q/49032297
accepted answer: http://stackoverflow.com/a/49405079
tagged with: python
score: 2
has title: Django: queryable computed fields
upvote count: 2
tagged with: django
tagged with: computed-field
possible better answer: http://stackoverflow.com/a/49032818
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49032818
has answer: http://stackoverflow.com/a/49405079
has body: Is there a "best" way of doing computed fields that can be queried? For example: from django.db import models class Person(models.Model): given_name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) NAME_ORDER_CONVENTION_CHOICES = ( # "Eastern" name order: family name followed by given name ('E', 'Eastern'), # "Western" name order: given name followed by family name ('W', 'Western') ) name_order_convention = models.CharField( length=1, choices=NAME_ORDER_CONVENTION_CHOICES, ) @property def full_name(self): """ Return full name, calculated on the basis of given name, family name and name order convention. """ template = "{} {}" if self.name_order_convention == "W": return template.format(self.given_name, self.family_name) return template.format(self.family_name, self.given_name) This gives you the ability to get the full_name for any Person, but if you want to do a database query based on full name, you would need to write a query with implicit knowledge of how this property is computed. This would seem to be something of a violation of DRY, in that there is no longer any central place where you can change where how the computed field is calculated - you have to change the full_name property, and anywhere that makes a query based on implicit knowledge of how full_name works. The main alternative I can think of is overriding the save() method to update these fields on each update. from django.db import models class Person(models.Model): given_name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) NAME_ORDER_CONVENTION_CHOICES = ( ('E', 'Eastern'), ('W', 'Western') ) name_order_convention = models.CharField( length=1, choices=NAME_ORDER_CONVENTION_CHOICES, ) # Computed fields full_name = models.CharField(max_length=60) def _calculate_full_name(self): template = "{} {}" if self.name_order_convention == "W": self.full_name = template.format(self.given_name, self.family_name) else: self.full_name = template.forma…
tagged with: django-models
type: Question
answer count: 2
downvote count: 0
favorite count: 0
tagged with: computed-properties

http://stackoverflow.com/a/62571868
type: Answer
answers question: http://stackoverflow.com/q/48975337
score: 0
has body: You can also use tf.expand_dims. The documentation says: This operation is useful if you want to add a batch dimension to a single element. For example, if you have a single image of shape [height, width, channels], you can make it a batch of one image with expand_dims(image, 0), which will make the shape [1, height, width, channels].

http://stackoverflow.com/comment/84938311
comment on: http://stackoverflow.com/q/48966289
score: 0
type: Comment
type: QuestionComment
has text: arrays generally contain elements of the same datatype. But, lists, on the other hand, can contain elements of all datatypes.

http://stackoverflow.com/q/49093053
score: 2
downvote count: 0
type: UnansweredQuestion
type: Question
answer count: 4
has title: How to print (join) 2 loops' result
favorite count: 0
tagged with: python-3.x
upvote count: 2
has body: I have 2 loops: The first loop: number = 1234567 number_string = str(number) for ch in number_string: print(ch) This will print: 1 2 3 4 5 6 7 I have another loop which is: totalNum = len(str(abs(number))) for i in range(totalNum, 0, -1): print("* 10^ ",int(i-1)) and I will get * 10^ 6 * 10^ 5 * 10^ 4 * 10^ 3 * 10^ 2 * 10^ 1 * 10^ 0 But how do I join these 2 loops to become the result like this: 1 * 10^ 6 2 * 10^ 5 3 * 10^ 4 4 * 10^ 3 5 * 10^ 2 6 * 10^ 1 7 * 10^ 0 I am new to Python, so I couldn't figure out how to do that.
tagged with: python
has answer: http://stackoverflow.com/a/49093111
has answer: http://stackoverflow.com/a/49093086
has answer: http://stackoverflow.com/a/49093101
has answer: http://stackoverflow.com/a/49093098
tagged with: for-loop

http://stackoverflow.com/q/49004536
has answer: http://stackoverflow.com/a/59072657
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63909434
tagged with: django
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/57647546
tagged with: authentication
has title: Django LDAP email as Username
type: Question
tagged with: ldap
answer count: 3
tagged with: email
downvote count: 0
favorite count: 0
has body: I am trying to login as a LDAP-user with an e-mail adress. I used the following code: settings.py AUTH_LDAP_SERVER_URI = "ldap://192.168.12.123" AUTH_LDAP_BIND_DN = "User" AUTH_LDAP_BIND_PASSWORD = "Password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_ONELEVEL, "(uid=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_E_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, ldap.SCOPE_ONELEVEL, "(mail=%(user)s)") AUTH_LDAP_E_USER_ATTR_MAP = AUTH_LDAP_USER_ATTR_MAP AUTH_LDAP_E_ALWAYS_UPDATE_USER = AUTH_LDAP_ALWAYS_UPDATE_USER AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', #'django.contrib.auth.backends.ModelBackend', 'accounts.backends.LDAPEmailBackend', ) backends.py from django_auth_ldap.backend import LDAPBackend, _LDAPUser class LDAPEmailBackend(LDAPBackend): settings_prefix = "AUTH_LDAP_E_" def get_or_create_user(self, email, ldap_user): model = self.get_user_model() username_field = getattr(model, 'USERNAME_FIELD', 'username') kwargs = { username_field + '__iexact': ldap_user.attrs['uid'][0], 'defaults': { username_field: ldap_user.attrs['uid'][0].lower(), 'email': email } } return model.objects.get_or_create(**kwargs) The console gives me this: search_s('DC=sbvg,DC=ch', 1, '(uid=%(user)s)') returned 0 objects: Authentication failed for ipa@sbvg.ch: failed to map the username to a DN. Caught LDAPError while authenticating ipa@sbvg.ch: SERVER_DOWN({'desc': u"Can't contact LDAP server"},) If you have any idea, do not hesitate to post it.

http://stackoverflow.com/comment/85056100
type: Comment
has text: @ClockSlave Sure, np :)
comment on: http://stackoverflow.com/a/49025690
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85027127
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49010949
has text: There is a subtle distinction here: variables don't have types, *values* do.
type: Comment

http://stackoverflow.com/comment/85451949
type: AnswerComment
comment on: http://stackoverflow.com/a/49223634
type: Comment
has text: In your edited code, you initialize at the beginning with a checkpoint if it exists. Then you train: `while True: ... summary, loss_ = sess.run(...)`. Every iteration in the while loop, your adam optimizer will backpropagate and slightly modify the neural network weights. And if you have `is_training=True` the backprop will consider the decayed means and variances in the batch norm. If you have `is_training=False`, the backprop will consider the normal mean and variance. Again, your code works differently based on the setting of `is_training`.
score: 0

http://stackoverflow.com/comment/85028899
type: Comment
has text: You can only control game objects with c code, not python, but c code could make python do OTHER things. What I suggest is having your python script write it's output to a file, and use c code to read the file and control the game objects
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48978797

http://stackoverflow.com/a/49095419
score: 1
accepted answer of: http://stackoverflow.com/q/49095208
has comment: http://stackoverflow.com/comment/85196306
has comment: http://stackoverflow.com/comment/85196507
answers question: http://stackoverflow.com/q/49095208
type: Answer
has comment: http://stackoverflow.com/comment/85197042
upvote count: 1
has comment: http://stackoverflow.com/comment/85197006
has comment: http://stackoverflow.com/comment/85196846
has comment: http://stackoverflow.com/comment/85195883
has comment: http://stackoverflow.com/comment/85196249
has body: Instead of looking for word in xml and parse it every time I suggest you can map your word and synonym in python dictionary and then you can very easily lookup or manipulate as you desire. I have use beautifulsoup to parse xml below: xml = """<synwords> affection N love . . . <synwords>""" from bs4 import BeautifulSoup soup = BeautifulSoup(xml, "html.parser") # xml is your xml content words = soup.find_all('word') mapped_dict = {word.find("mainword").text: word.find("synonym").text for word in words} print(mapped_dict) Output: {'sweetie': 'love', 'beloved': 'love', 'appreciation': 'love', 'affection': 'love', 'emotion': 'love'}
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85196958
downvote count: 0

http://stackoverflow.com/comment/85047928
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49021098
score: 0
has text: @damores not really... I mentioned that answer as possible solution, but i was looking for something different. I suppose the lazy way out I am asking for is just not possible.

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

http://stackoverflow.com/q/49100472
favorite count: 0
tagged with: python
tagged with: .obj
downvote count: 0
has body: I have written a very straight-forward script that imports many obj files one-by-one and renders them. The imported meshes have ~10k to ~120k vertices. After rendering, I completely remove the imported mesh (along with its data blocks) before importing the next one. However, as the for loop proceeds the importing procedure becomes extremely slow. I noticed that the import function starts behaving in weird ways and it takes a lot of time to import objects. I'm not sure why this is happening. Initially I was thinking memory issues are causing this but I think removing the data blocks should resolve memory leakage. This happens even without doing any rendering or any operations on the imported objects. Here's an instance of what the import function prints while importing a mesh: ( 0.0002 sec | 0.0002 sec) Importing OBJ '/data/e1f2651d55aecd7d8f2b6fca0ec9a39dn7a9/models/model.obj'... ( 0.0308 sec | 0.0306 sec) Parsing OBJ file... ( 1.8534 sec | 1.8511 sec) Done, loading materials and images... ( 2.0450 sec | 2.0426 sec) Done, building geometries (verts:72707 faces:137005 materials: 44 smoothgroups:0) ... ( 5.4944 sec | 5.4921 sec) Done. ( 5.4946 sec | 5.4945 sec) Finished importing: 'data/e1f2651d55aecd7d8f2b6fca0ec9a39dn7a9/models/model.obj' Progress: 100.00% As more objects are imported the import function behaves slower and slower, even for simpler shapes (e.g. ~12k vertices) you will get something like this: ( 0.0002 sec | 0.0002 sec) Importing OBJ '/data/jjgd2e3f46f7cc1e8ba69a5e14689f7b974/models/model.obj'... ( 0.0266 sec | 0.0263 sec) Parsing OBJ file... ( 0.7060 sec | 0.6793 sec) Done, loading materials and images... ( 3.0993 sec | 3.0726 sec) Done, building geometries (verts:12668 faces:43914 materials: 28 smoothgroups:0) ... ( 18.6672 sec | 18.6405 sec) Done. ( 18.6673 sec | 18.6671 sec) Finished importing: '/data/jjgd2e3f46f7cc1e8ba69a5e14689f7b974/models/model.obj' Progress: 100.00% However, if the same object with ~12k vertices is imported first I get somet…
type: AnsweredQuestion
tagged with: blender
tagged with: rendering
score: 1
type: Question
tagged with: 3d
upvote count: 1
has comment: http://stackoverflow.com/comment/98827547
answer count: 1
has answer: http://stackoverflow.com/a/49114854
accepted answer: http://stackoverflow.com/a/49114854
has title: Sequentially importing .obj files becomes drastically slow very quickly

http://stackoverflow.com/comment/85187258
comment on: http://stackoverflow.com/a/49090673
has text: Actually, the answer had all 3 cases grouped together for that question, I wanted individual code for each case. Combining it makes more sense, but as a beginner I'm trying to break it down as much as possible.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49046361
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49046317
answers question: http://stackoverflow.com/q/49046317
score: 4
upvote count: 4
has body: Use: set_index of columns for not reshaping reshape all another columns by stack - NaNs rows are dropped reorder_levels for change final ordering of columns reset_index for columns from MultiIndex remove column by drop rename first column df = (df.set_index(['time','id']) .stack() .reorder_levels([2,0,1]) .reset_index(name='a') .drop('a', 1) .rename(columns={'level_0':'type'})) print (df) type time id 0 A 4.42 1 1 A 4.48 3 2 A 5.45 2 3 B 6.64 2 4 B 7.49 1 5 B 7.72 3 6 C 8.13 1 7 C 8.65 2 8 C 9.07 3

http://stackoverflow.com/comment/84995569
comment on: http://stackoverflow.com/a/48974415
has text: I'd love to hear what is not helpful or wrong about my answer, to deserve a downvote. That way I can improve my answer!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84956553
type: QuestionComment
comment on: http://stackoverflow.com/q/48975805
has text: Possible duplicate of https://stackoverflow.com/questions/11372177/django-template-tag-in-if-block
score: 0
type: Comment

http://stackoverflow.com/a/60998345
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48990067
upvote count: 1
has body: I just added this file to my workspace, you could modify it if you got a scripts directory and take more advantage or the PIPENV_PIPFILE using the [scripts] in pipenv. #!/usr/bin/env bash script_dir=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd) PIPFILE=$script_dir/Pipfile export PIPENV_PIPFILE=$(cd $(dirname $PIPFILE) &amp;&amp; pwd)/$(basename $PIPFILE) pipenv run python $script_dir/generate_avatar.py Then the cronjob is just: * * * * * $FOODIR/run.sh
downvote count: 0

http://stackoverflow.com/comment/85027217
has text: @khelwood Yep, I guess the `if` statement is highly optimised; use cases for `truth` are where you would parse a keyword argument like `key=bool`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49009870

http://stackoverflow.com/a/48977618
downvote count: 0
answers question: http://stackoverflow.com/q/48977527
has comment: http://stackoverflow.com/comment/84961757
has comment: http://stackoverflow.com/comment/84964417
has body: The problem is this, you are first doing cursor.prepare(statement) which according to the docs: This can be used before a call to execute() to define the statement that will be executed. When this is done, the prepare phase will not be performed when the call to execute() is made with None or the same string object as the statement. When you call execute in your code you specifically use None which means your prepared statement won't be used. Just execute your statement within the executemany function call. Also to see errors you can the batcherrors=True flag in your cursor.executemany call so you can follow it with a cursor.getbatcherrors() to retrieve all the errors. This is all straight from the docs.
has comment: http://stackoverflow.com/comment/84961439
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/49099308
type: Question
has answer: http://stackoverflow.com/a/49099402
has title: how to call some logic in my views after rendering template in django
answer count: 1
has body: I am using form.py and the user is typing some Email-id, let us say I want to send an email to that particular email and write all that email into google sheet using gspread, I am able to do this in my views.py, but the problem is it's taking a lot of time to write which slow down the rendering process. Is there any other way I can use my logic after rendering the template.
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-templates
tagged with: django-views
score: 0
tagged with: django-models

http://stackoverflow.com/comment/95053933
has text: That just explains what was the problem in the first place, when you install opencv with pip it brings its own backends (ffmpeg) so I think the problem was that your first opencv backend was broken
score: 0
comment on: http://stackoverflow.com/q/49025795
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49027000
accepted answer: http://stackoverflow.com/a/49027416
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: xpath
score: 0
has title: python xpath : extract only few items from tables
answer count: 1
has answer: http://stackoverflow.com/a/49027416
type: AnsweredQuestion
has body: I want to extract only few items from the html which is a table. &lt;table cellspacing="0" cellpadding="2" width="100%" border="0" class="TableBorderBottom"&gt; &lt;tr&gt; &lt;td class="tblBursaSummHeader"&gt;No.&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Name&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Stock&lt;br&gt;Code&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Rem&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Last&lt;br&gt;Done&lt;/td&gt; &lt;td class="tblBursaSummHeader" width="55"&gt;Chg&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;% Chg&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Vol&lt;br&gt;('00)&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Buy Vol&lt;br&gt;('00)&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Buy&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Sell&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;Sell Vol&lt;br&gt;('00)&lt;/td&gt; &lt;td class="tblBursaSummHeader"&gt;High&lt;/td&gt; &lt;td class="tblBursaSummHeaderRect"&gt;Low&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="tblBursaSEvenRow"&gt;1&lt;/td&gt; &lt;td class="tblBursaSEvenRow"&gt;&lt;a href="/tools.pl?action=factsheet&amp;id=8494WA"&gt;LBI CAPITAL BHD-WARRANT A 08/8&lt;/a&gt; (LBICAP-WA)&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;8494WA&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;s&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;0.160&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;&lt;img src="/images/upArrow.gif" border=0&gt;&amp;nbsp;&lt;span class=tblUp&gt;+0.120&lt;/span&gt;&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;300.0&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;341,238&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;745&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;0.160&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;0.160&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;1,049&lt;/td&gt; &lt;td class="tblBursaSEvenRow Right"&gt;0.185&lt;/td&gt; &lt;td class="tblBursaSEvenRowRight Rig…

http://stackoverflow.com/comment/84983271
type: QuestionComment
score: 1
has text: Possible duplicate of [Python 3 UnicodeDecodeError - How do I debug UnicodeDecodeError?](https://stackoverflow.com/questions/46180610/python-3-unicodedecodeerror-how-do-i-debug-unicodedecodeerror)
comment on: http://stackoverflow.com/q/48989333
type: Comment

http://stackoverflow.com/comment/85198350
comment on: http://stackoverflow.com/a/49094617
type: AnswerComment
score: 0
type: Comment
has text: `AttributeError: __enter__`

http://stackoverflow.com/comment/85171130
has text: it's not mine..
score: 0
comment on: http://stackoverflow.com/q/49082945
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85133460
has text: Thank you @MohamedThasinah . Put your comment in the answer section so that I can mark your answer as the correct answer.
comment on: http://stackoverflow.com/q/49064086
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49041841
tagged with: python
has comment: http://stackoverflow.com/comment/85088964
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85088947
accepted answer: http://stackoverflow.com/a/49041921
tagged with: functools
tagged with: function
has title: How to set function properties/attributes from within the function definition?
answer count: 1
downvote count: 0
favorite count: 0
has body: How to set function properties/attributes from within the function definition? For example is there a way to achieve this from within the function definition: def test(): pass test.order = 1 So something along the lines of: def test(): self.order = 1 pass print(test.order)
has answer: http://stackoverflow.com/a/49041921

web-crawler
tags question: http://stackoverflow.com/q/48976680
tags question: http://stackoverflow.com/q/49120376
tag name: web-crawler
tags question: http://stackoverflow.com/q/49005519
tags question: http://stackoverflow.com/q/49041589
tags question: http://stackoverflow.com/q/48970724
tags question: http://stackoverflow.com/q/49074805
type: Tag
tags question: http://stackoverflow.com/q/49050556
tags question: http://stackoverflow.com/q/49107734
tags question: http://stackoverflow.com/q/49064332

http://stackoverflow.com/comment/85035587
comment on: http://stackoverflow.com/a/49015266
type: Comment
has text: Glad to hear it!
score: 0
type: AnswerComment

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

http://stackoverflow.com/comment/85102899
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49048965
type: Comment
has text: I see, I did not think to use read_htlm but it will not work to collect only the user data and the given note ?

http://stackoverflow.com/q/49057171
has title: 'User' object has no attribute 'is_valid' Django
has comment: http://stackoverflow.com/comment/85119444
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85119136
has comment: http://stackoverflow.com/comment/85119349
upvote count: 3
has comment: http://stackoverflow.com/comment/85119123
has answer: http://stackoverflow.com/a/49057432
type: Question
has body: I am making a registration form for users to signup using Django 1.8 and python 3.5 I have created a User(Extending User Model Using a Custom Model Extending AbstractUser)(ie I wanted to add custom fields to the default django's Users table like bio, date of birth etc) This is my mainpage/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) this is signup/view.py from django.shortcuts import render from mainpage.models import User def signup(request): form1=User(request.POST or None) if form1.is_valid(): form1.save() context = { "form1": form1, } return render(request, "signup.html",context) Traceback Environment: Request Method: GET Request URL: http://localhost:8000/signup/ Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'currency', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\signup\views.py" …
has comment: http://stackoverflow.com/comment/85119980
accepted answer: http://stackoverflow.com/a/49057432
has comment: http://stackoverflow.com/comment/85119402
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85119951
tagged with: django
tagged with: python

http://stackoverflow.com/q/49074363
type: Question
has title: Plotting a graph of iterations in Python?
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85155149
score: 0
upvote count: 1
downvote count: 1
has body: I've written the following piece of code using the Euler method to plot a graph of velocity against time for a free-falling object, which eventually reaches terminal velocity: import numpy as np import matplotlib.pyplot as plt g = -9.81 Cd = 0.47 p0 = 1.2 A = 0.0034 k = (Cd*p0*A)/2 m = 0.058 def euler(vyn, yn): #takes the starting velocity and height as arguments i = 0 while i &lt; 10000: dt = 0.01 i += 1 vyn = vyn - dt * (g + ((k/m) * abs(vyn) * vyn)) yn = yn - dt * vyn print(vyn, yn) if yn &lt; 0: #stops iterations when ball hits ground break return vyn NumPoints = 2000 xmin = 0 xmax = 1000 dx = (xmax - xmin) / (NumPoints - 1) xvals = [0.0] * NumPoints yvals = np.zeros(NumPoints) for i in range(NumPoints): xvals[i] = xmin + i * dx yvals[i] = euler(0,1000) plt.plot(xvals,yvals) plt.show() I put the print statement in the while loop by the way so that it prints the velocity and height of object from the ground each iteration, and the break is so that it breaks out of the loop by the time the ball hits the ground. However, when I add the graphing code at the bottom, the iterations loop back round for some reason, without breaking. A graph is also not printed. Removing the print statement does produce a graph, however it is just a horizontal line. How could I modify the code to produce a graph of velocity against time, and also height against time? Do I need to embed the graph code within the while loop? Thanks
tagged with: numpy
tagged with: graph
has comment: http://stackoverflow.com/comment/85154967
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85155108

http://stackoverflow.com/a/49045202
type: AcceptedAnswer
downvote count: 0
has body: You can pass df.cat_var_1+ "_" + df.cat_var_2 to argument y of StratifiedShuffleSplit.split(): But here is a method that use DataFrame.groupby: import pandas as pd import numpy as np nrows = 10000 p1 = {'Orange': 0.6, 'Banana': 0.4} p2 = {'Monkey': 0.2, 'Cat': 0.7, 'Dog': 0.1} c1 = [key for key, val in p1.items() for i in range(int(nrows * val))] c2 = [key for key, val in p2.items() for i in range(int(nrows * val))] random.shuffle(c1) random.shuffle(c2) df = pd.DataFrame({"c1":c1, "c2":c2, "val":np.random.randint(0, 100, nrows)}) index = [] for key, idx in df.groupby(["c1", "c2"]).groups.items(): arr = idx.values.copy() np.random.shuffle(arr) p1 = int(0.6 * len(arr)) p2 = int(0.8 * len(arr)) index.append(np.split(arr, [p1, p2])) idx_train, idx_test, idx_validate = list(map(np.concatenate, zip(*index)))
type: Answer
score: 14
upvote count: 14
answers question: http://stackoverflow.com/q/48988182
accepted answer of: http://stackoverflow.com/q/48988182

http://stackoverflow.com/q/49087200
favorite count: 0
has body: a = '{a=[],b=[],c=[ab=cd,ef=gh],d=[ij=kl],e=[]}' How can I extract characters between parenthesis [ ] from above string that are after =. Output expected is: 'cd','gh','kl'
upvote count: 2
tagged with: python
type: AnsweredQuestion
type: Question
downvote count: 4
tagged with: jython
score: -2
has title: extract characters between parenthesis with conditions
has comment: http://stackoverflow.com/comment/85179874
answer count: 1
has answer: http://stackoverflow.com/a/49087329
accepted answer: http://stackoverflow.com/a/49087329

http://stackoverflow.com/a/49035229
upvote count: 0
type: AcceptedAnswer
type: Answer
has body: When you are in the anaconda environment you can use pip install &lt;library&gt; to install libraries, you can search for them with pip search &lt;library&gt;. When they are installed with pip you can import &lt;library&gt; them like usual.
accepted answer of: http://stackoverflow.com/q/49035177
downvote count: 1
answers question: http://stackoverflow.com/q/49035177
score: -1

http://stackoverflow.com/a/48995417
has body: You're looking for "shift" in pandas. df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),columns=['a', 'b', 'c', 'd', 'e']) df.shift(1) will give you all the rows shifted down by one. Then you just need something like: df- df.shift(1) Good luck!
answers question: http://stackoverflow.com/q/48995329
upvote count: 1
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84996338
has comment: http://stackoverflow.com/comment/84996499
has comment: http://stackoverflow.com/comment/84996269

http://stackoverflow.com/comment/85285730
type: Comment
has text: I ran into the same errors with my browser's cache. Are you storing static files on AWS S3 by any chance?
comment on: http://stackoverflow.com/q/49088302
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85074907
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49031084
has text: I am not sure much about how c# works. But I surely know how object oriented programming works. I suggest you to understand it in Object way and then write it in Python way.

http://stackoverflow.com/q/48976701
type: Question
has comment: http://stackoverflow.com/comment/84959452
upvote count: 2
linked to: http://stackoverflow.com/q/1732348
accepted answer: http://stackoverflow.com/a/48977505
answer count: 2
has comment: http://stackoverflow.com/comment/84960368
has body: I am new to python and trying to modify some xml configuration files which are present in my local system. Input: I have an xml file(say Test.xml) with the following content. <?xml version="1.0" encoding="UTF-8" standalone="no"?> 500 5000 true WHAT I WANT TO ACHIEVE: I want to achieve below 2 things: Part 1: I want to modify value of SocketTimeout tag(only under composer tag) to 60 and also want to add a comment like this (foe e.g. Changed this value to reduce SocketTimeout). Hence the file Test.xml should be as below: <?xml version="1.0" encoding="UTF-8" standalone="no"?> 500 60 true Part 2: In the file Test.xml, I want to add a new tag under Domain tag as below: <?xml version="1.0" encoding="UTF-8" standalone="no"?> 500 60 true <New_tag> true </New_tag> That’s all I want :) WHAT I HAVE TRIED: To achieve this task I considered below optons: Minidom/ElementTree/lxml removes comments in the file and also changes the formatting of the file. Regex: Doesn’t removes comments, also doesn’t disturb formatting. Hence, I opted for regex and below is what I started with, but is not working :( import os, re # set the working directory os.chdir('C:\\Users\\Dell\\Desktop\\') # open the source file and read it fh = open('C:\\Users\\Dell\\Desktop\\Test.xml', 'r') subject = fh.read() fh.close() pattern = re.compile(r"\[ \].*?\[/ \]") #Replace result = pattern.sub(lambda match: match.group(0).replace(' 500 ',' 60 ') ,subject) # write the file f_out = open('C:\\Users\\Dell\\Desktop\\Test.xml', 'w') f_out.write(result) f_out.close() Any idea in implementing what I want or rectification in mistakes would be highly appreciable. Although I am new to python but will try my best to work on the suggestions.
has title: Editing local XML file using Python and Regular expression
tagged with: elementtree
possible better answer: http://stackoverflow.com/a/48978545
favorite count: 0
has answer: http://stackoverflow.com/a/48977505
has comment: http://stackoverflow.com/comment/84958543
tagged with: lxml
tagged with: python
tagged with: regex
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/84958874
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48978545

http://stackoverflow.com/q/49097306
tagged with: tarfile
has comment: http://stackoverflow.com/comment/85214739
score: 3
tagged with: python
favorite count: 0
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/113733798
type: Question
has body: I'm using Python's tarfile module to extract a .tar.gz file. The problem is that for every file foo.bar in my archive, an additional file ._foo.bar is also created, and I can't figure out why. my code looks like that: import tarfile tar_ref = tarfile.open('file.tar.gz', 'r:gz') tar_ref.extractall('directory') tar_ref.close() and for the following archive: file.tar.gz |-file1 |-file2 |-directory |-file3 I get the following file structure: directory |-file1 |-._file1 |-file2 |-._file2 |-directory |-file3 |-._file3 |-._directory What am i doing wrong?
has title: python's tarfile.extractall creates superfluous files
has comment: http://stackoverflow.com/comment/85199920
downvote count: 0

http://stackoverflow.com/comment/84948116
comment on: http://stackoverflow.com/q/48971454
type: Comment
type: QuestionComment
score: 1
has text: the function .index(a) finds the first value in the array that is equal to a, so if the values in the array are not unique it will not work

http://stackoverflow.com/a/49113748
has comment: http://stackoverflow.com/comment/85246870
has comment: http://stackoverflow.com/comment/85246886
has comment: http://stackoverflow.com/comment/85255115
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/49113507
has comment: http://stackoverflow.com/comment/85254654
answers question: http://stackoverflow.com/q/49113507
has comment: http://stackoverflow.com/comment/85254619
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85248930
has comment: http://stackoverflow.com/comment/85246900
has comment: http://stackoverflow.com/comment/85248943
type: Answer
has body: You can also try numpy's reshape method performed on pd.Series.values. s = pd.Series(np.arange(720)) df = pd.DataFrame(s.values.reshape((30,24)).T) Or split (specify how many arrays you want to split into), df = pd.DataFrame({"day" + str(i): v for i, v in enumerate(np.split(s.values, 30))})

http://stackoverflow.com/q/49033714
has body: I am newbie in AWS Arena. This is my 2nd question regarding AWS Lambda function and AWS LEX. I want to write a lambda function to trigger 2 different intents based on the value of something without any user Utterance. For example if a >= 90.....Intent-1 will work and say "Messi is the best Footballer" and if a &lt; 90......Intent-2 will work and say "Ronaldo is the best Footballer"
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49043343
tagged with: amazon-lex
type: Question
downvote count: 2
has comment: http://stackoverflow.com/comment/85087918
answer count: 1
tagged with: javascript
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
upvote count: 3
tagged with: python
has title: Write a conditional AWS Lambda Function for AWS LEX
has comment: http://stackoverflow.com/comment/85099151
linked to: http://stackoverflow.com/q/47938140
accepted answer: http://stackoverflow.com/a/49043343
has comment: http://stackoverflow.com/comment/85073160
score: 1

http://stackoverflow.com/a/48998085
has comment: http://stackoverflow.com/comment/85001824
downvote count: 0
has comment: http://stackoverflow.com/comment/85001690
has comment: http://stackoverflow.com/comment/85001878
has comment: http://stackoverflow.com/comment/85001714
type: Answer
has body: As you said, you have to switch your mindset to use functional programming. One of the key concepts of functional programming is lazy evaluation, which is the default policy in languages such as Haskell. The purpose of this policy is to save both time and memory, by calculating something only when it is needed. In that sense Python generators are also close to the functional paradigm. If you want to execute it as soon as possible, you shouldn't write it in a functional style and fix it with list() if you don't care about the results. Using a loop is totally ok.
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48997871

http://stackoverflow.com/comment/84992917
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48993568
has text: What results did you get when you tried timing these? (Hint: take a look at the %timeit magic command in IPython.) I'd suggest doing some timings and coming back with a more specific question (e.g.: "Why is `x**2` 30 times faster than `np.power(x, 2)` for a 1d array `x` of 1 million floats?", the answer to which is non-obvious).

http://stackoverflow.com/a/48964455
has comment: http://stackoverflow.com/comment/84938775
has comment: http://stackoverflow.com/comment/84935104
has comment: http://stackoverflow.com/comment/84939081
has comment: http://stackoverflow.com/comment/84938186
type: Answer
has comment: http://stackoverflow.com/comment/84938654
has comment: http://stackoverflow.com/comment/84935279
has comment: http://stackoverflow.com/comment/84935430
has comment: http://stackoverflow.com/comment/84938092
has body: Geo Lat: Long: Button On your Flask Server you get the data here: @app.route('/receiver', methods=['GET', 'POST']) def worker(): data= request.data print(data)
has comment: http://stackoverflow.com/comment/84939148
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84938925
has comment: http://stackoverflow.com/comment/84937464
has comment: http://stackoverflow.com/comment/84939108
has comment: http://stackoverflow.com/comment/84937884
has comment: http://stackoverflow.com/comment/84935353
has comment: http://stackoverflow.com/comment/84959056
has comment: http://stackoverflow.com/comment/84938001
has comment: http://stackoverflow.com/comment/84938879
score: 0
answers question: http://stackoverflow.com/q/48964373
has comment: http://stackoverflow.com/comment/84937208
has comment: http://stackoverflow.com/comment/84937964
has comment: http://stackoverflow.com/comment/84940911

http://stackoverflow.com/comment/85231828
comment on: http://stackoverflow.com/q/49113254
has text: @ piRSquared Correct. `Time` is not going to be unique. btw I changed the index to `timestamp` to be less confusing. I've updated the question to show what I'm looking for.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49110344
type: Question
score: 0
answer count: 1
tagged with: python-docx
has title: How to extract text from a table in a .docx file?
tagged with: python
accepted answer: http://stackoverflow.com/a/49513617
has body: I want to extract the text from a table that is in a .docx files using python for further analysis. Im using the following code: document = Document(path_to_your_docx) tables = document.tables for table in tables: for row in table.rows: for cell in row.cells: for paragraph in cell.paragraphs: print(paragraph.text) But it seems there is another "table" in the cell of this table, so I'm not able to extract this part (shown in the attached image). When I use the code above, I can't fetch the "Yes/No" text. I have tried also to iterate through the cells as if in a table, but I get the error that the cell doesn't have table attribute. Any advice? The table looks like this code behind table creation Thanks.
tagged with: http://stackoverflow.com/tag/docx
has answer: http://stackoverflow.com/a/49513617
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85225859

http://stackoverflow.com/comment/85238416
type: Comment
has text: Ok so just add your this code to mainpage/admin.py that is all ?
type: AnswerComment
comment on: http://stackoverflow.com/a/49116467
score: 0

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

http://stackoverflow.com/q/48996148
has body: I sadly cannot find anything on how the "scipy.ndimage.measurements.label" algorithm works but need to know that for my thesis that I have to hand in way too soon. Is there anyone who can help me out here? Here the scipy link: https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.label.html and also from the github page where the source links to, I cannot find anything about it. I could also not find anythin in the more extensive scipy docs (chapter 1.14.7 Segmentation and labeling): https://docs.scipy.org/doc/scipy-0.16.0/scipy-ref-0.16.0.pdf Any ideas what algorithm is implemented here? It would mean a lot to me if anyone could help! Cheers!
tagged with: python
score: 2
downvote count: 0
answer count: 0
tagged with: image-processing
tagged with: scipy
type: Question
tagged with: numpy
tagged with: labeling
has title: Algorithm behind scipy.ndimage.measurements.label
upvote count: 2
has comment: http://stackoverflow.com/comment/85075305
has comment: http://stackoverflow.com/comment/84998071
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84998046

http://stackoverflow.com/comment/85159065
score: 0
comment on: http://stackoverflow.com/q/49076566
type: Comment
type: QuestionComment
has text: @liliscent Not sure what that is, but I added an example of exactly what I want.

http://stackoverflow.com/q/49019238
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85044831
tagged with: multithreading
upvote count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/85043824
type: Question
tagged with: conditional-statements
tagged with: if-statement
has answer: http://stackoverflow.com/a/49019434
linked to: http://stackoverflow.com/q/20939299
has body: I was wondering if it would be feasible to use the idea of multi-threading to perform information sharing between a light intensity sensor and a motion sensor. I'm working on a project to automate lighting quality in a room environment. (I'm a beginner at programming and would appreciate any feedback!) The way I'm starting is just to test out code with simple numerical conditions and print statements for now. Below is the simulated code for the project. x=1 #set simply to say some is enters room def MotionSenseLeave(x): x=0 if x==0: print("3. Someone left") #Wait for someone to leave by checking condition LightSense() else: x==0 return x def LightSense(): #Turn on lights if x==1: #and light quality is above/below a value# print("2. Adjust Light") #Measure Light Quality MotionSenseLeave(x) elif x==0: print("Stop operation, the person left") MotionSenseEnter(x) elif x==1: #and light is close to value print("Light quality sufficent, no changes needed") MotionSenseLeave(x) def MotionSenseEnter(x): while x!=1: if x==1: print("1. Someone here") #Wait for someone to come in LightSense() else: x==0 return x MotionSenseEnter(x) #begin operation Basically, the operation begins with MotionSenseEnter() and waits for the condition of entry or x=1 (in this case I just set it to 1 in the beginning). If someone enters, then go to LightSense(), turn on lights, then the cases begin and after each case I run the MotionSenseEnter() or MotionSenseLeave() function to see if that person enters/leaves to shut on/off the system and restart it from the beginning until entry is detected. I was wondering if it would be more efficient to multi-thread these processes instead. If it is, I think I would have to first check to see if someone entered the room, then multi-thread the leave condition and light monitoring condition to continue the operation or close it and await for entry again. If anyone has any opinion on this, all feedback would be welcomed. Again, I'm a beginner at programming, I ap…
has comment: http://stackoverflow.com/comment/85043847
answer count: 1
downvote count: 0
has title: Python: Multi-threading or Loops?
score: 1
favorite count: 0

http://stackoverflow.com/comment/86869277
comment on: http://stackoverflow.com/a/49055076
has text: Yes: you should be able to delete components with either `del` or `block.del_component()`. You will want to be careful with indexed constraints, as deleting the component removes *all* the constraints. If you only want to remove one you can do something akin to `block.c[i] = Constraint.Skip` (but that only works on very recent versions of Pyomo). Instead of deactivating NL constraints, when I do things like this, I frequently clone the entire model instead of doing everything in place, e.g. the GDP cutting planes https://github.com/Pyomo/pyomo/blob/master/pyomo/gdp/plugins/cuttingplane.py
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/84958761
type: QuestionComment
has text: I am doing the project creation, and the adding of the environment, in Visual Studio. It seems that visual studio activates the virtual environment upon creation. Just to make sure I went thru the steps again and activated the environment at the command prompt and within the environment ran the pip command again. The result did not change. I am updating the question to reflect this.
comment on: http://stackoverflow.com/q/48976670
score: 0
type: Comment

http://stackoverflow.com/comment/84947053
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48970830
has text: Good Point @avigil - just kept that for the articulation! Anyway, modified ans!

http://stackoverflow.com/comment/85110382
score: 0
has text: @RameshMaharjan added some edits for clarification
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49051910

http://stackoverflow.com/a/49007410
has comment: http://stackoverflow.com/comment/85028577
has body: Almost ANY website can be scraped but some websites are trickier than others. Instead of Scrapy, I would recommend using a better alternative called Selenium which happens to have a library for python as well. Long story made short: You will start a web browser in form of a driver and navigate to the page of your choice and simulate user interactions such as clicking, entering data in forms and submission. You will also be able to run JavaScript functions. You might also want to do some research on legal constraints to ensure your operation is not unlawful. For instance, refer to case law of Ryanair Ltd v PR Aviation BV (Case C-30/14 CJEU).
accepted answer of: http://stackoverflow.com/q/49007301
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85028654
downvote count: 0
has comment: http://stackoverflow.com/comment/85031143
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49007301

http://stackoverflow.com/a/49010717
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49010538
has body: Try this: value_to_find = '3FrWvdxBkrEJKA57UtCvXYxoXrFER53FE' for dic in vd['outputs']: if dic['account'] == value_to_find: print('Value =', dic['value']) Output: Value = 13155

http://stackoverflow.com/a/49014273
answers question: http://stackoverflow.com/q/49013846
has comment: http://stackoverflow.com/comment/85235347
has comment: http://stackoverflow.com/comment/85148635
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85201578
has body: Why are you iterating over mem?, it's an object with all the info you may need. You just need to do something like: import psutil def get_memory_info(): mem = psutil.virtual_memory() def bytes_to_gb(amount): return round(amount / 1e+9, 2) data = {"total": bytes_to_gb(mem.total), "used": bytes_to_gb(mem.used), "available": bytes_to_gb(mem.available), "percent": mem.percent # Add here whatever data you need } return data print(get_memory_info())
has comment: http://stackoverflow.com/comment/85072797
type: Answer
has comment: http://stackoverflow.com/comment/85073231
accepted answer of: http://stackoverflow.com/q/49013846
has comment: http://stackoverflow.com/comment/85122716

http://stackoverflow.com/q/49077264
tagged with: python
has comment: http://stackoverflow.com/comment/85160821
has title: in range() statement doesnt work
has body: `So I am just making something to test if I can make certain outputs based on inputs Each time I try to enter an answer, nothing happens here I used if elif statements with the in range() in them. Nothing shows up when I type the answer from random import randint from termcolor import colored repeat = True from termcolor import colored import time import sys import multiprocessing print colored("Hello, this is a program to help you practice algebraic expressions.","magenta") print("") time.sleep(4) print colored("Alright let's start with something very basic...\nWhat is x if 2x = 32?","magenta") prob = int(raw_input()) if int(prob) in range (16, 16): print colored("Well done, you got the warmup correct","yellow") elif int(prob) in range(1, 15): print colored("Incorrect answer try again","red")
upvote count: 0
has comment: http://stackoverflow.com/comment/85160579
has comment: http://stackoverflow.com/comment/85160525
type: Question
has comment: http://stackoverflow.com/comment/85160410
answer count: 2
tagged with: if-statement
has comment: http://stackoverflow.com/comment/85160918
downvote count: 6
has comment: http://stackoverflow.com/comment/85161215
has answer: http://stackoverflow.com/a/49077591
has comment: http://stackoverflow.com/comment/85160836
score: -6
favorite count: 0
has answer: http://stackoverflow.com/a/49077529
type: UnansweredQuestion

http://stackoverflow.com/a/49051639
has body: Just do some debug to understand what is myEmailInfo: it could be a tuple (as it is printed like one) or an object with a string representation being a tuple (i.e. method __str__ returns a tuple). To help you perform debug, I personally recommend some software like: PyCharm (https://www.jetbrains.com/pycharm), which has a free "Community Edition" Visual Code (https://code.visualstudio.com) which is a free tool from Microsoft with a great community and amazing support of Python They both include some easy-to-use debuggers and amazing code completion for Python. That does not answer the question (because we cannot without knowing more about your code), but that will help find the issue.
type: Answer
accepted answer of: http://stackoverflow.com/q/49050858
has comment: http://stackoverflow.com/comment/86132127
answers question: http://stackoverflow.com/q/49050858
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85003855
score: 0
type: Comment
has text: The target machine will not have Python which is mostly why I'm using cxFreeze, to simplify things. Will this still work? I would need to pass a parameter to the exe right? I didn't think of the bat file, way better than a shortcut.
comment on: http://stackoverflow.com/a/48998679
type: AnswerComment

http://stackoverflow.com/q/48985722
score: 1
upvote count: 1
tagged with: imaplib
type: AnsweredQuestion
has body: I am currently working on a project in Python that would be connecting to an email server and looking at the latest email to tell the user if there is an attachment or a link embedded in the email. I have the former working but not the latter. I may be having troubles with the if any() part of my script. As it seems to half work when I test. Although it may be due to how the email string is printed out? Here is my code for connecting to gmail and then looking for the link. import imaplib import email word = ["http://", "https://", "www.", ".com", ".co.uk"] #list of strings to search for in email body #connection to the email server mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('email@gmail.com', 'password') mail.list() # Out: list of "folders" aka labels in gmail. mail.select("Inbox", readonly=True) # connect to inbox. result, data = mail.uid('search', None, "ALL") # search and return uids instead ids = data[0] # data is a list. id_list = ids.split() # ids is a space separated string latest_email_uid = data[0].split()[-1] result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') # fetch the email headers and body (RFC822) for the given ID raw_email = data[0][1] # here's the body, which is raw headers and html and body of the whole email # including headers and alternate payloads print "---------------------------------------------------------" print "Are there links in the email?" print "---------------------------------------------------------" msg = email.message_from_string(raw_email) for part in msg.walk(): # each part is a either non-multipart, or another multipart message # that contains further parts... Message is organized like a tree if part.get_content_type() == 'text/plain': plain_text = part.get_payload() print plain_text # prints the raw text if any(word in plain_text for word in word): print '****' print 'found link in email body' print '****' else: print '****' print 'no link in email body' print '****' So basically as you can see I have …
type: Question
has answer: http://stackoverflow.com/a/48986582
has comment: http://stackoverflow.com/comment/84976152
has comment: http://stackoverflow.com/comment/84976281
has title: Finding links in an emails body with Python
answer count: 1
tagged with: email
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48986582
tagged with: parsing

http://stackoverflow.com/q/49096810
downvote count: 0
has answer: http://stackoverflow.com/a/49097223
has title: How to try run django server
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85198688
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85198810
has comment: http://stackoverflow.com/comment/85198765
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85198645
accepted answer: http://stackoverflow.com/a/49097223
type: Question
has body: I am trying to write test that will test if django app is runnable. I just want to try run django server and if everything is ok return code 0 otherwise another code. python manage.py runserver This command run infinite loop and I need to stop it by CTRL + C. And that is the problem. I would like to run it just for few second. Note: I am runnig django on linux.
answer count: 2
possible better answer: http://stackoverflow.com/a/49096881
has answer: http://stackoverflow.com/a/49096881

http://stackoverflow.com/comment/84961317
type: Comment
type: AnswerComment
has text: I simulate it, there are duplicated datetimes. Please give me some time.
score: 0
comment on: http://stackoverflow.com/a/48977949

http://stackoverflow.com/comment/85215484
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49105159
type: QuestionComment
has text: sorry the error i'm receiving is AttributeError: 'list' object has no attribute 'split'. I also tried the above solution but still the same error. I have edited the original post to reflect the above

http://stackoverflow.com/q/49024296
answer count: 2
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85053402
tagged with: beautifulsoup
has title: Python - assign print output csv
has answer: http://stackoverflow.com/a/49024849
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
linked to: http://stackoverflow.com/q/37289951
has comment: http://stackoverflow.com/comment/85053377
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49024746
has body: I am working on a project to scrape multiple twitter URL's and assign their follower count to a csv: username= ['LazadaPH','ZALORAPH','ShopeePH','eBayPhilippines','beauty_MNL'] for user in username: url = 'https://www.twitter.com/'+ user r = requests.get(url) soup = BeautifulSoup(r.content,'lxml') f = soup.find('li', class_="ProfileNav-item--followers") title = f.find('a')['title'] num_followers = int(title.split(' ')[0].replace(',','')) print(user,num_followers) The output looks as follows: LazadaPH 52841 ZALORAPH 29786 ShopeePH 7004 eBayPhilippines 874 beauty_MNL 2469 Since I'm quite new to python (and don't hope to be asking a redundant question): but can someone guide me to sources and tutorials of how to assign this printed output to a csv and essentialy extract it into two columns (column 1 is website string and column 2 the follower count). Any suggestions? Thanks a bunch!
tagged with: screen-scraping
downvote count: 2
score: -2
tagged with: twitter
type: Question

http://stackoverflow.com/a/49118151
has comment: http://stackoverflow.com/comment/85241968
has comment: http://stackoverflow.com/comment/85243625
score: 0
has body: Is it too expensive to create for each time-step a new process...? Yes, this is always expensive and often very expensive. Persistent processes, that do not make you pay the constant overhead costs per each of the time-slice processing, are a more promising option here, but many additional factors have to be also taken into account first. All process-instantiation/termination overhead-costs are the more expensive, the less mathematically dense/complex is the task to calculate. So if your processing is cheap in [TIME]-domain, all the overhead costs will look the more expensive ( as your processing will have to spend them many times in the row ... ) All process-instatiations will also pay remarkable overhead-costs for memory (re-)allocations for data in [SPACE]-domain ( whereas having a feasible semi-persistent data-structures, that persistent processes can work with, an in-place matrix operators may save you a lot on memory-allocation overhead-avoidance ... very important topic on large scale matrices like in numerical mathematics processing for FEM, ANN, Video/image-kernel applications etc. ) Do not rely just on one's gut feelings. Review all details of this logic in the re-formulated Amdahl's Law to have all the quantitative figures before deciding on this design dilemma. Benchmark each of the processing stages, including the process-instantiations, including memory-transfer costs ( in parameters ), including processing costs of the computing phase of the processing "inside" the one step forward computations, including the costs of re-distribution of results among all involved counterparties. Only next you will be able to quantitatively decide a break-even point, after which more processes will not improve the processing ( will stop lowering the overall duration and will start add more overhead costs than the parallel-process accelerated computing may manage to cover ). Is it better to have the process running for the whole time? This may help a lot, once avoiding …
type: Answer
answers question: http://stackoverflow.com/q/49117826
has comment: http://stackoverflow.com/comment/85242819
has comment: http://stackoverflow.com/comment/85242489

http://stackoverflow.com/q/49093272
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49093767
has title: Python - modify to optimal number of ticks on resize event
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49093767
type: AnsweredQuestion
tagged with: matplotlib
type: Question
answer count: 1
has body: Matplotlib computes on first creation of a plot an optimal number of ticks and labels, so that the label strings do not overdraw another tick label. Is it possible to optimally modify this number of ticks on a resize event? If the figure size is increased then there may be an opportunity to have more ticks and labels. If the figure size is decreased then the number of ticks should be decreased whenever they overdraw other labels.
score: 0

http://stackoverflow.com/a/49108371
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49107547
type: Answer
has body: An alternative using the newer regex module could be: (?:\G(?!\A)|\[)([^][,]+)(?:,\s*)? Broken down, this says: (?:\G(?!\A)|\[) # match either [ or at the end of the last match ([^][,]+) # capture anything not [ or ] or , (?:,\s*)? # followed by , and whitespaces, eventually See a demo on regex101.com. In Python: import regex as re string = '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}' rx = re.compile(r'(?:\G(?!\A)|\[)([^][,]+)(?:,\s*)?') output = rx.findall(string) print(output) # ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
score: 1

http://stackoverflow.com/comment/85158316
comment on: http://stackoverflow.com/a/49076083
type: AnswerComment
type: Comment
has text: yes it should be in your HTML, maybe it not working cause of your Django settings, you need to set STATIC_URL and STATICFILES_DIRS to your static files folder
score: 0

http://stackoverflow.com/a/49107468
type: Answer
accepted answer of: http://stackoverflow.com/q/49106997
score: 2
answers question: http://stackoverflow.com/q/49106997
has body: From official document: Don’t create a session per request. Most likely you need a session per application which performs all requests altogether. A session contains a connection pool inside. Connection reusage and keep-alives (both are on by default) may speed up total performance. Surely the latter one is better and definitely you will have a faster experience.
upvote count: 2
type: AcceptedAnswer
downvote count: 0

conditional-statements
tags question: http://stackoverflow.com/q/49103628
tags question: http://stackoverflow.com/q/49019238
tags question: http://stackoverflow.com/q/49047409
tags question: http://stackoverflow.com/q/49119217
tags question: http://stackoverflow.com/q/48985751
tags question: http://stackoverflow.com/q/49020821
tag name: conditional-statements
tags question: http://stackoverflow.com/q/49082093
tags question: http://stackoverflow.com/q/49042180
tags question: http://stackoverflow.com/q/48991150
tags question: http://stackoverflow.com/q/49058919
type: Tag
tags question: http://stackoverflow.com/q/49105138

http://stackoverflow.com/comment/85090114
score: 0
has text: What is "Transcrypt"? Do you mean [this](https://transcrypt.org/) Python library?
type: QuestionComment
comment on: http://stackoverflow.com/q/49042487
type: Comment

http://stackoverflow.com/a/49039578
score: 7
answers question: http://stackoverflow.com/q/49039402
upvote count: 7
has body: Ummm a new way pd.concat([df1,df2],join ='inner',axis=0).sum(level=[0,1])
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84986183
comment on: http://stackoverflow.com/a/48965545
type: AnswerComment
has text: Off course now I am posting full code for more clarifications
score: 0
type: Comment

http://stackoverflow.com/comment/84985111
score: 1
has text: Accessing a function's local variable without calling it doesn't make any sense. What's the X in this [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48990191

http://stackoverflow.com/q/49018481
accepted answer: http://stackoverflow.com/a/49018548
favorite count: 0
has comment: http://stackoverflow.com/comment/85042175
type: Question
downvote count: 2
tagged with: python
score: -2
answer count: 1
has title: Python - can't encode character u'\u2019' in position 4: ordinal not in range(256)
has answer: http://stackoverflow.com/a/49018548
has comment: http://stackoverflow.com/comment/85042370
has comment: http://stackoverflow.com/comment/85042247
upvote count: 0
has comment: http://stackoverflow.com/comment/85042228
has body: I have the following string: cbBb’ the last character is u'\u2019'. I tried the following: value = "cbBb’" value.replace(u"\u2019", "-") value.encode('ascii', 'ignore') but then when i try to do: str(value) I get: can't encode character u'\u2019' in position 4: ordinal not in range(256) How can i solve this?
type: AnsweredQuestion

http://stackoverflow.com/a/49025019
score: 0
accepted answer of: http://stackoverflow.com/q/49024801
type: Answer
answers question: http://stackoverflow.com/q/49024801
has body: First of all, you can still use pip to install downloaded source archives or wheels. Just point pip to the file: pip install pdfminer.six-20170720.tar.gz As for why your pip installation is broken: Due to path length issues on Windows, Anaconda had moved the pip vendored packages to normal dependencies (pip vendors packages to avert problems exactly like you have now). You then installed a package (like Tensorflow), that requires an older version of one of the pip dependencies, html5lib. This caused everything to break, horribly. You should be able to fix the pip issue with conda update pip as the newer version has returned to vendored dependencies (after a bugfix upstream that avoids the path length issues). For more details, see this issue in the Tensorflow project, which is one such project that needed an older html5lib version and triggered the same problem.
type: AcceptedAnswer

http://stackoverflow.com/q/49029019
has comment: http://stackoverflow.com/comment/85062614
has body: I have started learning Python recently and I've been going through the NumPy official quickstart guide which includes this example for iterating. &gt;&gt;&gt; a array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729]) &gt;&gt;&gt; for i in a: ... print(i**(1/3.)) ... nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0 However, if I just try to raise -1000 to the power of (1/3.) outside of the loop it returns a value. &gt;&gt;&gt; -1000**(1/3.) -9.999999999999998 With parentheses around -1000 it also returns a value. &gt;&gt;&gt; (-1000)**(1/3.) (5+8.660254037844384j) Why is it that the same action returns nan in the for loop? I'm using Python 3.6.3 :: Anaconda custom (64-bit). I also tried with different fractions that do not round up and it's the same. With a fraction that rounds up to .0 it works though. I couldn't find a similar question. Excuse me if I'm missing something very obvious. Edit: A few comments mentioned that the question duplicates NumPy, RuntimeWarning: invalid value encountered in power and it's true, the problem was I didn't see such an error. The discussion there, however, seems to include a few possible workarounds.
has comment: http://stackoverflow.com/comment/85062618
score: 9
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/85062438
linked to: http://stackoverflow.com/q/45384602
has comment: http://stackoverflow.com/comment/85062870
has comment: http://stackoverflow.com/comment/85062687
has comment: http://stackoverflow.com/comment/85062542
has comment: http://stackoverflow.com/comment/85062562
favorite count: 0
upvote count: 9
has title: In Python 3.6, why does a negative number to the power of a fraction return nan when in a numpy array?
accepted answer: http://stackoverflow.com/a/49029425
has comment: http://stackoverflow.com/comment/85062486
tagged with: python
possible better answer: http://stackoverflow.com/a/49029638
has answer: http://stackoverflow.com/a/49029638
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49029425
downvote count: 0
has comment: http://stackoverflow.com/comment/85062349
has comment: http://stackoverflow.com/comment/85062406

http://stackoverflow.com/q/49050798
upvote count: 0
has answer: http://stackoverflow.com/a/49050962
has answer: http://stackoverflow.com/a/49051365
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85108286
has comment: http://stackoverflow.com/comment/85105952
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49050962
has body: I am stuck in Python. I need to create and parse a 3-level list. For example, a list inside a list inside a list. 2 levels are working for me but going to the third is so much confusion please help l= [1,5,6,7,8,['a','b','c','d']] a= ['name 1','name 2',l] for i in a: if type(i) == type([]): for j in i: print(j, end=' ') for k in j: if type(j) == type([]): print('non') else: print(i, end=' ')
downvote count: 3
has title: Three level list in PYTHON
type: Question
possible better answer: http://stackoverflow.com/a/49050864
score: -3
has answer: http://stackoverflow.com/a/49050864
answer count: 3
has comment: http://stackoverflow.com/comment/85105950

http://stackoverflow.com/q/49037567
accepted answer: http://stackoverflow.com/a/49043337
type: AnsweredQuestion
has body: I am having an issue where I am trying to create a recommender system for a local newspaper (as a school project), but I am running into trouble when I am trying to use the cross_validate function from the model_selection library. I am trying to use SVD and obtain the f1 score. But I am a bit confused. So this is unsupervised learning, and I do not have a test set, so I want to use KFolding for the cross validation. I believe the number of folds for this is denoted by the "cv" parameter in the cross_validate function. Is this correct? The problem arise when I try to run the code, as I get the following stack trace: https://hastebin.com/kidoqaquci.tex I am not passing anything to the "y" parameter of the cross_validate function, but is this wrong? Is not this where the test set should go? And as I said, I do not have any test set as this is unsupervised. I have looked at the example in chapter 3.1.1.1 here: http://scikit-learn.org/stable/modules/cross_validation.html And it looks like they are passing in a "target" for the dataset in the cross_validate function. But why are they passing both a target set AND the cv parameter? Does not a cv value above 1 indicate that kfolding should be used and that the fold left out is to be used as the target (test) set? Or am I completely misunderstanding something? Why am I getting the "missing argument" error in the stack trace? This is the code that is failing: from sklearn.model_selection import cross_val_score as cv from sklearn.decomposition.truncated_svd import TruncatedSVD import pandas as pd # keywords_data_filename = 'keywords_data.txt' active_data_filename = 'active_time_data.txt' header = ['user_id', 'item_id', 'rating'] # keywords_data = pd.read_csv(keywords_data_filename, sep='*', names=header, engine='python') active_time_data = pd.read_csv(active_data_filename, sep='*', names=header, engine='python') # Number of users in current set print('Number of unique users in current data-set', active_time_data.user_id.unique…
tagged with: scikit-learn
type: Question
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/49043337
score: 0
has title: Recommender System using SciKit-Learn's cross_validate, missing 1 required positional argument: 'y_true'

http://stackoverflow.com/comment/85168676
type: QuestionComment
has text: @Saurav Panda I have tried your suggestion still no luck
comment on: http://stackoverflow.com/q/48975594
score: 0
type: Comment

http://stackoverflow.com/q/49071849
has title: How to get all descendants of a node with Django mptt?
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64172021
type: Question
accepted answer: http://stackoverflow.com/a/49078672
tagged with: django-models
tagged with: django-mptt
tagged with: descendant
has answer: http://stackoverflow.com/a/49078672
score: 0
answer count: 3
has body: I would like my categories to show all items in that category including descendant categories, so the parent category contains all items for subcategories. I have tried adding this method to my Category class in models.py def get_all_products(self): # To display all items from all subcategories return Product.objects.filter(category__in=Category.objects.get_descendants(include_self=True)) And added this to my template.html, but it does't work. What am I doing wrong? {{ product.product_name }} {% empty %} No items {% endfor %}
possible better answer: http://stackoverflow.com/a/64172021
has answer: http://stackoverflow.com/a/76774504

http://stackoverflow.com/q/49013245
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: magic-methods
has comment: http://stackoverflow.com/comment/85035011
tagged with: methods
linked to: http://stackoverflow.com/q/15507848
has title: How do get dir() to return a non-empty list for a user-defined class?
type: Question
has body: A variant of this question has already been asked here. However, it is still not clear to me how to properly deal with __dir__ Some have suggested using a class named "DirMixIn," However, it is poorly documented and it not at all clear how one is supposed to use it. I wrote a class, and whenever I call its __dir__ method, I get an empty list. I'm not sure why. optional lineno available here # from lineno import lineno try: lineno except NameError: lineno = lambda: '' class ForceGetattr: def __init__(self, inner_self): print(lineno(), ' | ', 'dir(self) == ', dir(self)) # debug while isinstance(inner_self, type(self)): inner_self = object.__getattribute__(inner_self, '_inner_self') object.__setattr__(self, '_inner_self', inner_self) # self.inner_self = inner_self create_attrs_from_inner = object.__getattribute__(self, 'create_attrs_from_inner') create_attrs_from_inner() print(lineno(), ' | ', 'dir(self) == ', dir(self)) def create_attrs_from_inner(self): get_inner_attrs = object.__getattribute__(self, 'get_inner_attrs') # debug print(lineno(), ' | ', 'dir(self) == ', dir(self)) inner_attrs = get_inner_attrs() assert(len(inner_attrs) &gt; 0) ignore = object.__getattribute__(self, 'ignore') already_have = object.__getattribute__(self, 'already_have') print(lineno(), ' | ', 'dir(self) == ', dir(self)) # debug for attr_name in (ignore | already_have): inner_attrs.discard(attr_name) assert(len(inner_attrs) &gt; 0) print(lineno(), ' | ', 'dir(self) == ', dir(self)) # debug for attr_name in inner_attrs: make_proxy = object.__getattribute__(self, 'make_proxy') attr = make_proxy(attr_name) setattr(self, attr_name, attr) print(lineno(), ' | ', 'dir(self) == ', dir(self)) # debug return def get_inner_attrs(self): inner_self = object.__getattribute__(self, '_inner_self') dr = set(dir(inner_self)) dt = type(inner_self).__dict__.keys() if hasattr(inner_self, '__dict__'): dt = set(inner_self.__dict__.keys()) # print('dr == \n', dr) # print('\n\n') # print(dt) # print('dr == \n', dr)…
tagged with: class
has comment: http://stackoverflow.com/comment/85031442
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/a/60476125
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49053741
has body: Setting debug=False temporarily fixes the problem. But I dont really know what is the issue when debug is set to True

http://stackoverflow.com/comment/85083623
has text: Thanks a bunch. I will look through the documentation.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49019146

http://stackoverflow.com/q/49052907
has answer: http://stackoverflow.com/a/49071147
has comment: http://stackoverflow.com/comment/85125671
score: 3
has comment: http://stackoverflow.com/comment/85111832
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85111330
has comment: http://stackoverflow.com/comment/85110901
type: Question
linked to: http://stackoverflow.com/q/42403844
has body: I've created a map and I am reading in a CSV of latitude and longitude coordinates into a Pandas DataFrame. I've been successful in plotting multiple great arcs using a 'for' loop after reading in the DataFrame. I am now trying to animate the multiple great arcs. The reason for the animation is to live update the plot when the CSV is updated. I eventually will use a SQL table for the DataFrame rather than a CSV, but I wanted to get the animation portion working first. I read and watched multiple tutorials on matplotlib and animation. I've read the source documentation and attempted to apply multiple examples. I've been able to successfully animate a single great arc but can't seem to expand the code to multiple arcs. Edit1: I want all great circle arcs from the file to be drawn on the map (I've got this part working). When a new set of latitude and longitude is added to the file I want it to update automatically within the same figure. I am trying to use this as a realtime display. **Edit2: I've paired down the code as much as possible. It is minimal with a basic map, a few long/lat coordinates in a data frame and my attempt to animate the lines. I had to keep a CSV input as it is the only way to verify that the map updates once the CSV is updated. The CSV contains the following: sourcelon sourcelat destlon destlat 50.44 30.51 -80.84 35.22 52.52 13.4 -80.84 35.22 43.18 -22.97 -80.84 35.22 35.18 -22.97 -80.84 35.22 The arcs are being drawn, but are not being updated when the CSV is updated. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import pandas as pd import numpy as np import matplotlib.animation # create new figure, axes instances. fig=plt.figure() # setup mercator map projection. plt.figure(figsize=(27, 20)) m = Basemap(projection='mill', lon_0=0) m.drawcoastlines(color='r', linewidth=1.0) def animate(i): df = pd.read_csv('c:/python/scripts/test2.csv', sep='\s*,\s*',header=0, encoding='ascii', engine='python'); df for x,y,z,w in zip(…
has comment: http://stackoverflow.com/comment/85111538
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85125315
tagged with: updating
favorite count: 0
has comment: http://stackoverflow.com/comment/85128102
tagged with: pandas
has title: Matplotlib animate multiple great circles and update from pandas df
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/85111316
type: UnansweredQuestion

http://stackoverflow.com/a/49100460
has comment: http://stackoverflow.com/comment/85285086
upvote count: 2
has comment: http://stackoverflow.com/comment/85222791
type: Answer
accepted answer of: http://stackoverflow.com/q/49093704
score: 2
answers question: http://stackoverflow.com/q/49093704
has body: First of all you should split ChooseTransport into 7 colunms then try to use data.corr() (if your data is a pandas.DataFrame). For splitting ChooseTransport try this: for row_index, answer in enumerate(data['ChooseTransport']): for i in range(7): name = 'ChooseTransport_' + str(i) data.loc[row_index, name] = int(answer[i]) Then drop old column ChooseTransport: data.drop(columns=['ChooseTransport'], inplace=True) Finally use data.corr(): data.corr() For visualisation use seaborn: import seaborn as sns sns.heatmap(data.corr())
has comment: http://stackoverflow.com/comment/85212512
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49084214
accepted answer: http://stackoverflow.com/a/49084341
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
has body: While making a website, I ran into a problem. I am sending a JSON data from views.py to my template to print each attribute value from JSON data, but the data showing is empty. data = { "philip": {"age": 20, "salary": 10000}, "jerry": {"age": 27, "salary": 30000} } names = ["philip", "jerry"] return render(request, 'index.html', {'data': data, 'names': names}) I'm storing the names from JSON data in a list and sending both data and names to template. &lt;div class="col-sm-3"&gt; {% for name in names %} {{ data.name }} {% endfor %} &lt;/div&gt; I want to get values associated with each name.
tagged with: django
has comment: http://stackoverflow.com/comment/85174096
type: Question
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/49084341
score: 0
has title: JSON on Django template
answer count: 1
has comment: http://stackoverflow.com/comment/85173989
tagged with: python-3.x

http://stackoverflow.com/q/49016255
favorite count: 0
has comment: http://stackoverflow.com/comment/85037540
has answer: http://stackoverflow.com/a/63408972
has answer: http://stackoverflow.com/a/49016481
tagged with: django
has body: I have this in my views.py def read_file(request): f = open('path/text.txt', 'r') file_contents = f.read() print (file_contents) f.close() return render(request, "index.html", context) Urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^impala/$', views.people, name='impala'), ] I am not seeing anything on the website (text.txt file has information). I also don't see any output in the terminal and there are no errors.
tagged with: python
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/63408972
accepted answer: http://stackoverflow.com/a/49016481
upvote count: 3
type: Question
tagged with: python-2.7
answer count: 2
has title: Django: Display contents of txt file on the website
downvote count: 0
has comment: http://stackoverflow.com/comment/85037645

regression
tags question: http://stackoverflow.com/q/48979658
tags question: http://stackoverflow.com/q/49072359
tags question: http://stackoverflow.com/q/49058847
tags question: http://stackoverflow.com/q/48969217
tags question: http://stackoverflow.com/q/49007740
tag name: regression
type: Tag
tags question: http://stackoverflow.com/q/49067495
tags question: http://stackoverflow.com/q/49043622
tags question: http://stackoverflow.com/q/49043061

http://stackoverflow.com/q/49019241
has title: Execute trained tensorflow model using linear algebra only
has body: I'm training the image classification model as per : https://www.tensorflow.org/tutorials/image_recognition I aim to extract the learned weight values ( based on : Extracting weights values from a tensorflow model checkpoint ) and execute the model using linear algebra operations only. The function def run_inference_on_image(image) (src https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/classify_image.py) classifies an image but the linear algebra operations used to classify the image do not appear to be viewable. Is possible to execute the model using the various matrix transformations that I assume are taking place ' under the hood' in function run_inference_on_image ?
tagged with: deep-learning
linked to: http://stackoverflow.com/q/45562755
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49068562
favorite count: 0
linked to: http://stackoverflow.com/q/39352108
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47178371
tagged with: python
score: 3
upvote count: 3
tagged with: image-processing
tagged with: tensorflow
type: Question
tagged with: neural-network

http://stackoverflow.com/comment/85235715
score: 0
comment on: http://stackoverflow.com/q/49115251
type: Comment
type: QuestionComment
has text: I'm afraid `x^2` is not doing what you think is doing. The `^` is an xor operator

http://stackoverflow.com/q/48998881
has comment: http://stackoverflow.com/comment/85003194
has comment: http://stackoverflow.com/comment/85003118
upvote count: 2
has comment: http://stackoverflow.com/comment/85003280
downvote count: 2
has comment: http://stackoverflow.com/comment/85003356
has comment: http://stackoverflow.com/comment/85003202
has body: I'm trying to escape quote marks in Python, but my intended plan does not work: &gt;&gt;&gt; s = 'Hi "there"' &gt;&gt;&gt; s.replace('"', '\"') 'Hi "there"' &gt;&gt;&gt; s.replace('"', '\\"') 'Hi \\"there\\"' What is the proper way to single-escape quotes within a string (e.g. make 'Hi \"there\"')?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85003207
has answer: http://stackoverflow.com/a/48998978
linked to: http://stackoverflow.com/q/24085680
type: Question
has comment: http://stackoverflow.com/comment/85003212
has comment: http://stackoverflow.com/comment/85003166
duplicate of: http://stackoverflow.com/q/24085680
answer count: 1
has comment: http://stackoverflow.com/comment/85003254
has comment: http://stackoverflow.com/comment/85003126
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/48998978
has comment: http://stackoverflow.com/comment/85003209
has comment: http://stackoverflow.com/comment/85003244
has title: Python: escape quotes with slashes
tagged with: python

http://stackoverflow.com/comment/84948729
has text: Please format..
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48971762

tweepy
tags question: http://stackoverflow.com/q/49000392
tags question: http://stackoverflow.com/q/49098726
type: Tag
tags question: http://stackoverflow.com/q/48966176
tags question: http://stackoverflow.com/q/49027297
tag name: tweepy

http://stackoverflow.com/comment/85151787
comment on: http://stackoverflow.com/a/49058317
type: Comment
has text: I don't believe this is currently solved. The suggestion in the issue only relates to the specific example in question, it isn't a general fix I don't think.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48982423
has answer: http://stackoverflow.com/a/49007248
has body: I am working on fb chatbot and use postback in the generic templates buttons. However, there is no response after I click the postback button. "buttons": [ { "type": "web_url", "url": "https://maps.google.com/?q={lat},{lon}".format(lat=store['coordinates']['lat'], lon=store['coordinates']['lon']), "title": u"店家位置" }, { "type": "postback", "payload": Function.sendGourmetComments + "_{id}".format(id=store["id"]), "title": u"觀看評論" }, { "type": "postback", "payload": Function.sendStoreHearts + "_{upload}".format(upload=None) + "_{id}".format(id=store["id"]) + "_{push}".format(push=None) + "_{edit}".format(edit=None) + "_{search}".format(search=True), "title": u"撰寫評論" } ] I guess I didn't check the message_postback event, however, I did. I didn't even receive any response from my webhook. So it's kind of mysterious to me what's going on. It was working fine before, but it doesn't work without change after restart my computer. I am using ngork to expose my server API as callback url.
type: Question
tagged with: flask
score: 0
tagged with: facebook-webhooks
answer count: 1
tagged with: facebook-chatbot
has title: Facebook Chatbot postback don't respond
type: UnansweredQuestion
tagged with: facebook
tagged with: python

http://stackoverflow.com/comment/85018359
has text: sorry if Im not make it clear enough, but yes, I should move y coordinate for 1 like in plot
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48998246

http://stackoverflow.com/comment/85208092
type: Comment
comment on: http://stackoverflow.com/q/49101423
score: 1
has text: You can do either one in almost all cases. From just means your are importing something within that module. For example ‘from numpy import arcsin’
type: QuestionComment

http://stackoverflow.com/q/48982838
has comment: http://stackoverflow.com/comment/85028038
has body: I am sending this dataframe from django views to template html file Forecast Date 2018-01-22 05:30:00 147.01 2018-01-23 05:30:00 139.67 2018-01-24 05:30:00 140.51 2018-01-25 05:30:00 144.68 2018-01-26 05:30:00 142.97 2018-01-27 05:30:00 151.83 2018-01-28 05:30:00 151.93 2018-01-29 05:30:00 142.88 2018-01-30 05:30:00 157.31 2018-01-31 05:30:00 145.67 In this above data frame the forecast is the column and date and the values are rows , but i want the the date to be in a column and the forecast values to be in another column. This is the HTML file where i am trying to change the dataframe to html table. `&lt;html&gt; &lt;body&gt; &lt;table&gt; &lt;table&gt; {% for r in table %} {% cycle '&lt;tr&gt;' '' '' '' %}tr&gt; &lt;td&gt;{{r.content}}&lt;/td&gt; &lt;{% cycle '' '' '' '&lt;/tr&gt;' %} {% endfor %} &lt;/table&gt; {{accuracy}} &lt;/html&gt;`
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48983649
tagged with: django-templates
tagged with: django-views
has comment: http://stackoverflow.com/comment/84974734
has title: How to change dataframe to html table in django ?
type: Question
has answer: http://stackoverflow.com/a/48983649
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/48967223
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84940547
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/101695346
upvote count: 6
has comment: http://stackoverflow.com/comment/84940502
accepted answer of: http://stackoverflow.com/q/48967165
score: 6
has comment: http://stackoverflow.com/comment/84940519
has comment: http://stackoverflow.com/comment/84940581
has comment: http://stackoverflow.com/comment/105520121
has comment: http://stackoverflow.com/comment/101620618
answers question: http://stackoverflow.com/q/48967165
has body: I believe you need groupby: df['D'] = df["C"].shift(1).groupby(df['A'], group_keys=False).rolling(2).mean() print (df.head(20)) C D A B id 01 2018-01-01 10 NaN 2018-01-02 11 NaN 2018-01-03 12 10.5 2018-01-04 13 11.5 2018-01-05 14 12.5 2018-01-06 15 13.5 2018-01-07 16 14.5 2018-01-08 17 15.5 2018-01-09 18 16.5 2018-01-10 19 17.5 id 02 2018-01-11 20 NaN 2018-01-12 21 19.5 2018-01-13 22 20.5 2018-01-14 23 21.5 2018-01-15 24 22.5 2018-01-16 25 23.5 2018-01-17 26 24.5 2018-01-18 27 25.5 2018-01-19 28 26.5 2018-01-20 29 27.5 Or: df['D'] = df["C"].groupby(df['A']).shift(1).rolling(2).mean() print (df.head(20)) C D A B id 01 2018-01-01 10 NaN 2018-01-02 11 NaN 2018-01-03 12 10.5 2018-01-04 13 11.5 2018-01-05 14 12.5 2018-01-06 15 13.5 2018-01-07 16 14.5 2018-01-08 17 15.5 2018-01-09 18 16.5 2018-01-10 19 17.5 id 02 2018-01-11 20 NaN 2018-01-12 21 NaN 2018-01-13 22 20.5 2018-01-14 23 21.5 2018-01-15 24 22.5 2018-01-16 25 23.5 2018-01-17 26 24.5 2018-01-18 27 25.5 2018-01-19 28 26.5 2018-01-20 29 27.5

http://stackoverflow.com/a/49046940
type: Answer
has comment: http://stackoverflow.com/comment/85102626
has body: To check if the ng-grid cell is selected or not you can use the following code block : divClasses = driver.find_element_by_xpath("//div[@class='ui-grid-cell-contents ng-binding ng-scope' and contains(text(), 'Stefan')]//ancestor::div[@class='ui-grid-row ng-scope']").get_attribute("class") if "ui-grid-row-selected" in divClasses : print("Row is selected") else : print("Row is not selected")
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49042698
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49042698

http://stackoverflow.com/a/49094252
answers question: http://stackoverflow.com/q/49094026
downvote count: 0
has comment: http://stackoverflow.com/comment/85418423
accepted answer of: http://stackoverflow.com/q/49094026
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85196870
type: Answer
has body: Maybe you could replace the inner loop and your function with these matrix operations? for i in range(307200): temp = A[:,i,np.newaxis] - B[:] C[i,:] = np.linalg.norm(temp, axis=0) For smaller arrays, I got about 20 times lower running times. Perhaps you gain even more. In any case, plese make sure that you are receiving good results (on a smaller sets).
upvote count: 3
has comment: http://stackoverflow.com/comment/85197154

http://stackoverflow.com/a/48981359
answers question: http://stackoverflow.com/q/48981294
has body: One way is to use zip to associate characters in the same position. We can then send all of the characters from each position to a Counter, then use Counter.most_common to get the most common character from collections import Counter l = ['abcd', 'a5c1', 'b51d'] print(''.join([Counter(z).most_common(1)[0][0] for z in zip(*l)])) # a5cd
score: 0
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48981294
has comment: http://stackoverflow.com/comment/84968125
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84969381

http://stackoverflow.com/q/49101624
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49101744
tagged with: daemon
has body: I have a class MyClass which creates 7 threads when it is initialized. One thread is a TCPServer, and the other six are objects of MyClass which the TCPServer uses to process requests. My intention is to create method which can run in the background of MyClass and maintain the 6 threads. The 6 threads correspond to 2 distributed objects obj1 and obj2 replicated with an implementation of Raft called PySyncObj. There are three threads per object. Each cluster of objects obj_1_cluster and obj_2_cluster has a leader, which the server must keep track of, because all changes to the object must be sent only to the leader. class MyClass(object): def __init__(self): self.server = TCPServer() self.obj_1_cluster = self.init_cluster(Class_1['bindings'], Class_1) self.server.obj1 = self.get_leader(obj_1_cluster) self.obj_2_cluster = self.init_cluster(obj_2['bindings'], Class_2) self.server.obj2 = self.get_leader(obj_2_cluster) # Create Daemon process for keeping leader current. self.obj1_leader_daemon = Thread(target = self.__obj1_leader_daemon()) self.obj1_leader_daemon.setDaemon(True) self.obj1_leader_daemon.start() self.obj2_leader_deamon = Thread(target = self.__obj2_leader_daemon()) self.obj2_leader_deamon.setDaemon(True) self.obj2_leader_deamon.start() def __obj1_leader_daemon(self): while True: print("Running obj1 daemon") if self.server.obj1._isLeader(): pass else: self.server.obj1 = self.get_leader(self.obj1) def __obj2_leader_daemon(self): while True: print("running obj2 daemon") if self.server.obj2._isLeader(): pass else: self.server.obj2 = self.get_leader(self.obj2) When I run this code, the only output I see is... Running obj1 daemon Running obj1 daemon Running obj1 daemon ... until I kill the process with ctrl-C. Is there a way to change this so that these two processes can run with their own thread- busily checking the state of the objects in case they need to change them? I've read a lot about threading and I don't see why this isn't currently working the way I t…
tagged with: python-multithreading
tagged with: multithreading
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49101744
tagged with: raft
type: Question
has title: python threading method stuck

http://stackoverflow.com/comment/85117766
comment on: http://stackoverflow.com/q/49056567
has text: Yes I understand that, but I want to treat missing indexes as missing values, for which the documentation says they should be treated as zero. Is it a bug in Pandas or in the documentation?
score: 0
type: Comment
type: QuestionComment

pybrain
type: Tag
tag name: pybrain
tags question: http://stackoverflow.com/q/48966371

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

http://stackoverflow.com/comment/85074155
has text: @RobertMillard It looks like the request returned `None`, which is obviously not a valid JSON object. As to why, no idea, sorry.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49013516
type: AnswerComment

http://stackoverflow.com/q/49040074
score: 1
type: Question
has comment: http://stackoverflow.com/comment/85085512
has title: Going back one iteration in a for loop?
has body: I was wondering if, while in a for loop and using a dictionary, you could go back an iteration if someone does not put in an appropriate value. If what I'm saying doesn't make much sense, maybe my code can give you a better idea of what I'm trying to do. attributesD = {"Charisma": 0, "Intelligence" : 0 ,"strength" : 0 , "agility" : 0 , "constitution" : 0} totalPoints = 15 def listing(): print(" Attributes ".center(108,"*")) abilitiesSteady_Print("\n\nPoints left: " + str(totalPoints) + "\n\n") for index in attributesD: abilitiesSteady_Print(index + ": " + str(attributesD[index]) + "\n\n") for key in attributesD: if totalPoints &gt; 0: listing() try: attributesD[key] = int(input("\n\nHow many points would you like to put in " + key + "?\n&gt;")) totalPoints -= attributesD[key] replit.clear() except: steady_print("Not possible, try again") else: continue If the user doesn't put in an appropriate answer, it willl skip that attribute, and 0 will remain as the value. How to I prevent that from happening?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85087066
has answer: http://stackoverflow.com/a/49040280
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/85175008
score: 0
type: Comment
type: QuestionComment
has text: Desired output:no 'foo!'
comment on: http://stackoverflow.com/q/49084733

http://stackoverflow.com/comment/84963766
score: 0
type: QuestionComment
has text: I've written these modules myself. Now I feel like an idiot because your solution was so simple! Thanks very much
type: Comment
comment on: http://stackoverflow.com/q/48979233

http://stackoverflow.com/comment/85060153
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49026524
has text: FYI, your issue is most likely due to either your docker configuration, which you didn't provide (try first to reproduce the issue outside of docker to confirm docker is causing the problem) or due to the way you configured splash ui, in which case SuperUser should be better suited as the question would not be code related
score: 0

http://stackoverflow.com/comment/85211304
score: 2
comment on: http://stackoverflow.com/q/49102849
type: Comment
type: QuestionComment
has text: According to [the example](http://doc.qt.io/qt-5/qtwidgets-tools-undoframework-example.html): _"An undo command class knows how to both redo() - or just do the first time - and undo() an action."_, i.e. redo is equal to "do", so to say. To be honest I was also surprised when I first used the undo framework (a couple of years ago), but that's the way it is. So, to answer your question - because it is designed like that. I presume it has something to do with a particullar design pattern. Take a look at the [command pattern](https://www.youtube.com/watch?v=9qA5kw8dcSU).

http://stackoverflow.com/comment/84937199
type: Comment
has text: hmm actually i iterate over the x which is the row.. so the a[j] contains all possible j´s... it does look right.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48965707

http://stackoverflow.com/q/48993409
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48993450
has title: assign values groupwise using the group name as input
type: Question
has body: This is probably an easy one but I couldn't figure it out. I have two dataframes import numpy as np import pandas da0 = pandas.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['two', 'one', 'two', 'three', 'three', 'one', 'two', 'two'], 'C' : np.random.randn(8), 'D' : np.random.randn(8) }) da1 = pandas.DataFrame({'E' : ['one', 'two', 'three'], 'F' : ['alpha', 'beta', 'gamma'] }) I would like to add a new column to da0. This column should should take the values from column 'F' in da1 corresponding to the matching between 'E' in da1 and 'B' in da0. In the example, the result should be da0 = pandas.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['two', 'one', 'two', 'three', 'three', 'one', 'two', 'two'], 'C' : np.random.randn(8), 'D' : np.random.randn(8), 'new': ['beta', 'alpha', 'beta', 'gamma', 'gamma', 'alpha', 'beta', 'beta'] }) I tried grouping da0 by 'B' and then using transform but then I didn't know how to use the name of the group in the custom function. How should I do this?
possible better answer: http://stackoverflow.com/a/48993492
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48993492
tagged with: pandas
has answer: http://stackoverflow.com/a/48993450
tagged with: python

sql-server
tags question: http://stackoverflow.com/q/49073887
tags question: http://stackoverflow.com/q/49084328
tags question: http://stackoverflow.com/q/49113341
type: Tag
tags question: http://stackoverflow.com/q/49082424
tags question: http://stackoverflow.com/q/49075522
tag name: sql-server
tags question: http://stackoverflow.com/q/48969397
tags question: http://stackoverflow.com/q/49043373
tags question: http://stackoverflow.com/q/49033818
tags question: http://stackoverflow.com/q/49006295
tags question: http://stackoverflow.com/q/49000660

http://stackoverflow.com/comment/85186520
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49090260
has text: So I just need a dependency mechanism then
score: 0

http://stackoverflow.com/a/49043828
type: Answer
has comment: http://stackoverflow.com/comment/85161253
answers question: http://stackoverflow.com/q/49035660
score: 3
has body: I'm kind of assuming you don't want to insert 1500 figures in a report or talk and therefore the purpose of this is just to investigate the file slice by slice. If this is the case I would simply open the file using ncview file.nc This allows you to step through the slices, animate, pass the cursor over the slices to see the values and click on a point to see a timeseries. If you don't have it, you can install it easily with apt-get (ubuntu, mint etc) with sudo apt-get install ncview
downvote count: 0
has comment: http://stackoverflow.com/comment/85150359
upvote count: 3

http://stackoverflow.com/comment/85121721
type: QuestionComment
score: 3
has text: Those *are* the definitions for char1 and char2. There's no " in" variables here.
comment on: http://stackoverflow.com/q/49058382
type: Comment

http://stackoverflow.com/comment/85042393
has text: If you get an error, please provide it. Also provide an expected output
comment on: http://stackoverflow.com/q/49018432
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85042818
comment on: http://stackoverflow.com/q/49016294
score: 0
type: Comment
type: QuestionComment
has text: `differentiate` should work fine with indexed variables. Can you please update your question with the pyomo version, python version, and a minimal example that illustrates the behavior?

http://stackoverflow.com/comment/85229805
type: QuestionComment
comment on: http://stackoverflow.com/q/49078760
has text: Ah, that fixed it. So simple and makes me feel so dumb. Thank you!
score: 0
type: Comment

http://stackoverflow.com/q/49091764
accepted answer: http://stackoverflow.com/a/49094113
upvote count: 1
answer count: 1
has body: I am running the first lines of the cell types notebook: sweep_number = 30 sweep_data = data_set.get_sweep(sweep_number) And I get this error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-8-1ff88b13fc24&gt; in &lt;module&gt;() 4 5 sweep_number = 30 ----&gt; 6 sweep_data = data_set.get_sweep(sweep_number) 7 C:\ProgramData\Anaconda3\lib\site-packages\allensdk\core\nwb_data_set.py in get_sweep(self, sweep_number) 112 unit = stimulus_dataset.attrs["unit"] 113 unit_str = None --&gt; 114 if unit.startswith('A'): 115 unit_str = "Amps" 116 elif unit.startswith('V'): TypeError: startswith first arg must be bytes or a tuple of bytes, not str
has comment: http://stackoverflow.com/comment/85250967
tagged with: allen-sdk
type: AnsweredQuestion
has title: TypeError while running Cell Types notebook from AllenSDK
linked to: http://stackoverflow.com/q/19827615
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/49094113
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/85203245
has comment: http://stackoverflow.com/comment/85192884
has comment: http://stackoverflow.com/comment/85242690

web2py
tags question: http://stackoverflow.com/q/49055834
type: Tag
tag name: web2py

http://stackoverflow.com/q/49065126
tagged with: python
tagged with: excel
score: 2
tagged with: openpyxl
type: Question
has answer: http://stackoverflow.com/a/52547698
has title: Keeping excel-like pivot with openpyxl
has body: I have an xlsx with 2 worksheet. In the first sheet I have an Excel pivot, in the second one the data source for the pivot table. I would like to modify the data source via python keeping the pivot structure in the other sheet. Opening the woorkbook with openpyxl I lost the pivot table, does anyone know if there is an option to avoid this behaviour?
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/85020688
comment on: http://stackoverflow.com/q/49007666
has text: @cco I do think that would work, but I would like to be able to send them a file which does not require any specific knowledge rather than expecting them to learn the basics of Jupyter notebooks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49081500
upvote count: 3
has body: When f is printed at the end, its still the value from when you first assigned it to f. Changing b after you did that evaluation does nothing to the value of f. You'd have to do f=a and b and c and d and e again, after changing the value of b, to have any affect on f: &gt;&gt;&gt; a=True &gt;&gt;&gt; b=True &gt;&gt;&gt; c=True &gt;&gt;&gt; d=True &gt;&gt;&gt; e=True &gt;&gt;&gt; f=a and b and c and d and e &gt;&gt;&gt; f True &gt;&gt;&gt; b = False &gt;&gt;&gt; f True &gt;&gt;&gt; f=a and b and c and d and e &gt;&gt;&gt; f False
downvote count: 0
answers question: http://stackoverflow.com/q/49081455
type: Answer
score: 3

http://stackoverflow.com/a/49010829
accepted answer of: http://stackoverflow.com/q/49010377
has comment: http://stackoverflow.com/comment/85026406
has body: Here is what I think you are trying to achieve: from datetime import datetime import time def open_inTime(): return datetime.now().time() start_time = datetime.strptime('14:50', '%H:%M').time() end_time = datetime.strptime('16:00', '%H:%M').time() if start_time &lt;= open_inTime() &lt;= end_time: print('Success!') else: print("Time to open webbrowser is long over due") Explanation In general, use functions to return values. Define time objects from strings and assign them to variables. Use chained comparisons as this is more efficient and readable.
type: AcceptedAnswer
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49010377
score: 3

http://stackoverflow.com/comment/85156906
comment on: http://stackoverflow.com/a/49075275
has text: Yep, flush = True did it also for the Popup console :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85239969
type: QuestionComment
comment on: http://stackoverflow.com/q/49117330
score: 0
has text: sorry, I mixed up the keys and values. Edited the question.
type: Comment

http://stackoverflow.com/comment/85021678
type: AnswerComment
has text: Hi! I guess i'll need to find another solution for this then. Thanks for your answer!
type: Comment
comment on: http://stackoverflow.com/a/49007756
score: 0

http://stackoverflow.com/comment/85103852
type: QuestionComment
score: 1
has text: If you provided data along with your output, it would be much easier to help.
comment on: http://stackoverflow.com/q/49039465
type: Comment

http://stackoverflow.com/q/48975202
upvote count: 0
possible better answer: http://stackoverflow.com/a/48975341
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/84955330
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84955308
score: -1
tagged with: python-3.x
answer count: 2
downvote count: 1
has body: I have the following code: import requests from bs4 import BeautifulSoup import urllib.request import urllib.parse import re market = 'INDU:IND' quote_page = 'http://www.bloomberg.com/quote/' + market page = urllib.request.urlopen(quote_page) soup = BeautifulSoup(page, 'html.parser') name_box = soup.find('h1', attrs={'class': 'name'}) name = name_box.text.strip() print('Market: ' + name) This code works and lets me get the market name from the url. I'm trying to do something similar to this website. Here is my code: market = 'BTC-GBP' quote_page = 'https://uk.finance.yahoo.com/quote/' + market page = urllib.request.urlopen(quote_page) soup = BeautifulSoup(page, 'html.parser') name_box = soup.find('span', attrs={'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'}) name = name_box.text.strip() print('Market: ' + name) I'm not sure what to do. I want to retrieve the current rate, the amount it's increased/decreased by as a number &amp; a percentage. And finally as of when the information was updated. How do I do this, I don't mind if you do a different method to the one I used previously as long as you explain it. If my code is inefficient/unpythonic could you also tell me what to do to fix this. I'm pretty new to web scraping and these new modules. Thanks!
has answer: http://stackoverflow.com/a/48975446
linked to: http://stackoverflow.com/q/27543776
has answer: http://stackoverflow.com/a/48975341
accepted answer: http://stackoverflow.com/a/48975446
has title: Python - How to retrieve certain text from a website
type: AnsweredQuestion

http://stackoverflow.com/comment/85225486
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49096276
has text: Sorry, you completely changed the question. This invalidates all given answers to the original question.
type: AnswerComment

http://stackoverflow.com/q/49098469
linked to: http://stackoverflow.com/q/26688936
favorite count: 0
has comment: http://stackoverflow.com/comment/85203517
tagged with: pid
tagged with: python
has comment: http://stackoverflow.com/comment/85202508
tagged with: command-line
tagged with: subprocess
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/60561841
tagged with: process
upvote count: 1
has answer: http://stackoverflow.com/a/49099648
has comment: http://stackoverflow.com/comment/85202349
has title: How to get Process ID with name in python
type: Question
answer count: 2
has body: I am trying to build a simple python script that does one thing right now: it finds the process id of a process given it's PID. I have looked on here and found many different resources, but none that quite fit what I need. The most helpful is this one and I have used their example to try to make progress. Right now I have this: from subprocess import check_output def get_pid(name): return check_output(["pidof",name]) print(get_pid("fud")) I am using sudo top to view all my processes in a different terminal window. There is one process in particular named "fud" that I see on the screen and know that it is running. When I run the program for that process and any other process I get this: File "fort.py", line 6, in &lt;module&gt; print(get_pid("fud")) File "fort.py", line 4, in get_pid return check_output(["pidof",name]) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I am not really sure what is going on here, and would like detailed guidance on an effective way to correct this mistake and do what I am trying to do. Thanks!
downvote count: 0

http://stackoverflow.com/q/48971410
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 2
upvote count: 3
tagged with: arduino
type: Question
has body: I am using pyserial to communicate with my arduino on com5. Everythin works well when I use IDLE, BUT then when I use Spyder the servo does not rotate. I know it connects however, because I get RX blinks on the Arduino uno every 2 seconds, showing that time.sleep is firing, but no rotation. Again, the problem is only on Spyder. It works on IDLE. This is the sketch for the servo on an arduino uno: #include &lt;Servo.h&gt; Servo myservo; void setup() { myservo.attach(13); Serial.begin(9600); } void loop() { if (Serial.available() &gt; 0) { if (Serial.read() == 's') { myservo.write(90); delay(0); } if (Serial.read() == 'a') { myservo.write(45); delay(0); } if (Serial.read() == 't') { myservo.write(135); delay(0); } } } This is the code on python (Spyder) import serial import time ser1 = serial.Serial('COM5', 9600) ser1.write(b's') time.sleep(2) ser1.write(b'a') time.sleep(2) ser1.write('s'.encode()) time.sleep(2) ser1.write('a'.encode()) time.sleep(2) ser1.write('t'.encode()) time.sleep(2) as you can see I encoded as bytes and encode, and still nothing. Thanks in advance.
tagged with: pyserial
has title: How do I control an arduino servo through a python IDE?
tagged with: spyder
favorite count: 0
tagged with: servo

http://stackoverflow.com/a/49051221
has body: I am not sure if this will fix your problem. You can define a separate function that acquires frames from the camera and puts it in a queue. You can run this function in a separate thread. Refer to this link for documentation on threading. This speeds up the process of getting frames from the camera because the cap.read() function is a blocking function (if you are using cap=cv2.VideoCapture()). The code would be something like this. def getf(queue): cap = cv2.VideoCapture(0) while(processing): fr = {} ret, a = cap.read() if ret: fr["imagecaptured"]=a queue.put(fr) else: #whatever you want to do when a frame is unable to be read from cam cap.release() stream = threading.Thread(target=getf, args=queue) Note that 'processing' in the above code example is a global variable. Now, you can define a function to set processing to be true, and start the thread with 'stream.start()' command or put this directly in the program. Once the thread is started, frames are continuously put in queue for you to read when you want. With the below code, you have the frame. if not queue.empty(): capturedframe = queue.get() frame = capturedframe["imagecaptured"] I used this method to stream from camera and at same time do something else. Referred from a link on making a webcam widget with pyqt. Note that the above code snippets are for an example and are not read to be run. Apart from definitions, I suggest you also include a condition to keep check on queue size. You can now modify this to use for your application and see if it does the job. You can also refer to this link for a similar example.
type: Answer
answers question: http://stackoverflow.com/q/49033670
score: 0

http://stackoverflow.com/comment/85196814
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49095885
has text: It's not clear what your expected output or your actual problem is... please have a look at how to create a [mcve]
score: 0

http://stackoverflow.com/comment/85290569
type: QuestionComment
has text: @OdatNurd thanks for that comment, that was the problem. Instead of fixing Sublime I decided to just use Notepad++ instead. Thanks again for that help.
score: 0
comment on: http://stackoverflow.com/q/49101915
type: Comment

http://stackoverflow.com/a/49023675
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: result = Mensaje.objects.values('remitente__username').annotate(num_msg=Count('pk')).order_by('remitente__username') You did order_by as .order_by('-fechaEnvio') which has no logic in this context. ( You are trying to ordering a Table with an attribute (fechaEnvio), which is not belongs to the newly generated group_by table)
type: Answer
accepted answer of: http://stackoverflow.com/q/49019609
answers question: http://stackoverflow.com/q/49019609
score: 1

http://stackoverflow.com/q/49061458
has body: Launching the game puts the buttons in a random order (caused by a function) but when I continue to press the 'Correct' button, the buttons' positions don't update after the loading screen; even though their text updates. The position of the buttons don't update even after the randomPosition function changes each of the buttons' positions. Is there any way to update the buttons' positions so that the 'Correct' one isn't in the same place after the loading screen? import tkinter as tk from tkinter import StringVar from tkinter import * from random import randint f1 = ("MS Serif", 29) lives = 3 multiplier = 0 levelCounter = 1 answer2Counter = 0 answer3Counter = 1 answer4Counter = 2 def randomPosition(): #PLACES THE BUTTONS IN RANDOM VARIETY EACH TIME GAME IS OPEN global xpos1, xpos2, ypos3, ypos4, random random = randint(1,4) print("Random Integer Position: " + str(random)) #CO-ORDINATES FOR BUTTON PLACEMENT if random == 1: xpos1 = 50 xpos2 = 730 ypos3 = 610 ypos4 = 720 elif random == 2: xpos1 = 730 xpos2 = 50 ypos3 = 610 ypos4 = 720 elif random == 3: xpos1 = 50 xpos2 = 730 ypos3 = 720 ypos4 = 610 elif random == 4: xpos1 = 730 xpos2 = 50 ypos3 = 720 ypos4 = 610 randomPosition() BtnWidth = 20 def wrong(self, controller): global lives lives -= 1 print("Lives: " + str(lives)) if lives == 0: app.destroy() def correct(self, controller): global multiplier, levelCounter multiplier += 1 levelCounter += 1 answer1.set(ftvArray[levelCounter]) answer2.set(wrongFtvArray[multiplier][answer2Counter]) #READS 1ST VALUE OF ARRAY answer3.set(wrongFtvArray[multiplier][answer3Counter]) #READS 2ND VALUE OF ARRAY answer4.set(wrongFtvArray[multiplier][answer4Counter]) #READS 3RD VALUE OF ARRAY ftvArray = ['CORRECT', 'CORRECT', 'CORRECT', 'CORRECT', 'CORRECT', 'CORRECT', 'CORRECT', 'CORRECT', 'CORRECT', 'CORRECT'] wrongFtvArray = [['WRONG', 'WRONG', 'WRONG'], ['WRONG', 'WRONG', 'WRONG'], ['WRONG', 'WRONG', 'WRONG'], ['WRONG', 'WRONG', 'WRONG'], ['WRONG', 'WRONG', 'WRONG']] #'WRONG' IS A PLACE…
has comment: http://stackoverflow.com/comment/85128707
has comment: http://stackoverflow.com/comment/85128257
score: -1
has comment: http://stackoverflow.com/comment/85128423
has answer: http://stackoverflow.com/a/49075317
has comment: http://stackoverflow.com/comment/85130116
upvote count: 0
answer count: 1
tagged with: button
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85130085
has comment: http://stackoverflow.com/comment/85128412
has comment: http://stackoverflow.com/comment/85128204
tagged with: python
has title: Updating the position of a button after clicking? (Tkinter Python GUI)
tagged with: tkinter
type: UnansweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85128600

http://stackoverflow.com/q/49110073
has body: I tried rubberduckying this, but I give up. I don't understand why this keeps failing me. I have the following dictionary template I want to fill testfile = {'locations': {'location_name1": {'document_title1': 'title_value1', 'page_nr1': 'text_value1'} }} I have the following code that triest to insert multiple values into it. This represents the code that I'm currently working with. testfile = {} locatie = 0 while location != 5: page_nr = 0 while page_nr != 3: testfile = testfile + {'location':{'location_naam' + str(location): {'page_nr' + str(page_nr):'text_value'+ str(pagina_nr)}}} page_nr += 1 location += 1 This keeps resulting in the code overwriting testfile every loop. But i want to add the values and basically getting 3 location_names with 5 document_titles/page_nrs per location_name. How do i achieve this? EDIT The desired output would be {'location': {'location_naam0': { 'page_nr0': 'text_value0', 'page_nr1': 'text_value1', 'page_nr1': 'text_value1'}}, {'location_naam1': { 'page_nr0': 'text_value0', 'page_nr1': 'text_value1', 'page_nr1': 'text_value1'}}, {'location_naam2': { 'page_nr0': 'text_value0', 'page_nr1': 'text_value1', 'page_nr1': 'text_value1'}}, {'location_naam3': { 'page_nr0': 'text_value0', 'page_nr1': 'text_value1', 'page_nr1': 'text_value1'}}, {'location_naam4': { 'page_nr0': 'text_value0', 'page_nr1': 'text_value1', 'page_nr1': 'text_value1'}} }
tagged with: dictionary-comprehension
has comment: http://stackoverflow.com/comment/85251308
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49123025
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85225078
has answer: http://stackoverflow.com/a/49112015
type: Question
has answer: http://stackoverflow.com/a/49110212
has comment: http://stackoverflow.com/comment/85251445
accepted answer: http://stackoverflow.com/a/49123025
has title: How to add multiple values to a multilevel dictionary in python
possible better answer: http://stackoverflow.com/a/49110212
score: 0
answer count: 3

jupyter
tags question: http://stackoverflow.com/q/49118477
tags question: http://stackoverflow.com/q/49097097
tags question: http://stackoverflow.com/q/49083326
tags question: http://stackoverflow.com/q/49079714
type: Tag
tags question: http://stackoverflow.com/q/48985027
tags question: http://stackoverflow.com/q/49060661
tags question: http://stackoverflow.com/q/48978628
tags question: http://stackoverflow.com/q/49017178
tag name: jupyter
tags question: http://stackoverflow.com/q/49041338
tags question: http://stackoverflow.com/q/48964883
tags question: http://stackoverflow.com/q/49090954
tags question: http://stackoverflow.com/q/49107183

http://stackoverflow.com/q/48996994
type: Question
has body: from impala.dbapi import connect conn=connect(host="impala01",port=21050,user='username',password='password') error: TTransportException: Could not connect to "impala01":21050 Although connecting "impala01" is successful from the shell,but through python it gives me this error. Any suggestions?
score: 0
has comment: http://stackoverflow.com/comment/86799860
has title: TTransportException: Could not connect to "impala01":21050
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: impala
has comment: http://stackoverflow.com/comment/85092011

http://stackoverflow.com/a/49026563
upvote count: 1
answers question: http://stackoverflow.com/q/49010792
has comment: http://stackoverflow.com/comment/85103890
has comment: http://stackoverflow.com/comment/85103935
accepted answer of: http://stackoverflow.com/q/49010792
has body: you can remove the ones you do not want to be as stop words from this list # Open a file and read it into memory file = open('words.txt') text = file.read() # Apply the stoplist to the text clean = [word for word in text.split() if word not in stoplist]
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85100868
has comment: http://stackoverflow.com/comment/85099789
type: Answer
has comment: http://stackoverflow.com/comment/85100795
score: 1

http://stackoverflow.com/q/49052163
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85109175
tagged with: bioinformatics
has title: in python loop print lines from alternating files
tagged with: python
has answer: http://stackoverflow.com/a/49052418
tagged with: biopython
accepted answer: http://stackoverflow.com/a/49052433
has answer: http://stackoverflow.com/a/49052476
type: AnsweredQuestion
tagged with: fasta
score: 1
possible better answer: http://stackoverflow.com/a/49052418
upvote count: 1
has comment: http://stackoverflow.com/comment/85109030
type: Question
tagged with: fastq
has comment: http://stackoverflow.com/comment/85108979
has answer: http://stackoverflow.com/a/49052433
answer count: 3
has body: I am trying to use python to find four-line blocks of interest in two separate files then print out some of those lines in controlled order. Below are the two input files and an example of the desired output file. Note that the DNA sequence in the Input.fasta is different than the DNA sequence in Input.fastq because the .fasta file has been read corrected. Input.fasta &gt;read1 AAAGGCTGT &gt;read2 AGTCTTTAT &gt;read3 CGTGCCGCT Input.fastq @read1 AAATGCTGT + '(''%$')) @read2 AGTCTCTAT + &amp;---+2010 @read3 AGTGTCGCT + 0-23;:677 DesiredOutput.fastq @read1 AAAGGCTGT + '(''%$')) @read2 AGTCTTTAT + &amp;---+2010 @read3 CGTGCCGCT + 0-23;:677 Basically I need the sequence line "AAAGGCTGT", "AGTCTTTAT", and "CGTGCCGCT" from "input.fasta" and all other lines from "input.fastq". This allows the restoration of quality information to a read corrected .fasta file. Here is my closest failed attempt: fastq = open(Input.fastq, "r") fasta = open(Input.fasta, "r") ReadIDs = [] IDs = [] with fastq as fq: for line in fq: if "read" in line: ReadIDs.append(line) print(line.strip()) for ID in ReadIDs: IDs.append(ID[1:6]) with fasta as fa: for line in fa: if any(string in line for string in IDs): print(next(fa).strip()) next(fq) print(next(fq).strip()) print(next(fq).strip()) I think I am running into trouble by trying to nest "with" calls to two different files in the same loop. This prints the desired lines for read1 correctly but does not continue to iterate through the remaining lines and throws an error "ValueError: I/O operation on closed file"

http://stackoverflow.com/q/48979658
has comment: http://stackoverflow.com/comment/84964555
tagged with: python
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84964669
downvote count: 0
has title: Am I measuring the performance of my Multiple Linear Regression model correct?
has comment: http://stackoverflow.com/comment/84964652
has answer: http://stackoverflow.com/a/48984664
accepted answer: http://stackoverflow.com/a/48984664
type: Question
has comment: http://stackoverflow.com/comment/84964438
score: 4
has body: This might be a little bit of a silly question (and probably trivial question) but I am new to machine learning. This can probably be easily deduced from the code I came up with, and it's not an excuse for a poorly formulated question. If you find this question poorly formulated, please inform me so I can update it. I trained a multiple linear regression model and I want to see how well it performs a given data set. So, I googled around and I found a nice article explaining me how to find out the "error" of the predicted values, from the true ones. A couple of options it gave me were: I applied all of them and they gave me incredibly high values, so I don't know whether these are correct or how I should interpret them. Output the article was receiving: 10.0 150.0 12.2474487139 Output that my model received: 7514.293659640891 83502864.03257468 9137.990152794797 As a quick reference, these are my true / predicted values The 'TLDR' question: Am I measuring my error correctly using the above mentioned methods, and are these results implying that my model performs incredibly bad? (This didn't seem like it, when I compared the prediction with the true values) Here you can have a look at the data set I am using. The code I used to create the model and predict values ( I tried to remove the unneeded code ) # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.linear_model import LinearRegression from sklearn import metrics dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values # Independent variables y = dataset.iloc[:, 4].values # Dependent variable # Encode categorical data into numerical values (1, 2, 3) # For example; New york becomes 1 and Florida becomes 2 labelencoder_states = LabelEncoder() # We just want to apply this to the state column, since this has categorical data states_encoded = labelencoder_states.fit_transform(X[:, 3]) # …
has comment: http://stackoverflow.com/comment/84973239
has comment: http://stackoverflow.com/comment/84964666
has comment: http://stackoverflow.com/comment/84964584
answer count: 1
has comment: http://stackoverflow.com/comment/84964619
has comment: http://stackoverflow.com/comment/84981610
has comment: http://stackoverflow.com/comment/84964466
favorite count: 0
tagged with: regression
has comment: http://stackoverflow.com/comment/84964724
tagged with: machine-learning

http://stackoverflow.com/comment/85242788
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49118592
has text: This doesn't seem to be related to pandas or dataframes. You need a postgres driver (e.g. http://initd.org/psycopg/ ) and then you just loop through the JSON list/object, create an appropriate SQL query and run it.

http://stackoverflow.com/comment/85153296
comment on: http://stackoverflow.com/q/49073355
has text: Start with the itertools `product` method on the list with itself?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85110572
score: 0
comment on: http://stackoverflow.com/q/49052264
type: QuestionComment
type: Comment
has text: So the original dataframe contains: `id`, `start_date` and `end_date` and you want to create a new dataframe with: `id`, month and year taken from `start_date` and minutes that is the difference between `start_date` and `end_date`. Am I correct?

http://stackoverflow.com/a/49062251
has body: This is one solution. It should be efficient as there is no explicit merge or apply. merged_df['visit_date'] = pd.to_datetime(merged_df['visit_date']) date_info_df['calendar_date'] = pd.to_datetime(date_info_df['calendar_date']) s = date_info_df.set_index('calendar_date')['day_of_week'] t = date_info_df.set_index('day_of_week')['holiday_flg'] merged_df['day_of_week'] = merged_df['day_of_week'].fillna(merged_df['visit_date'].map(s)) merged_df['holiday_flg'] = merged_df['holiday_flg'].fillna(merged_df['day_of_week'].map(t)) Result air_store_id area_name day_of_week genre_name holiday_flg hpg_store_id \ 0 air_a1 Tokyo Tuesday Japanese 0.0 hpg_h1 1 air_a2 NaN Wednesday NaN 0.0 NaN 2 air_a3 NaN Thursday NaN 0.0 NaN 3 air_a4 NaN Saturday NaN 1.0 NaN latitude longitude reserve_datetime reserve_visitors visit_date \ 0 1234.0 5678.0 2017-04-22 11:00:00 25.0 2017-05-23 1 NaN NaN NaN 35.0 2017-05-24 2 NaN NaN NaN 45.0 2017-05-25 3 NaN NaN NaN NaN 2017-05-27 visit_datetime 0 2017-05-23 12:00:00 1 NaN 2 NaN 3 NaN Explanation s is a pd.Series mapping calendar_date to day_of_week from date_info_df. Use pd.Series.map, which takes pd.Series as an input, to update missing values, where possible.
type: Answer
has comment: http://stackoverflow.com/comment/85129607
has comment: http://stackoverflow.com/comment/85129885
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85130530
answers question: http://stackoverflow.com/q/49062176
downvote count: 0

http://stackoverflow.com/a/50209866
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/49054734
has body: Considering s2 as a switch, you can record flow tables using this (-O OpenFlow13 is optional): sh ovs-ofctl dump-flows s2 -O OpenFlow13 &gt; exampleLog.txt If you have rules in s2, the results would be: mininet@mininet-vm:~/mininet$ cat exampleLog.txt OFPST_FLOW reply (OF1.3) (xid=0x2): cookie=0x170000000000000, duration=9.458s, table=0, n_packets=6, n_bytes=588, priority=10,ip,in_port=1,nw_src=10.0.0.1,nw_dst=10.0.0.6 actions=output:4 cookie=0x170000001000000, duration=8.556s, table=0, n_packets=5, n_bytes=490, priority=10,ip,in_port=4,nw_src=10.0.0.6,nw_dst=10.0.0.1 actions=output:1 cookie=0x0, duration=42.627s, table=0, n_packets=20, n_bytes=1368, priority=0 actions=CONTROLLER:65535
type: Answer

http://stackoverflow.com/a/48980316
downvote count: 0
type: Answer
has body: Python dictionaries don't preserve their order, but there's another data type that does: OrderedDict, from the collections module.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48980285

http://stackoverflow.com/comment/85179449
type: Comment
has text: You don't need to convert to an array (explicitly).
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49087055

http://stackoverflow.com/q/49035035
type: AnsweredQuestion
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49035399
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49035153
possible better answer: http://stackoverflow.com/a/49035399
tagged with: export-to-csv
has title: CSV Modification Python
answer count: 3
tagged with: pandas
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49035153
tagged with: python
has answer: http://stackoverflow.com/a/49035681
has body: I am having difficulties with the processing of a CSV File. I need a pythonic solution that reads a CSV with rows like: And generates an output(preferably with the same CSV name) to produce this: (All the header information like Row1, Row2, Row3 should be removed and the value type row specifying Number should be removed as well) Is some kind of pandas/python solution viable for this? I've been trying but to no avail. Any guidance would also greatly help as I'm new to this.

http://stackoverflow.com/a/49103060
answers question: http://stackoverflow.com/q/49101504
has body: You will need to add __init__.py to your Football/football directory for python package discovery. Then, one thing you could do is add a setup.py at your project's root level and within that use find_packages() to recursively find packages to add to the python path. You'll then have to pip install your project into the virtual environment before running your tests. Tools like tox make accomplishing these steps easier by automatically setting up the virtual environment before calling your test commands. Another option is to use the monkeypatch fixture (a pytest builtin) and modify the PYTHONPATH for your tests. You could put this in your tests/conftest.py. Still you would need to create an __init__.py in your Football/football directory. @pytest.fixture(autouse=True) # run this automatically before tests def pythonpath(monkeypatch): path_to_project = "&lt;path to your project root&gt;" monkeypatch.setenv('PYTHONPATH', path_to_project)
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/85178979
has text: Just trying to get some help mate! stuck with this from quite a long time. Sorry to offend you.
comment on: http://stackoverflow.com/q/49086789
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85025610
comment on: http://stackoverflow.com/a/49009675
type: AnswerComment
has text: @SmartManoj: setting up the `set` takes most of that time. if you set it up once and test `in` many times you will see significant speedup. also note the difference between `1 in x` and `8 in x` for the tuple.
type: Comment
score: 1

http://stackoverflow.com/a/49001932
has comment: http://stackoverflow.com/comment/85008613
type: Answer
answers question: http://stackoverflow.com/q/49001784
score: 0
has body: You can try this: from requests import get urls = ['https://google.com', 'https://bing.com'] for url, res in zip(urls, map(get, urls)): if 'google' in res.text: # print 'https://google.com' here print url
has comment: http://stackoverflow.com/comment/85008739

http://stackoverflow.com/comment/85069237
type: QuestionComment
comment on: http://stackoverflow.com/q/49031951
has text: I already add some more useful info about the error
score: 0
type: Comment

http://stackoverflow.com/a/49134255
type: Answer
upvote count: 1
score: 1
has body: Solution is to set spark.sql.files.openCostInBytes and spark.sql.files.maxPartitionBytes to 60000000000 instead of 60g': $ pyspark --conf spark.sql.files.openCostInBytes=60g --conf spark.sql.files.maxPartitionBytes=60g
downvote count: 0
answers question: http://stackoverflow.com/q/49048212
accepted answer of: http://stackoverflow.com/q/49048212
type: AcceptedAnswer

http://stackoverflow.com/q/49100629
has comment: http://stackoverflow.com/comment/85206764
has body: I need help editing this function lenumerate() that takes a string (like 's') and returns a list of 2-item lists containing each word and it's length:[['But', 3], ['then', 4], ['of', 2], ... ['are', 3], ['nonmigratory', 12]] lenumerate(s) - convert 's' into list of 2-element lists: [[word, length],[word, length], ...] # Define the function first ... def lenumerate(s): l = [] # list for holding your result # Convert string s into a list of 2-element-lists Enter your code here return l ... then call the lenumerate() to test it text = "But then of course African swallows are nonmigratory" l = lenumerate(text) print("version 1", l) I think I need to spit the list and use the len() function, but I am not exactly sure how to go about using both of those in the most efficient way.
tagged with: python
has comment: http://stackoverflow.com/comment/85206639
has answer: http://stackoverflow.com/a/49100663
answer count: 4
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/85206683
downvote count: 3
score: -1
type: Question
has comment: http://stackoverflow.com/comment/85206804
has title: Converting list of 2-element lists: [[word, length], [word, length], ...]
has comment: http://stackoverflow.com/comment/85206509
has comment: http://stackoverflow.com/comment/85206518
has answer: http://stackoverflow.com/a/49100747
accepted answer: http://stackoverflow.com/a/49100663
tagged with: string-length
possible better answer: http://stackoverflow.com/a/49100677
has comment: http://stackoverflow.com/comment/85206774
has comment: http://stackoverflow.com/comment/85206992
has answer: http://stackoverflow.com/a/49100677
tagged with: string
has comment: http://stackoverflow.com/comment/85206444
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49100784
upvote count: 2

http://stackoverflow.com/q/48994802
answer count: 1
has answer: http://stackoverflow.com/a/49056760
score: -1
tagged with: sudo
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has title: How to use sudo chown command in python?
upvote count: 1
tagged with: python
has body: there are few servers running with python 2.4.3 where pexpect is not working.. Is there any way to place sudo password for sudo chown
tagged with: passwords
type: Question

http://stackoverflow.com/a/71142229
upvote count: 0
has body: To find hidden files matching a certain extension, you can try this glob.glob('/path/**/.*.ext') If you want to find all files in a folder glob.glob('/path/*') + glob.glob('/path/.*')
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49047402
downvote count: 1

http://stackoverflow.com/a/49075537
downvote count: 0
answers question: http://stackoverflow.com/q/49075236
upvote count: 2
type: Answer
has body: I guess there are two problems. First is a simple error in the code. x=x1+x2 adds the two arrays, however what you really want is to append one to the other. While this is just for the sake of the toy example, it should not matter in the real case, but it will lead to you seeing different images. Second: Of course you need to use the same bins for all histograms. So if you know the bins to use beforehands, e.g. because the minimum and maximum data are known, this makes it easy. import numpy as np import matplotlib.pyplot as plt #CHUNK OF DATA 1 x1=np.random.normal(-1,1,1000000) y1=np.random.normal(-1,1,1000000) #CHUNK OF DATA 2 x2=np.random.normal(-1,1,1000000) y2=np.random.normal(-1,1,1000000) #CLASSIC WAY x=np.concatenate((x1,x2)) y=np.concatenate((y1,y2)) plt.hist2d(x,y,bins=np.linspace(-3,3,101)) plt.savefig("histo1.png",dpi=200) #ALTERNATIVE WAY arr1, xedges1, yedges1=np.histogram2d(x1,y1,bins=np.linspace(-3,3,101)) arr2, xedges2, yedges2=np.histogram2d(x2,y2,bins=np.linspace(-3,3,101)) arr=arr1+arr2 plt.figure() plt.pcolormesh(xedges1,yedges1,arr.T) plt.savefig("histo2.png",dpi=200) plt.show() Both codes produce the same figure. In case you do not know the bins in advance or cannot rely on just setting them to a useful number, I fear you need to follow a two-step procedure: Read in the data chunk by chunk, find the maximum and minimum, update the overall maximum and minimum and store it for later use. Remove the chunks from the memory. Read in the data again chunk by chunk and do the histogramming as above, use the previously stored minimum and maximum for the bins in each case. A starting point may be this question: Numpy histogram of large arrays
score: 2

http://stackoverflow.com/a/48997584
upvote count: 6
has body: This isn't directly supported in pandas at the moment (see issue here), but there's something of a trick for doing it. The following is used mark contiguous groups, the comparison/shift is comparing each season to the prior value to mark the changes as 1, then the cumsum creates new groups for each change. df['marker'] = (df['season'] != df['season'].shift()).cumsum() From there, you can groupby and do whatever you want - for example for your case: df.groupby('marker').agg({'date': 'first', 'season': 'first', 'rainfall': lambda x: list(x)}) Out[14]: date season rainfall marker 1 1941-01-01 Winter [74.7, 69.1] 2 1941-03-01 Spring [76.2, 33.7, 51.3] 3 1941-06-01 Summer [25.7, 53.9, 91.8] 4 1941-09-01 Autumn [25.5, 106.2, 92.3] 5 1941-12-01 Winter [86.5, 114.0, 13.8] 6 1942-03-01 Spring [58.0, 42.5, 101.1] 7 1942-06-01 Summer [2.3, 70.2, 78.5] 8 1942-09-01 Autumn [146.8, 131.1, 19.8] 9 1942-12-01 Winter [183.9]
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48997350
score: 6
answers question: http://stackoverflow.com/q/48997350
type: AcceptedAnswer

http://stackoverflow.com/a/49034134
has body: First up, make sure you are hitting the debug button in spyder, not the run button. The run button does not trigger breakpoints, so you will need to hit debug, and then continue to get to the first breakpoint in your code. If that's failing, one option is to use the python debugger (pdb). This is entirely from the command-line, i.e. running debug commands and receiving debug information will also be through the command-line. class EnergyModel: __init__(self): # set breakpoint import pdb; pdb.set_trace() ... Running from the command-line will then pause execution within the __init__ method. Some of the commands you can issue pdb when the breakpoint is hit are listed here: https://nblock.org/2011/11/15/pdb-cheatsheet/ Update #1 Example of a function that spyder can trigger breakpoints on def test(a_string): print(a_string) # breakpoint set here will be hit test("hello world")
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85085846
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49033806
accepted answer of: http://stackoverflow.com/q/49033806
downvote count: 0
has comment: http://stackoverflow.com/comment/85077257

http://stackoverflow.com/comment/84947417
comment on: http://stackoverflow.com/q/48971008
score: 0
type: Comment
type: QuestionComment
has text: any error generated or what ? what happens after running above code ?

http://stackoverflow.com/comment/85180663
type: QuestionComment
has text: Please don't post pictures of code and error messages on SO, post the text here on SO.
type: Comment
comment on: http://stackoverflow.com/q/49087547
score: 0

http://stackoverflow.com/a/49003860
downvote count: 0
has comment: http://stackoverflow.com/comment/85057919
has comment: http://stackoverflow.com/comment/85015627
type: Answer
has comment: http://stackoverflow.com/comment/85029908
has comment: http://stackoverflow.com/comment/85016234
score: 12
has comment: http://stackoverflow.com/comment/85014326
has body: Use numpy.add.at: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.array([1,2,3]) &gt;&gt;&gt; B = np.array([10,20,30]) &gt;&gt;&gt; I = np.array([0,1,1]) &gt;&gt;&gt; &gt;&gt;&gt; np.add.at(A, I, B) &gt;&gt;&gt; A array([11, 52, 3]) Alternatively, np.bincount: &gt;&gt;&gt; A = np.array([1,2,3]) &gt;&gt;&gt; B = np.array([10,20,30]) &gt;&gt;&gt; I = np.array([0,1,1]) &gt;&gt;&gt; &gt;&gt;&gt; A += np.bincount(I, B, minlength=A.size).astype(int) &gt;&gt;&gt; A array([11, 52, 3]) Which is faster? Depends. In this concrete example add.at seems marginally faster, presumably because we need to convert types in the bincount solution. If OTOH A and B were float dtype then bincount would be faster.
upvote count: 12
accepted answer of: http://stackoverflow.com/q/49003798
answers question: http://stackoverflow.com/q/49003798
has comment: http://stackoverflow.com/comment/85015479
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85014058

http://stackoverflow.com/comment/85198767
comment on: http://stackoverflow.com/a/49090806
score: 0
type: AnswerComment
has text: @Tom1416 Here is an example of grouping those separate tests inside a class: https://bpaste.net/show/f31fb75b6dff
type: Comment

http://stackoverflow.com/comment/85205917
type: Comment
comment on: http://stackoverflow.com/a/49100334
has text: @DeliriousLettuce what about `letters` is a global variable?
type: AnswerComment
score: 0

http://stackoverflow.com/q/49036698
score: 0
tagged with: pandas
tagged with: finance
tagged with: interpolation
has body: I have a time-series of dates and interest rates on a pandas dataframe. Below is the list: dates rates 0 3/1/2018 0.014553 1 3/8/2018 0.014951 2 4/2/2018 0.016987 3 5/1/2018 0.018719 4 6/1/2018 0.020044 5 9/4/2018 0.021602 6 12/3/2018 0.022361 7 3/1/2019 0.023080 8 6/3/2019 0.023726 9 9/3/2019 0.024333 10 12/2/2019 0.024811 11 3/2/2020 0.025234 12 3/1/2021 0.026456 13 3/1/2022 0.027126 14 3/1/2023 0.027541 15 3/1/2024 0.027898 16 3/3/2025 0.028206 17 3/2/2026 0.028486 18 3/1/2027 0.028748 19 3/1/2028 0.028998 20 3/1/2030 0.029444 21 3/1/2033 0.029850 22 3/1/2038 0.030126 23 3/2/2043 0.030019 24 3/2/2048 0.029778 I'd like to interpolate a rate for any date (for example - 03/21/2021) that falls b/n the min and max dates. And I'd like to achieve this using the interpolate method of pandas. How can I do it?
tagged with: python
type: AnsweredQuestion
tagged with: quantitative-finance
type: Question
answer count: 1
has title: Interpolate from Existing Time-series Data - Python
has answer: http://stackoverflow.com/a/49036856
accepted answer: http://stackoverflow.com/a/49036856

http://stackoverflow.com/q/49100872
downvote count: 0
favorite count: 0
tagged with: windows
tagged with: python
type: AnsweredQuestion
score: 1
has title: Python script with flask server takes too long to exit on Windows
type: Question
accepted answer: http://stackoverflow.com/a/49459200
tagged with: flask
has body: I'm new to Python. As a part of a project I'm trying to deploy a Flask server locally, through the Windows command line. My Python version is 3.6.0. The code: from flask import Flask app = Flask(__name__) @app.route('/') def index(): return ' Hello World! ' if __name__ == "__main__": app.run() The problem: It's about killing the script as it runs. Launching this script with python deploy.py and hitting CTRL+C shuts it off. BUT - if I hit access that '/' route via the browser once or more, and a moment later try to kill the script in the same manner, then it would take about 10 seconds of nothing until it responds and is finally killed. Why is this happening? How can I shut the server off immediately each time for continuous and quick development? Thanks!!
has answer: http://stackoverflow.com/a/49459200
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/85153719
has text: Oh I know what it is I think, I will answer here shortly.
comment on: http://stackoverflow.com/q/49073298
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49121066
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49120985
has body: The problem comes from the y[x] since y is an int. You probably want to initialize heightarray as a 2D list and do heightarray[y][x] = .... See here for more details: https://www.cs.cmu.edu/~112/notes/notes-2d-lists.html
downvote count: 0
type: Answer

http://stackoverflow.com/q/49017469
type: UnansweredQuestion
tagged with: os.walk
has comment: http://stackoverflow.com/comment/85040089
has comment: http://stackoverflow.com/comment/85044503
tagged with: yield-from
type: Question
has body: My goal is to store all files and directories in a structured data tree, where each: directory is a node file is a leaf My code below works fine. However, I only take one step at a time and interrupt/restart the walking process for every directory. (see step_in() method) Apparently it is possible and considered "advanced" to break into the process of an iteration itself and work with it. Therefore my question is, is it possible to "break into" the os.walk process and yield what's necessary? import os import sys import inspect DEBUG = True def report(*args,**kwargs): global DEBUG if DEBUG: print(*args,**kwargs) class directory: def __init__(self, path): self.path = path @property def name(self): return os.path.basename(self.path) def __repr__(self): ID = hex(id(self)) return "&lt;directory \"{:}\" at {}&gt;".format(self.name,ID) def step_in(self): """Step into the dir and find all files/dirs. Step into the directory path and search for: - directories --&gt; add string name to children (SEMI CHILD) - and files --&gt; add string name to leafs """ for p,d,f in os.walk(self.path): self.children = d report("---&gt;kids found : {}".format(d)) self.leafs = f report("---&gt;leafs found: {}".format(f)) return p class walker: def __init__(self, root_path): self.root = directory(root_path) def walk(self, target=None): """Walk through all dirs and create tree. Recursive process with root directory as initial directory. """ if not(target): target = self.root path = target.step_in() for i in range(len(target.children)): #get the next path next_path = os.path.join(path,target.children[i]) report("\nnext is: {}".format(next_path)) #save dir by replacing the string child with an actual child target.children[i] = directory(next_path) #walk into that child self.walk(target.children[i]) if __name__ == "__main__": w = walker('/Users/xxx/test/xxx') w.walk()
tagged with: iteration
has comment: http://stackoverflow.com/comment/85044485
has title: Breaking into the iteration process of os.walk()
tagged with: python
answer count: 0
score: 0

minimax
type: Tag
tags question: http://stackoverflow.com/q/48989490
tag name: minimax
tags question: http://stackoverflow.com/q/49097182
tags question: http://stackoverflow.com/q/48964502

set-theory
type: Tag
tags question: http://stackoverflow.com/q/49118597
tag name: set-theory

http://stackoverflow.com/q/49055059
type: Question
has comment: http://stackoverflow.com/comment/85287827
has answer: http://stackoverflow.com/a/49172216
has body: I'm using squishtest library for manipulating Qt application from my Python code and attempting to use event handlers as follows: import squishtest def handle_mouse_event(event): print 'Clicked!' squishtest.startApplication('application') squishtest.installEventHandler('QMouseEvent', handle_mouse_event) Unfortunately this doesn't work, i.e. nothing happens on clicking elements inside the app, however it works in case I run equivalent of this code inside the Squish IDE in Squish runtime: import squish def handle_mouse_event(event): print 'Clicked!' squish.startApplication('application') squish.installEventHandler('QMouseEvent', handle_mouse_event) What is the difference and how to get event handlers working with squishtest? Python 2.7.14, Squish 6.3.1, Ubuntu 16.04
tagged with: squish
answer count: 1
downvote count: 0
favorite count: 0
has title: Using Qt Event Handlers in squishtest
accepted answer: http://stackoverflow.com/a/49172216
tagged with: python
has comment: http://stackoverflow.com/comment/85241672
tagged with: qt
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/49042185
has title: Many-to-one relationship in Django
favorite count: 0
type: Question
tagged with: django
tagged with: python
answer count: 1
has body: I'm new to django thus the question. This is my Location object, class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) And this is my modified User object class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(max_length=255, null=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_mobile_verified = models.BooleanField(default=False) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) This is the User Registration API view class RegisterView(views.APIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() subject = "Please Activate Your Account!" token = self._generate() link = HOST + PREFIX + str(user.id) + SUFFIX + token message = 'Please use the following link to activate your account.\n\n{}'.format(link) from_email = settings.EMAIL_HOST_USER to_list = [user.email, 'melissa@gmail.com'] send_mail(subject, message, from_email, to_list, fail_silently=True) Token.objects.create(user=user, token=token) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this is the relevant url url(r'^register/$', RegisterView.as_view(), name='register') Now I want to modify this endpoint to take a location id as a path param and then add the logic in my UserCreation function that the user is added to the location as described by the id. Can someone help me do this ?
upvote count: 3
has answer: http://stackoverflow.com/a/49042234
downvote count: 0
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/49042234
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/85100150
type: Comment
has text: If this is something you need to do regularly, you might consider another tree algorithm. MPTT (via django-mptt) stores the parent_id as a field on the model, so no extra lookups are required.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49041669

http://stackoverflow.com/comment/85204484
has text: @DeliriousLettuce it's not identical, it has an explanation. Which means it should have been a comment on your answer reminding you to include it, but meh.
type: AnswerComment
comment on: http://stackoverflow.com/a/49099616
type: Comment
score: 1

http://stackoverflow.com/a/48980679
type: AcceptedAnswer
downvote count: 0
has body: Python and Java are fundamentally very different languages, with Python being much more like a scripting language than compiled (even though it does get compiled on-the-fly). Also, Python doesn't really have quite the concept of "an unchanging variable...", at least not by variable name. Variable names are essentially pointers to any type of data (see: dynamic typing) and without some special python decorators you can always change the value of a variable, sometimes quite to your detriment. More to your point though, because of its scripting nature (and that it can be executed interactively), the order of things matters: &gt;&gt;&gt; def test(): ... print x ... &gt;&gt;&gt; test() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in test NameError: global name 'x' is not defined &gt;&gt;&gt; x = 1 &gt;&gt;&gt; test() 1 &gt;&gt;&gt; In this case, the global x in the function test is just a pointer and it doesn't matter that x doesn't exist yet because you haven't tried to run test. This might seem counter-intuitive when coming from a strongly-typed and compiled language, but it allows for a lot of nice things like dynamic imports that will only load modules as the functions are used: &gt;&gt;&gt; def dyn_import(): ... import random ... for i in xrange(5): ... print random.random() ... &gt;&gt;&gt; random.random() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'random' is not defined &gt;&gt;&gt; dyn_import() 0.246957404578 0.302236192705 0.614960539467 0.0928052533036 0.389804554563 &gt;&gt;&gt; random.random() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'random' is not defined If every variable needed to be fully defined before being used inside a function, then defining dyn_import would fail unless random was loaded and it was understood what random.random() means. In this case, it is not loaded un…
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48979657
score: 1
answers question: http://stackoverflow.com/q/48979657
has comment: http://stackoverflow.com/comment/84966554
has comment: http://stackoverflow.com/comment/84966698

http://stackoverflow.com/comment/85725153
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49355161
has text: But the main point of this answer being that using `mpl_cairo` would be faster than using the current cairo backend with [your fix](https://github.com/matplotlib/matplotlib/pull/10828/files) (as proposed in my answer), is that correct?
type: AnswerComment

http://stackoverflow.com/q/49096283
has body: I use the following method to maintain a Keep-Alive connection through a proxy to the target site. import http.client proxies = {"https": "https://user:pass@host:port"} url = urlparse(proxies["https"]) auth = '%s:%s' % (url.username, url.password) headers['Proxy-Authorization'] = 'Basic '+base64.b64encode(auth.encode('utf-8')).decode() conn = http.client.HTTPSConnection(proxy.hostname, proxy.port) conn.set_tunnel("target_site.com",headers=p_headers) conn.request("POST", "/tapi/", payload, headers) However, HTTPSConnection is not thread safe. I am trying to do connection through urllib3 so that I will be able to use multiprocessing. My code doesn't work. What is the wright way to do it? import urllib3 default_headers = urllib3.make_headers(proxy_basic_auth="user:pass") conn=urllib3.HTTPSConnectionPool('https://target_site.com',maxsize=2, _proxy="https://host:port/", _proxy_headers=default_headers) conn.request("POST", "/tapi/",fields=payload, headers=headers)
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
score: 2
tagged with: keep-alive
answer count: 0
downvote count: 0
has title: Python Keep-Alive proxy connection with urrlib3
type: Question
upvote count: 2
tagged with: proxy
tagged with: urllib3
favorite count: 0

http://stackoverflow.com/q/49081980
favorite count: 0
possible better answer: http://stackoverflow.com/a/49082049
tagged with: python-internals
has answer: http://stackoverflow.com/a/49082049
has comment: http://stackoverflow.com/comment/85169419
tagged with: python
tagged with: dictionary
tagged with: instance-variables
accepted answer: http://stackoverflow.com/a/49082043
type: AnsweredQuestion
has title: built in __dict__ is returning names of attributes with class names as prefix
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85169471
type: Question
linked to: http://stackoverflow.com/q/1301346
duplicate of: http://stackoverflow.com/q/1301346
has answer: http://stackoverflow.com/a/49082043
has body: class Enrollment(object): def __init__(self,enrollmentId=None, enrollmentReference=None): self.enrollmentId = enrollmentId self.enrollmentReference = enrollmentReference @property def enrollmentId(self): return self.__enrollmentId @enrollmentId.setter def enrollmentId(self, enrollmentId): self.__enrollmentId = enrollmentId @property def enrollmentReference(self): return self.__enrollmentReference @enrollmentReference.setter def enrollmentReference(self, enrollmentReference): self.__enrollmentReference = enrollmentReference If i now try to print the attributes of the above class: print(Enrollment().__dict__) It prints the attributes prefixed with class name as below: {'_Enrollment__enrollmentId': None, '_Enrollment__enrollmentReference': None} Note: If I remove object as the super class, all works well and it prints the attributes correctly as below: {'enrollmentId': None, 'enrollmentReference': None} I have been been wrapping my head around this for 2 days now with no luck. Not able to understand why the class name is prefixed to attributes. I need to serialize the Enrollment object to JSON.
answer count: 2
downvote count: 0

http://stackoverflow.com/q/49119793
tagged with: coroutine
type: Question
answer count: 2
score: 0
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/49119860
possible better answer: http://stackoverflow.com/a/49226915
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49226915
has body: I was wondering how concurrency works in python 3.6 with asyncio. My understanding is that when the interpreter executing await statement, it will leave it there until the awaiting process is complete and then move on to execute the other coroutine task. But what I see here in the code below is not like that. The program runs synchronously, executing task one by one. What is wrong with my understanding and my impletementation code? import asyncio import time async def myWorker(lock, i): print("Attempting to attain lock {}".format(i)) # acquire lock with await lock: # run critical section of code print("Currently Locked") time.sleep(10) # our worker releases lock at this point print("Unlocked Critical Section") async def main(): # instantiate our lock lock = asyncio.Lock() # await the execution of 2 myWorker coroutines # each with our same lock instance passed in # await asyncio.wait([myWorker(lock), myWorker(lock)]) tasks = [] for i in range(0, 100): tasks.append(asyncio.ensure_future(myWorker(lock, i))) await asyncio.wait(tasks) # Start up a simple loop and run our main function # until it is complete loop = asyncio.get_event_loop() loop.run_until_complete(main()) print("All Tasks Completed") loop.close()
has title: Understanding Python Concurrency with Asyncio
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49119860
downvote count: 1

http://stackoverflow.com/comment/85186524
has text: Hmm, I have no idea what that stuff is, but clock rate still rather sounds like a number to me, not like a hex string. Are you sure you don't want that number instead? I added a bit to my answer...
score: 0
comment on: http://stackoverflow.com/q/49089834
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49067921
has comment: http://stackoverflow.com/comment/85155382
answers question: http://stackoverflow.com/q/49067775
has comment: http://stackoverflow.com/comment/85155521
has body: Use this: data_ids = [x['href'].split('=')[1] for x in soup.find_all('a', {'class': 'icon-font-before icon-chain-solid-before', 'href': True})] print(data_ids) Output: ['22614089', '22622854', '22616496', '22601480', '22611197', '22600498', '22605808', '22602601', '22602543', '22594071', '22595982', '22593725', '22591441', '22553315', '22584758', '22582155', '22585128', '22585477', '22587617']
type: Answer
has comment: http://stackoverflow.com/comment/85156107
downvote count: 0
has comment: http://stackoverflow.com/comment/85155911
has comment: http://stackoverflow.com/comment/85141365
has comment: http://stackoverflow.com/comment/85156076
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85150541
accepted answer of: http://stackoverflow.com/q/49067775

http://stackoverflow.com/q/49047133
accepted answer: http://stackoverflow.com/a/49047833
has comment: http://stackoverflow.com/comment/85098820
has comment: http://stackoverflow.com/comment/85098736
type: AnsweredQuestion
has title: Why does python read my file twice?
has comment: http://stackoverflow.com/comment/85099466
has comment: http://stackoverflow.com/comment/85098710
score: -1
downvote count: 5
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49047833
has body: I'm trying to read a binary file bit by bit because it may be large. My code is: import bz2 read_buffer_size = 10000 with open(r'C:\Python27\python.exe', 'rb') as f: data = f.read(read_buffer_size) while data: print len(data) data = f.read(read_buffer_size) and it gives me output of: 100 10000 10000 8160 10000 10000 8160 In this case the file is 28160 bytes, so I was expecting to see: 10000 10000 8160 Why is python reading my file twice?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85098903
has comment: http://stackoverflow.com/comment/85098854
tagged with: python

http://stackoverflow.com/comment/84982949
score: 0
type: AnswerComment
has text: @Universalis How are those 10x5?
comment on: http://stackoverflow.com/a/48988659
type: Comment

http://stackoverflow.com/comment/85045931
comment on: http://stackoverflow.com/q/49020250
type: QuestionComment
type: Comment
has text: Curiously, "\d" isn't a valid escape sequence, so python should still be treating it as the 2 characters. Did your real case start with a different letter?
score: 0

http://stackoverflow.com/comment/85088949
type: AnswerComment
has text: @RamazanPolat Where should the function definition for new_method as shown in the Wrapper class example (in my post) go?
comment on: http://stackoverflow.com/a/49020695
type: Comment
score: 0

http://stackoverflow.com/comment/85033917
comment on: http://stackoverflow.com/q/49013719
has text: Can the multiplier in your padder be negative?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49014806
has comment: http://stackoverflow.com/comment/85034706
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: gettext
has comment: http://stackoverflow.com/comment/85034499
has comment: http://stackoverflow.com/comment/85034401
score: 1
type: Question
has comment: http://stackoverflow.com/comment/85034759
downvote count: 0
has comment: http://stackoverflow.com/comment/85034683
has comment: http://stackoverflow.com/comment/85034577
tagged with: python
tagged with: plugins
has body: |-- locale | `-- es | `-- LC_MESSAGES | |-- pluginloader.mo | `-- pluginloader.po |-- pluginloader.py `-- plugins `-- PluginA |-- first_plugin | `-- __init__.py |-- manifest.json `-- po |-- es.po `-- first_plugin.pot I have above structure for my app(pluginloader) which uses it's own tranlation from locale directory. I would like to use pluginA translation es.po in pluginA. How i can do that? I am importing plugins in pluginloader by following code. ` import imp import os import gettext t = gettext.translation('pluginloader', localedir='locale', languages=['es'], fallback=True) t.install() PluginFolder = "./plugins" MainModule = "__init__" print(_("Hello world")) def getPlugins(): plugins = [] possibleplugins = os.listdir(PluginFolder) for i in possibleplugins: location = os.path.join(PluginFolder, i) for j in os.listdir(location): location1 = os.path.join(location, j) if not os.path.isdir(location1) or not MainModule + ".py" in os.listdir(location1): continue info = imp.find_module(MainModule, [location1]) plugins.append({"name": i, "info": info}) return plugins def loadPlugin(plugin): return imp.load_module(MainModule, *plugin["info"]) for i in getPlugins(): plugin = loadPlugin(i) plugin.run()`
tagged with: internationalization
favorite count: 0
has title: How to use plugin translation along with application own translation?

http://stackoverflow.com/a/49075920
type: Answer
has comment: http://stackoverflow.com/comment/85157770
accepted answer of: http://stackoverflow.com/q/49075522
upvote count: 4
answers question: http://stackoverflow.com/q/49075522
score: 4
has body: Well one problem is you have (nolock) in the wrong place. It should immediately follow a table alias, not the join condition: Also don't you need to add concatenation operators when building this SQLCommand string? I've never used Python, but if this were .net code, it wouldn't even compile. SQLCommand = ("SELECT TP.UserID, Phone " + "FROM dbo.SEC_UserProfile as TP (nolock) INNER JOIN dbo.SEC_User as TE (nolock)" + "ON TP.UserID = TE.UserID " + "WHERE TP.UserID LIKE ?")
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49042293
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49042558
tagged with: python
has title: Pandas: value_counts and cut with groupby multiindex
has body: With a DataFrame like this: time location 1 A 1 A 2 B 4 A 9 A 12 B 12 B 12 B 18 A I can get a count of the number of occurrences within a time bin by doing the following cut and value_counts operations: d = {'time': [1,1,2,4,9,12,12,12,18], 'location': ['A','A','B','A','A','B','B','B','A']} df = pd.DataFrame(d) time_bins = np.arange(0, 100, 10) cut_frame = pd.cut(df.time, bins=time_bins) counts = pd.value_counts(cut_frame,sort=False) count_frame = pd.DataFrame(counts) count_frame.index.name = 'time_window' The resulting DataFrame looks like this: time_window time (0, 10] 5 (10, 20] 4 How can I break this down further by the location series to get something like this with a MultiIndex? location time_window A (0, 10] 4 (10, 20] 1 B (0, 10] 1 (10, 20] 3 Or this? time_window location time (0, 10] A 4 (0, 10] B 1 (10, 20] A 1 (10, 20] B 3
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49042558
type: Question
score: 0

http://stackoverflow.com/comment/85214094
score: 0
comment on: http://stackoverflow.com/q/49065020
type: Comment
has text: I tried the suggestions from the Thread you linked. But if I'd already solved my Problem with the suggestions I wouldn't ask here ;)
type: QuestionComment

http://stackoverflow.com/q/49004307
tagged with: cython
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/49004448
has title: Cython define fixed length array of pointers
has answer: http://stackoverflow.com/a/49012635
accepted answer: http://stackoverflow.com/a/49012635
favorite count: 0
possible better answer: http://stackoverflow.com/a/49004448
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am fairly new to Cython and haven't done any C in a long time, so this may be fairly obvious, but I don't know how to go about doing it. Consider the simple example of a binary tree: ctypedef struct binary_node_t: double value binary_node_t[2] * children Sure, I could just have binary_node_t * left and binary_node_t * right, but for my problem, I have more children, and it would be tedious, so I'd really like to have a fixed size array of pointers. So when I'd want to initialize the node and its children, I'd like to do something like this: cdef binary_node_t * root = &lt;binary_node_t *&gt;PyMem_Malloc(sizeof(binary_node_t)) root.children = &lt;binary_node_t[2] *&gt;PyMem_Malloc(2 * sizeof(binary_node_t)) The issue I'm facing is that binary_node_t[2] * doesn't seem to be valid and gives the following error during compilation error: array type has incomplete element type ‘..._binary_node_t {aka struct ..._binary_node_t}’ ..._binary_node_t (*children)[2]; ^~~~~~~~ What is the proper way to do what I'm trying to do, namely define a fixed length array of pointers to structs and allocating them when needed. EDIT 1 I've also tried the standard C initialization, like so: ctypedef struct binary_node_t: double value binary_node_t * children[2] .... cdef binary_node_t * root = &lt;binary_node_t *&gt;PyMem_Malloc(sizeof(binary_node_t)) root.children = &lt;binary_node_t * [2]&gt;PyMem_Malloc(2 * sizeof(binary_node_t)) but this results in the following error error: cast specifies array type memcpy(&amp;(__pyx_v_root-&gt;children[0]), ((..._binary_node_t *[2])PyMem_Malloc((2 * (sizeof(..._binary_node_t))))), sizeof(__pyx_v_root-&gt;children[0]) * (2));
downvote count: 0

http://stackoverflow.com/q/48967112
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84939996
type: Question
has answer: http://stackoverflow.com/a/48967247
has title: Performance issues with pandas iterrows
has body: I am having performance issues with iterrows in on my dataframe as I start to scale up my data analysis. Here is the current loop that I am using. for ii, i in a.iterrows(): for ij, j in a.iterrows(): if ii != ij: if i['DOCNO'][-5:] == j['DOCNO'][4:9]: if i['RSLTN1'] &gt; j['RSLTN1']: dl.append(ij) else: dl.append(ii) elif i['DOCNO'][-5:] == j['DOCNO'][-5:]: if i['RSLTN1'] &gt; j['RSLTN1']: dl.append(ij) else: dl.append(ii) c = a.drop(a.index[dl]) The point of the loop is to find 'DOCNO' values that are different in the dataframe but are known to be equivalent denoted by the 5 characters that are equivalent but spaced differently in the string. When found I want to drop the smaller number from the associated 'RSLTN1' column. Additionally, my data set may have multiple entries for a unique 'DOCNO' that I want to drop the lower number 'RSLTN1' result. I was successful running this will small quantities of data (~1000 rows) but as I scale up 10x I am running into performance issues. Any suggestions? Sample from dataset In [107]:a'DOCNO','RSLTN1'.sample(n=5) Out[107]: DOCNO RSLTN1 6815 MP00064958 72386.0 218 MP0059189A 65492.0 8262 MP00066187 96497.0 2999 MP00061663 43677.0 4913 MP00063387 42465.0
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/44117326
answer count: 1
has comment: http://stackoverflow.com/comment/84940053
accepted answer: http://stackoverflow.com/a/48967247
has comment: http://stackoverflow.com/comment/84939960

http://stackoverflow.com/comment/85039498
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49017230
has text: Are there duplicate keys in the dictionaries in `data_set`?
score: 0

http://stackoverflow.com/q/49058067
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49059016
tagged with: python
linked to: http://stackoverflow.com/q/40391316
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49678536
tagged with: scrapy
has comment: http://stackoverflow.com/comment/85121871
type: Question
has body: I have a spider which exports data to different CSV files (per the names of the class definitions as defined in the spider class). However, I also wanted to keep the order of the fields in a specific order as they were being processed and exported into their different CSV files. For example, this is my items.py: import scrapy class first_class_def_Item(scrapy.Item): f1 = scrapy.Field() # f1 an arbitrary id used for both class definition items f2 = scrapy.Field() f3 = scrapy.Field() class second_class_def_Item(scrapy.Item): f1 = scrapy.Field() f4 = scrapy.Field() f5 = scrapy.Field() f6 = scrapy.Field() This is my pipelines.py: from scrapy.exporters import CsvItemExporter from scrapy import signals from pydispatch import dispatcher def item_type(item): # The CSV file names are used (imported) from the scrapy spider. # For this example, I just want to keep "first_class_def.csv" without, # the "_item", as in "first_class_def_Item.csv" as defined in the main scrapy spider return type(item).__name__.replace('_Item','') class SomeSitePipeline(object): # For simplicity, I'm using the same class def names as found in the, # main scrapy spider and as defined in the items.py SaveTypes = ['first_class_def','second_class_def'] def __init__(self): dispatcher.connect(self.spider_opened, signal=signals.spider_opened) dispatcher.connect(self.spider_closed, signal=signals.spider_closed) def spider_opened(self, spider): self.files = dict([ (name, open("/somefolder/"+name+'.csv','wb')) for name in self.SaveTypes ]) self.exporters = dict([ (name,CsvItemExporter(self.files[name])) for name in self.SaveTypes ]) [e.start_exporting() for e in self.exporters.values()] def spider_closed(self, spider): [e.finish_exporting() for e in self.exporters.values()] [f.close() for f in self.files.values()] def process_item(self, item, spider): typesItem = item_type(item) if typesItem in set(self.SaveTypes): self.exporters[typesItem].export_item(item) return item And this is my spider.py: import os impo…
tagged with: scrapy-pipeline
answer count: 2
has answer: http://stackoverflow.com/a/49059016
accepted answer: http://stackoverflow.com/a/49678536
downvote count: 0
has title: How To Keep/Export Field Items in Specific Order Per Spider Class Definition, Utilizing The Items Pipeline in Scrapy
favorite count: 0

http://stackoverflow.com/a/49057183
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49054827
type: AcceptedAnswer
has body: Use: canvas = tkinter.Canvas(...) canvas['highlightthickness'] = 0 or specifically: grid[-1][-1]['highlighthickness'] = 0
accepted answer of: http://stackoverflow.com/q/49054827
type: Answer

http://stackoverflow.com/comment/85243158
type: QuestionComment
comment on: http://stackoverflow.com/q/49116570
has text: If your reuse logic is working properly, it could also mean that there is some other error because just a 1000 addition operations shouldn't take up several gigabytes. Maybe you are actually creating new constant tensors accidentally somewhere, or have things in your graph that should rather be fed in as placeholders. I suggest you to also plot the graph in Tensorboard to verify such things when it still works with a smaller number of iterations in your loop.
score: 0
type: Comment

http://stackoverflow.com/comment/85167304
type: AnswerComment
has text: Updated the function to reduce_sum(). That should fix it
comment on: http://stackoverflow.com/a/49080705
type: Comment
score: 1

http://stackoverflow.com/a/49083334
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85172895
downvote count: 0
has body: This is the best intuitive explanation of backprop that I know of.Highly recommended. 1.What loss function are you using? If you use cross-entropy loss(the one with log in it) then the delta3 has to be just (a3 - target).For Least squares loss,the other one is correct.Use only (a3 - y_train[j]) in your code. 2.No the learning rate and 1/m are not optional. 3.The biases are supposed to be updated always. 4.Try to initialize the biases and weights seperatedly.I find it much easier to understand. Example Forward pass: Z1 = Weights*X + biases A1 = sigmoid(Z1) Refer to this notebook .I have implemented the exact same thing using just numpy and it works. Corrections: delta3 = a3 - y_train[j] delta2 = np.multiply((weights2.T * delta3), sigmoid_prime(z1)) where sigmoid_prime is: def sigmoid_prime(z): return sigmoid(z)*(1-sigmoid(z)) and z1 is a1.dot(weights1).Your feed forward function needs to return this value also so that you can use it here. Also since you are using stochastic gradient descent(and not mini-batch gradient descent) your m is actually 1 here.So you should remove the 1/m term. Initialize the weights using np.random.normal and not np.random.random Do not get rid of the bias terms. Read up on back-prop on the link above and also here
score: 1
accepted answer of: http://stackoverflow.com/q/49082085
answers question: http://stackoverflow.com/q/49082085
has comment: http://stackoverflow.com/comment/85172142
has comment: http://stackoverflow.com/comment/85172791

http://stackoverflow.com/a/49071215
has comment: http://stackoverflow.com/comment/85147846
type: Answer
score: 1
has body: You can read one line at a time with the readline function: with open('data.txt', 'r') as myfile: line1=myfile.readline() data=myfile.readline().replace('\n', '') For some arbitrary line you can iterate through the file until you get to that line: with open('data.txt', 'r') as myfile: dataline = 4 # any number less than or equal to the number of lines in the file for line in range(dataline - 1): myfile.readline() data=myfile.readline().replace('\n', '')
has comment: http://stackoverflow.com/comment/85147716
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49071184

http://stackoverflow.com/q/49075248
has comment: http://stackoverflow.com/comment/85156678
type: Question
has comment: http://stackoverflow.com/comment/85156687
score: 0
answer count: 0
type: UnansweredQuestion
has title: python statsmodel.api error: invalid syntax
tagged with: python
has comment: http://stackoverflow.com/comment/85156653
tagged with: statsmodels
has body: I'm using some simple syntax copied from a similar example, but I get an invalid syntax error on my 'y' variable and I don't understand why? import pandas as pd import os df = pd.read_excel(os.path.expanduser("~/Desktop/ML_Wheat_Input.xlsx")) df.head() Price US S-to-U World S-to-U Date 0 203.41 0.451164 0.316851 2015-11-01 1 206.34 0.416095 0.318938 2015-10-01 2 193.97 0.409023 0.316268 2015-09-01 3 187.87 0.392560 0.309860 2015-08-01 4 207.38 0.361605 0.302978 2015-07-01 import statsmodels.api as sm x = df[['US S-to-U', 'World S-to-U'] y = df'Price' X1 = sm.add_constant(X) est = sm.OLS(y, X1).fit() est.summary()

beautifulsoup
tags question: http://stackoverflow.com/q/49088585
tags question: http://stackoverflow.com/q/49085421
tags question: http://stackoverflow.com/q/49024296
tags question: http://stackoverflow.com/q/49120376
tags question: http://stackoverflow.com/q/49046234
tags question: http://stackoverflow.com/q/49073323
tags question: http://stackoverflow.com/q/48976977
tags question: http://stackoverflow.com/q/49088106
tags question: http://stackoverflow.com/q/48997998
tags question: http://stackoverflow.com/q/49117304
tags question: http://stackoverflow.com/q/48975744
tags question: http://stackoverflow.com/q/48995133
tags question: http://stackoverflow.com/q/49046887
tags question: http://stackoverflow.com/q/48970399
tags question: http://stackoverflow.com/q/49059182
tags question: http://stackoverflow.com/q/49118209
tags question: http://stackoverflow.com/q/49019168
tags question: http://stackoverflow.com/q/49003764
tags question: http://stackoverflow.com/q/48965148
tags question: http://stackoverflow.com/q/49030014
tags question: http://stackoverflow.com/q/49088880
tags question: http://stackoverflow.com/q/49038444
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/49059489
tags question: http://stackoverflow.com/q/49005853
tags question: http://stackoverflow.com/q/48983551
tags question: http://stackoverflow.com/q/48994782
tags question: http://stackoverflow.com/q/49084094
tags question: http://stackoverflow.com/q/49074805
tags question: http://stackoverflow.com/q/49077430
tags question: http://stackoverflow.com/q/49105642
tags question: http://stackoverflow.com/q/49047840
tags question: http://stackoverflow.com/q/48997893
tags question: http://stackoverflow.com/q/48977468
tags question: http://stackoverflow.com/q/48975310
tags question: http://stackoverflow.com/q/49096001
tags question: http://stackoverflow.com/q/48977900
tags question: http://stackoverflow.com/q/49016527
tags question: http://stackoverflow.com/q/49010813
tags question: http://stackoverflow.com/q/49078435
tags question: http://stackoverflow.com/q/49035188
tags question: http://stackoverflow.com/q/49075563
tags question: http://stackoverflow.com/q/49018025
tags question: http://stackoverflow.com/q/48992650
tags question: http://stackoverflow.com/q/49108672
tags question: http://stackoverflow.com/q/49076283
tags question: http://stackoverflow.com/q/49019048
tags question: http://stackoverflow.com/q/49043857
type: Tag
tags question: http://stackoverflow.com/q/48985758
tags question: http://stackoverflow.com/q/48975202
tags question: http://stackoverflow.com/q/48999772
tags question: http://stackoverflow.com/q/49037564
tags question: http://stackoverflow.com/q/49103186
tags question: http://stackoverflow.com/q/48978408
tags question: http://stackoverflow.com/q/49035081
tags question: http://stackoverflow.com/q/48994414
tags question: http://stackoverflow.com/q/49061655
tags question: http://stackoverflow.com/q/49011726
tags question: http://stackoverflow.com/q/49109263
tags question: http://stackoverflow.com/q/49120065
tags question: http://stackoverflow.com/q/49025442
tags question: http://stackoverflow.com/q/49099520
tags question: http://stackoverflow.com/q/49067775
tags question: http://stackoverflow.com/q/49056625
tags question: http://stackoverflow.com/q/49098987
tags question: http://stackoverflow.com/q/49051855
tags question: http://stackoverflow.com/q/49096235
tags question: http://stackoverflow.com/q/49019717
tags question: http://stackoverflow.com/q/49097561
tags question: http://stackoverflow.com/q/49042607
tags question: http://stackoverflow.com/q/49109545
tags question: http://stackoverflow.com/q/48967328
tags question: http://stackoverflow.com/q/49094280
tags question: http://stackoverflow.com/q/48990275
tags question: http://stackoverflow.com/q/49085716
tags question: http://stackoverflow.com/q/49040814
tags question: http://stackoverflow.com/q/49063237
tags question: http://stackoverflow.com/q/49031894
tags question: http://stackoverflow.com/q/49062469

http://stackoverflow.com/q/48970035
tagged with: python
tagged with: nlp
type: AnsweredQuestion
tagged with: spacy
score: 1
has body: Here's my code: from spacy.lang.en import English nlp = English() nlp.add_pipe(nlp.create_pipe('sentencizer')) doc = nlp("The quick brown fox jumps over the lazy dog.") for sent in doc.sents: print(list(sent.root.children)) I'm expecting sent.root.children to contain links to other words / sentence fragments like maybe lazy or brown, but it's an empty array. Why does this happen?
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48972463
has title: Why doesn't spacy given any children to the root node?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48972463
favorite count: 0

http://stackoverflow.com/comment/84993146
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48993441
has text: sorry, its for `h_train`. I'm using the variable explorer in Anaconda-spyder
type: AnswerComment

http://stackoverflow.com/q/49098155
score: 0
answer count: 2
tagged with: scikit-learn
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52647547
has body: I have the following code where I want to use k-fold cross validation for a Linear Regression model: kf = KFold(n_splits=100) predi = cross_val_predict(model, train[columns], train[target], cv = kf) predi = pandas.Series(predi) model.fit(data[columns], data[target]) pred_test = model.predict(test[columns]) print(mean_squared_error(pred_test, test[target])) However, I am not sure whether the code does what I would like it to do. Specifically, I am not sure about the model.fit part. Does it even use the cross-validation? The reason why I am not sure that calculating it like this yields worse results than without cross-validation.
tagged with: machine-learning
type: Question
has title: Using cross_val_predict for predictions
has answer: http://stackoverflow.com/a/49102974

http://stackoverflow.com/comment/85192208
score: 0
type: Comment
has text: Your file is not encoded in UTF8 either, check the updated answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/49093476

http://stackoverflow.com/q/48979977
type: Question
score: -1
tagged with: numpy
has comment: http://stackoverflow.com/comment/84965041
answer count: 2
possible better answer: http://stackoverflow.com/a/48980004
has title: How to store data in a float type? (append)
favorite count: 0
has body: How to store data in a float type (append) Python? data= #data is a float64 [ 335 -2.2827743] [ 340 4.5311280] [ 358 0.4698628] [ 367 3.8023018] [ 388 2.9782774] result=[] i in range(0,4): if data[i][0]&lt;360: result.append(data[i]) The result I want: result= [ 335 -2.2827743] [ 340 4.5311280] [ 358 0.4698628]
has comment: http://stackoverflow.com/comment/84965157
has comment: http://stackoverflow.com/comment/84965078
tagged with: python
has comment: http://stackoverflow.com/comment/84965215
has answer: http://stackoverflow.com/a/48980003
accepted answer: http://stackoverflow.com/a/48980003
tagged with: append
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48980004
downvote count: 2
has comment: http://stackoverflow.com/comment/84965076
has comment: http://stackoverflow.com/comment/84965120
upvote count: 1

http://stackoverflow.com/comment/85235596
comment on: http://stackoverflow.com/q/49114633
type: QuestionComment
has text: good question. This would return an empty list, `[ ]`. But luckily all my i`d_str` are unique in the actual dataset that I am using so this shouldnt be a problem
score: 0
type: Comment

http://stackoverflow.com/q/49092345
has comment: http://stackoverflow.com/comment/85210998
type: Question
has comment: http://stackoverflow.com/comment/85190663
answer count: 1
has body: ​​Hello all, This is what I need help getting done in python. to explain the context a bit: I get processes related data repeatedly, at some fixed interval (assume 10 seconds) which is info of all processes currently existing. (am mainly interested in the state) I need to create data structure in python to basically store total time in each state for each process, each time I get samples (say every 10 seconds), so increment the state i find it in this time, if earlier record exists, or create new record for that state, etc. So for each process, I need to maintain the state in a string, like "S","R","Z" or "UN" , and time in each state (increment same state, if process found in same state as last time, or add that state if first time process appeared in that state, or increment the state it is in now, if it was in that state previously and we had already created that record in the inner data structure ) I have a double dictionary, process_state_info = {} Then I get my sample at 10 seconds interval, say 3 processes running, in state like this showing me that since last 10 seconds, these pid's were in this state, pid:1, state "S" pid:2, state "R" pid 3, state "UN" So this type of structure should be built process_state_info = {1: [{"state":"S", "total_time": 10}],2: [{"state":"R","total_time":10}],3:[{"state":"UN","total_time":10}]} Each pid may come in different state in next samples, so i need to map pid to all possible states and time spent in those states. for eg, if next sample gives me, pid:1, state "R" ( changed state, so i need to add an entry in inner structure) pid:2, state "R" ( in same state, so i will increment existing entry by10 seconds) pid 3, state "Z" (changed state, add entry in inner structure) pid 4, state "R" (new pid, add new outer structure) So process_state_info will need to become process_state_info = {1: [{"state":"S", "total_time": 10}, {"state":R", "total"time":10}],2:[{"state":"R","total_time":20}],3:[{"state":"UN","total_time":10}, {"stat…
has title: add to a dictionary of list of dictionaries in python
score: 0
has answer: http://stackoverflow.com/a/49092380
has comment: http://stackoverflow.com/comment/85192118
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85196580
type: UnansweredQuestion

http://stackoverflow.com/comment/85041832
comment on: http://stackoverflow.com/q/49018263
type: Comment
type: QuestionComment
score: 3
has text: Please provide an example input that can be copied and pasted into our editors. ... Please read [mcve].

http://stackoverflow.com/comment/84946555
type: QuestionComment
comment on: http://stackoverflow.com/q/48970091
score: 0
has text: Oh right, yeah it would be because `event` is an unnecessary parameter, using `lambda i=string: _print(var, i)` works.
type: Comment

http://stackoverflow.com/comment/85213785
type: QuestionComment
has text: Sorry, could you post more of your code? What do you mean by "simple string concatenation" ?
comment on: http://stackoverflow.com/q/49104228
score: 0
type: Comment

http://stackoverflow.com/q/48998130
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
tagged with: selenium
has comment: http://stackoverflow.com/comment/85033759
has comment: http://stackoverflow.com/comment/85010525
type: Question
has title: WebDriverException Error
has comment: http://stackoverflow.com/comment/85034045
has body: I'm running a script to collect information from various pages on a website. #python2 from __future__ import division from bs4 import BeautifulSoup from pyvirtualdisplay import Display from BeautifulSoup import SoupStrainer import pandas as pd import urllib,re,csv,os,urllib2,requests,itertools,pdfkit,time import smtplib import math from selenium import webdriver import requests.packages.urllib3 import requests requests.packages.urllib3.disable_warnings() from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import WebDriverException from datetime import datetime os.environ["LANG"] = "en_US.UTF-8" start_time = time.time() os.chdir('DIRECTORY') #import .csv with variables for fulls list fulls = zip(orgs, terms, sites, smo_ids, year_i, year_start, year_end) orgs2 = [] terms2 = [] sites2 = [] results2 = [] smo_ids2 = [] article_number = [] years2 = [] numbers = range(2000001) numbers = numbers[0::200] start_time = time.time() display = Display(visible=0, size=(1600, 1200)) display.start() otime = datetime.now() startpoint = 1 for full in fulls: site = full[2] org = full[0] smo_id = full[3] term = full[1] year = full[4] driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") try: driver.get(site) #get original site info except (WebDriverException, TimeoutException) as e: print(e.Message) print "REFRESHING PAGE" driver.refresh(site) source = driver.page_source soup = BeautifulSoup(source, "html.parser") soup2 = soup.encode("utf-8") try: resultno = re.findall('&lt;h1 id="pqResultsCount"&gt;\n(.*?) result',soup2) resultno = ''.join(resultno) resultno = resultno.translate(None, "(){}&lt;&gt;,") resultno = int(resultno) except ValueError, e: resultno = int(0) no_pages = int(math.ceil(resultno/20)) an = re.findall('{"(.*?)markedlistcheckbox:markallitems',soup2) an = ''.join(an) an = re.findall('markAll":false,"formats":{(.*?)},"markURL"',an) an = ''.join(an) an = re.sub(r'":.+?,"', '', an) an = an.translate(None, '"') an = an.…
has comment: http://stackoverflow.com/comment/85033894
score: 0
answer count: 0
tagged with: exception

http://stackoverflow.com/a/49013959
type: AcceptedAnswer
score: 0
has body: The variable name_q is local to the function test. It doesn't exist in function main. You have to give it as a parameter: def main(name_q): names = name_q.get() log(names) def test(): name_q = Queue() user_input = int(input('How many random names you wanna make out of Barry? [NUMBERS] \n')) names= "barry" generator = NamesGenerator(names).generate() for i in range(0, user_input): name_q.put(generator[i]) main(name_q) NB: this has nothing to do with your problem but please put capital letters only at the beginning of class names, not to any variable. If you don't, this will lead to misunderstanding when people read your code. Moreover, Python code should be written with a maximum of 79 columns, as indicated in PEP8.
type: Answer
accepted answer of: http://stackoverflow.com/q/49013784
answers question: http://stackoverflow.com/q/49013784
has comment: http://stackoverflow.com/comment/85033518

http://stackoverflow.com/q/49119250
has title: storing values with multiple lines with multiple dictionaries
has body: I am trying to help out a friend by writing a program that continuously reads temperatures updates from his cooling machines The code should go through cooling machine data to register the temperatures. Periodically the following data will be printed: Highest temperature per machine, lowest temperature, highest temperature and top 5 temperatures overall. Below tempinput will be received every 5 minutes in the format below. For explanation purposes I have added a second line of tempinput to this code (received 5 minutes later). tempinput = [ { "Machine":"Cool-01", "Date":"01/01/2018", "Time":"12:25:00", "CurrTemp":"23.52"}, {"Machine":"Cool-02", "Date":"01/01/2018", "Time":"12:25:00", "CurrTemp":"22.02"} ] #tempinput = [ #{ #"Machine":"Cool-01", #"Date":"01/01/2018", #"Time":"12:30:00", #"CurrTemp":"23.50"}, #{"Machine":"Cool-02", #"Date":"01/01/2018", #"Time":"12:30:00", #"CurrTemp":"22.12"} #] The key = Machine. I then want to store the values per Machine in such a way that it will keep the values of the last 2 hours per Machine in memory (= 24 readings). After the first 24 readings and assignments I want the system to 'remove' the oldest stored value (based on an index not on time as this is sometimes ‘off’) and then place the other 23 lines a place down the ladder and fill the removed value with the latest values... I am really struggling how I can store the data as described above. After 'for key in dict_in_list', I am lost (do not know how to proceed). I cant get my head around the storing of 24 lines of data per machine. I hope someone can point me in the right direction and that my question is not downgraded (i have searched through the entire Stackoverflow site and could not find any example that I understood / reflects my request). Thanks in advance. for dict_in_list in tempinput: for key in dict_in_list: .....here i am stuck; tried a lot of ways but nothing works
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85244189
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85244501
has answer: http://stackoverflow.com/a/49119451
type: Question
answer count: 1

http://stackoverflow.com/a/48977816
type: Answer
has comment: http://stackoverflow.com/comment/84960771
has body: If you do not give any parameter value to q &amp; N then it automatically takes input as 5,10 respectively. def geometric_progression(x0,q=5,N=10): sequence = [] i = 1 while i&lt;N+2: sequence.append(x0*(q**(i-1))) i=i+1 return sequence
answers question: http://stackoverflow.com/q/48977589
has comment: http://stackoverflow.com/comment/84960822
score: 0
has comment: http://stackoverflow.com/comment/84960753

python-3.x
tags question: http://stackoverflow.com/q/49040059
tags question: http://stackoverflow.com/q/49026570
tags question: http://stackoverflow.com/q/49037989
tags question: http://stackoverflow.com/q/49100091
tags question: http://stackoverflow.com/q/49080455
tags question: http://stackoverflow.com/q/49029337
tags question: http://stackoverflow.com/q/49110542
tags question: http://stackoverflow.com/q/48997161
tags question: http://stackoverflow.com/q/48992644
tags question: http://stackoverflow.com/q/49023427
tags question: http://stackoverflow.com/q/49091106
tags question: http://stackoverflow.com/q/49102858
tags question: http://stackoverflow.com/q/49021835
tags question: http://stackoverflow.com/q/49101716
tags question: http://stackoverflow.com/q/49093373
tags question: http://stackoverflow.com/q/49073615
tags question: http://stackoverflow.com/q/49102300
tags question: http://stackoverflow.com/q/48964998
tags question: http://stackoverflow.com/q/48972569
tags question: http://stackoverflow.com/q/49077539
tags question: http://stackoverflow.com/q/48981282
tags question: http://stackoverflow.com/q/48967576
tags question: http://stackoverflow.com/q/49085832
tags question: http://stackoverflow.com/q/49081417
tags question: http://stackoverflow.com/q/49067775
tags question: http://stackoverflow.com/q/49021071
tags question: http://stackoverflow.com/q/49100796
tags question: http://stackoverflow.com/q/48971427
tags question: http://stackoverflow.com/q/49038899
tags question: http://stackoverflow.com/q/49051877
tags question: http://stackoverflow.com/q/49112479
tags question: http://stackoverflow.com/q/49012613
tags question: http://stackoverflow.com/q/48999930
tags question: http://stackoverflow.com/q/48970332
tags question: http://stackoverflow.com/q/49026796
tags question: http://stackoverflow.com/q/49079030
tags question: http://stackoverflow.com/q/48967376
tags question: http://stackoverflow.com/q/49061953
tags question: http://stackoverflow.com/q/49018080
tags question: http://stackoverflow.com/q/49062917
tags question: http://stackoverflow.com/q/49072649
tags question: http://stackoverflow.com/q/48974956
tags question: http://stackoverflow.com/q/48995577
tags question: http://stackoverflow.com/q/49091841
tags question: http://stackoverflow.com/q/48968435
tags question: http://stackoverflow.com/q/48990455
tags question: http://stackoverflow.com/q/49110185
tags question: http://stackoverflow.com/q/48968918
tags question: http://stackoverflow.com/q/49097658
tags question: http://stackoverflow.com/q/49037852
tags question: http://stackoverflow.com/q/49007680
tags question: http://stackoverflow.com/q/49031102
tags question: http://stackoverflow.com/q/49072921
tags question: http://stackoverflow.com/q/49086873
tags question: http://stackoverflow.com/q/49015697
tags question: http://stackoverflow.com/q/49038659
tags question: http://stackoverflow.com/q/49108058
tags question: http://stackoverflow.com/q/49064086
tags question: http://stackoverflow.com/q/49039436
tags question: http://stackoverflow.com/q/48978144
tags question: http://stackoverflow.com/q/49117330
tags question: http://stackoverflow.com/q/49077702
tags question: http://stackoverflow.com/q/49066006
tags question: http://stackoverflow.com/q/48992929
tags question: http://stackoverflow.com/q/49001876
tags question: http://stackoverflow.com/q/48995936
tags question: http://stackoverflow.com/q/49109334
tags question: http://stackoverflow.com/q/49015856
tags question: http://stackoverflow.com/q/49079440
tags question: http://stackoverflow.com/q/49100218
tags question: http://stackoverflow.com/q/49090796
tags question: http://stackoverflow.com/q/49084214
tags question: http://stackoverflow.com/q/49109946
tags question: http://stackoverflow.com/q/49104421
tags question: http://stackoverflow.com/q/49076253
tags question: http://stackoverflow.com/q/48964177
tags question: http://stackoverflow.com/q/49013318
tags question: http://stackoverflow.com/q/49031935
tags question: http://stackoverflow.com/q/49014409
tags question: http://stackoverflow.com/q/49018580

http://stackoverflow.com/q/49071728
has answer: http://stackoverflow.com/a/49073146
has comment: http://stackoverflow.com/comment/85148968
favorite count: 0
has comment: http://stackoverflow.com/comment/85151908
possible better answer: http://stackoverflow.com/a/49074332
answer count: 2
tagged with: cython
has answer: http://stackoverflow.com/a/49074332
accepted answer: http://stackoverflow.com/a/49073146
has title: Return a struct from C to Python using Cython
has body: I am trying to pass a struct back into my Python from a c file. Let's say I have a file pointc.c like this: typedef struct Point { int x; int y; } Point; struct Point make_and_send_point(int x, int y); struct Point make_and_send_point(int x, int y) { struct Point p = {x, y}; return p; } Then I set-up a point.pyx file like this: "# distutils: language = c" # distutils: sources = pointc.c cdef struct Point: int x int y cdef extern from "pointc.c": Point make_and_send_point(int x, int y) def make_point(int x, int y): return make_and_send_point(x, y) // This won't work, but compiles without the 'return' in-front of the function call How do I get the returned struct into my Python? Is this kind of thing only possible by creating a struct in the Cython and sending by reference to a void c function? As a reference, my setup.py is: from distutils.core import setup, Extension from Cython.Build import cythonize setup(ext_modules = cythonize( "point.pyx", language="c" ) )
tagged with: http://stackoverflow.com/tag/c
tagged with: struct
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/85149213
upvote count: 8
has comment: http://stackoverflow.com/comment/85149613
type: Question
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/comment/85128130
has text: That worked! Thank You. Whenever I want to return a value from a function in python will I need to do this ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49061492
type: Comment

http://stackoverflow.com/a/49077349
score: 4
upvote count: 4
has body: The code uses formatted string literals (the f"&lt;element&gt;{summary}&lt;/element&gt;"), which were only introduced in Python 3.6, so you need to use at least that version of Python.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49077286
answers question: http://stackoverflow.com/q/49077286
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85242185
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49118298
type: AnswerComment
has text: @MilesNocte In IDLE, do: `import os`, `print(os.getcwd())`. If you are launching IDLE from a GUI, it is probably looking in a different path than the rest of your files.

http://stackoverflow.com/a/48996330
type: Answer
downvote count: 0
score: 1
has body: You can see here that the Message class does not have as_dict method defined in it. If you want to get the message content, you can access .content property of a Message instance to get the Message content dict. (This is mentioned in the Message class documentation string) Fix: Group('chat-'+label).send({'text': json.dumps(m.content)})
answers question: http://stackoverflow.com/q/48996067
upvote count: 1

http://stackoverflow.com/comment/85034572
comment on: http://stackoverflow.com/a/49014801
type: Comment
has text: Shuffling a list of strings is really just shuffling a list of pointers, it doesn't copy the strings themselves. But making a list of indexes beforehand means you don't need to read the whole file into memory at all.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48991150
score: 0
has body: I am very new to Python and my knowledge of the variety of function is very limited. My intention is to compare each entries in an nxm array to entries in another nxm array, for all integers n,m >1. I'd like for Python to return another nxm array of Boolean values. Idea: Entries in an array in Python is denoted by array[i][j] for all i in n and j in m. Run i and j across all values in n and m, respectively. Then compare array_1[i][j] with array_2[i][j]. If array_1[i][j] == array_2[i][j] or array_1[i][j] != array_2[i][j], for some i and j in n and m, respectively, then return "True", otherwise, "False. The result of which, boolean, is then fed into an empty array array_3. import numpy array_3 = [] array_1 = [['Roy',80,75,85,90,95], ['John',75,80,75,85,100], ['Dave',80,80,80,90,95]] array_2 = [['Roy',80,75,75,80], ['John',75,60,75,75,90], ['Dave',50,80,70,90,85]] print(type(array_1)) print(type(array_2)) print(type(array_3)) for array_1[i][j] in array_1: if array_1[i][j] == array_2[i][j]: From here, I am unable to proceed further. Any HINTS are appreciated. No solutions unless at least 24 hours from posting Edit: import numpy array_1 = numpy.array([['Roy',80,75,85,90,95], ['John',75,80,75,85,100], ['Dave',80,80,80,90,95]]) array_2 = numpy.array([['Roy',80,75,75,80], ['John',75,60,75,75,90], ['Dave',50,80,70,90,85]]) arrayssize = [array_1.shape, array_2.shape] print(size) for x in range(3): for y in range(5): array_3 = [True if array_1[x][y] == array_2[x][y] else False]
type: Question
tagged with: arrays
has answer: http://stackoverflow.com/a/48991496
answer count: 1
tagged with: multidimensional-array
accepted answer: http://stackoverflow.com/a/48991496
tagged with: python
has title: comparing entries between two n x m array algorithmically
type: AnsweredQuestion
tagged with: conditional-statements

http://stackoverflow.com/q/49109466
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85224110
tagged with: scipy
type: Question
tagged with: numpy
downvote count: 0
favorite count: 0
answer count: 1
has title: How to get the X, Y values from the given Z value after using interpolate.interp2d to plot a surface
tagged with: python
has answer: http://stackoverflow.com/a/49113092
tagged with: interpolation
has comment: http://stackoverflow.com/comment/85225614
has comment: http://stackoverflow.com/comment/85224269
has body: I have x and y arrays to represent the row and column of a grid data and its values are in the z 2d array. I have used interpolate.interp2d to plot a surface graph. Now, I am able to obtain the z value for given x, y value but I want to be able to obtain the x,y values from the given z value. code: import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D from scipy import interpolate x = [0, 0.01, 0.02] y = [0, 5e-05, 0.0001] print(np.meshgrid(x, y)) xx, yy = np.meshgrid(x, y) z = [[ 1. , 0.99990035, 0.99981654], [ 0.90849264, 0.85447203, 0.81382534], [ 0.82880434 , 0.76083003 , 0.71961281]] f = interpolate.interp2d(x, y, z, kind='linear') xnew = np.arange(x[0],x[2], 1e-6) ynew = np.arange(y[0],y[2], 1e-6) znew = f(xnew, ynew) print(f(0.003,0.0006)) xnew,ynew=np.meshgrid(xnew,ynew) fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(xnew,ynew, znew, cmap=cm.get_cmap('coolwarm')) plt.show()
upvote count: 1
accepted answer: http://stackoverflow.com/a/49113092
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85223852

http://stackoverflow.com/q/49099147
has answer: http://stackoverflow.com/a/49099216
tagged with: jupyter-notebook
tagged with: immutability
downvote count: 3
answer count: 1
has body: My instructor said tuple is list type and it is immutable. but i tried code &gt;&gt;&gt;tuple1=[3,4,5,6] &gt;&gt;&gt;tuple1[1]=44 &gt;&gt;&gt;tuple1 [3,44,5,6] &gt;&gt;&gt;list[3]=66 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'type' object does not support item assignment &gt;&gt;&gt; s=['hi','hello',33] &gt;&gt;&gt; list[1]='hitech' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'type' object does not support item assignment this was output. but I don't know why it is not showing &lt;Error&gt;
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/49099216
has comment: http://stackoverflow.com/comment/85203855
score: -3
has comment: http://stackoverflow.com/comment/85203581
type: AnsweredQuestion
upvote count: 0
has title: I am trying to learn use of tuple in python in shell (jupyter notebook) /(anaconda prompt) , from online courses . I got stuck on tuple part
favorite count: 0
tagged with: tuples
type: Question
tagged with: python

http://stackoverflow.com/a/58116723
has comment: http://stackoverflow.com/comment/117049076
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/49100256
has body: OpenCV also requires floats to have single precision, as per this question. This means every array needs to be converted to np.float32 before passing to calibrateCamera.
upvote count: 5
type: Answer

http://stackoverflow.com/comment/85087739
comment on: http://stackoverflow.com/q/49040837
has text: Possible duplicate. Check this: https://stackoverflow.com/questions/23668427/pandas-joining-multiple-dataframes-on-columns
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49010709
upvote count: 0
type: Question
score: -1
has comment: http://stackoverflow.com/comment/85025963
tagged with: sqlite
has body: I would much appreciate if you could help me with the issue. I want to import .csv (5 columns with data) data into .db format using Python. I took the script from here: import sqlite3 import csv class csvrd(object): def csvFile(self): self.readFile('c:/users/quant/desktop/trade.csv') def readFile(self, filename): conn = sqlite3.connect('c:/users/quant/desktop/ledger_4.db') cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS trading(date varchar,asset varchar,quant varchar,price varchar,com varchar)""") filename.encode('utf-8') print ("test1") with open(filename) as f: reader = csv.reader(f) for field in reader: cur.execute("INSERT INTO unicom VALUES (?,?,?,?,?);", field) conn.commit() conn.close() c = csvrd().csvFile() but unfortunately I get this: 'charmap' codec can't decode byte 0x9d in position 62: character maps to Could you please advise what is wrong with the code or help with any other way to import the csv? Thank you a lot in advance! Thank you for your reply! A few rows from csv: date asset quant price com "08.08.2017 11:35:49" Башнефть а.о. 3 2 188,00 2,63 "08.08.2017 11:35:49" Башнефть а.о. 3 2 188,00 2,63 "08.08.2017 11:35:49" Башнефть а.о. 2 2 188,00 1,75
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49010795
favorite count: 0
has title: import .csv into .db in python3
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/85026999

http://stackoverflow.com/a/49059762
has comment: http://stackoverflow.com/comment/85124915
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85124970
type: Answer
accepted answer of: http://stackoverflow.com/q/49059667
answers question: http://stackoverflow.com/q/49059667
score: 3
upvote count: 3
has body: I think you have to vectorize f first: &gt;&gt;&gt; np.fromfunction(np.vectorize(f), (5, 5), dtype=int) array([[ 1, 1, 1, 1, 1], [ 2, 3, 3, 3, 3], [ 3, 4, 5, 5, 5], [ 4, 6, 7, 8, 8], [ 5, 7, 8, 9, 10]]) Indeed, fromfunction passes the coordinates not one-by-one but in one go: &gt;&gt;&gt; def f(i, j): ... print(i, j) ... return sum((i+1)//k for k in range(1, j+2)) ... &gt;&gt;&gt; np.fromfunction(f, (5, 5), dtype=int) [[0 0 0 0 0] [1 1 1 1 1] [2 2 2 2 2] [3 3 3 3 3] [4 4 4 4 4]] [[0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4]] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/paul/local/lib/python3.6/site-packages/numpy/core/numeric.py", line 1914, in fromfunction return function(*args, **kwargs) File "&lt;stdin&gt;", line 3, in f TypeError: only integer scalar arrays can be converted to a scalar index

http://stackoverflow.com/comment/85153116
type: QuestionComment
score: 0
has text: if you hardcode `url = "base.com/&page=3"` does it take you to the right page?
comment on: http://stackoverflow.com/q/49073298
type: Comment

http://stackoverflow.com/a/49098482
has body: As all the above solutions, with the difference that you can use the # sign in order to remove any zero padding in day or month: from datetime import datetime dt = datetime.strptime(a, "%a, %d %b %Y %H:%M:%S %Z") print(dt.strftime("%#d/%#m/%Y")) Output: 9/8/2053 This works for Windows. For Unix systems, consult using the - sign.
type: Answer
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49098309
downvote count: 0

scikit-learn
tags question: http://stackoverflow.com/q/48984071
tags question: http://stackoverflow.com/q/48980313
tags question: http://stackoverflow.com/q/49050243
tags question: http://stackoverflow.com/q/48979808
tags question: http://stackoverflow.com/q/49112581
tags question: http://stackoverflow.com/q/49094242
tags question: http://stackoverflow.com/q/49015452
tags question: http://stackoverflow.com/q/49098056
tags question: http://stackoverflow.com/q/49049771
tags question: http://stackoverflow.com/q/49092695
tags question: http://stackoverflow.com/q/49068020
tags question: http://stackoverflow.com/q/49006391
tags question: http://stackoverflow.com/q/49109483
tags question: http://stackoverflow.com/q/49110691
tags question: http://stackoverflow.com/q/49074737
tags question: http://stackoverflow.com/q/49015192
tags question: http://stackoverflow.com/q/48963813
tags question: http://stackoverflow.com/q/48975402
tags question: http://stackoverflow.com/q/49016589
tags question: http://stackoverflow.com/q/49055410
tags question: http://stackoverflow.com/q/49058847
tags question: http://stackoverflow.com/q/49101935
tags question: http://stackoverflow.com/q/48978463
tags question: http://stackoverflow.com/q/49037567
tags question: http://stackoverflow.com/q/49075045
tags question: http://stackoverflow.com/q/49039015
tags question: http://stackoverflow.com/q/49050166
tags question: http://stackoverflow.com/q/49116461
tags question: http://stackoverflow.com/q/49042340
tags question: http://stackoverflow.com/q/49016933
tags question: http://stackoverflow.com/q/49099293
tags question: http://stackoverflow.com/q/49095096
tags question: http://stackoverflow.com/q/48993472
tags question: http://stackoverflow.com/q/49006722
tags question: http://stackoverflow.com/q/48966101
tags question: http://stackoverflow.com/q/49054538
tags question: http://stackoverflow.com/q/49025207
tags question: http://stackoverflow.com/q/48991245
tags question: http://stackoverflow.com/q/48996733
tags question: http://stackoverflow.com/q/49052420
tags question: http://stackoverflow.com/q/48973628
tags question: http://stackoverflow.com/q/49004835
tags question: http://stackoverflow.com/q/48999072
tags question: http://stackoverflow.com/q/49027972
tags question: http://stackoverflow.com/q/49068574
tags question: http://stackoverflow.com/q/49089508
tags question: http://stackoverflow.com/q/49018652
tags question: http://stackoverflow.com/q/48973468
tags question: http://stackoverflow.com/q/49079122
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48993412
tags question: http://stackoverflow.com/q/49077428
tags question: http://stackoverflow.com/q/48989629
type: Tag
tags question: http://stackoverflow.com/q/49103139
tags question: http://stackoverflow.com/q/48974973
tags question: http://stackoverflow.com/q/49001316
tags question: http://stackoverflow.com/q/49035107
tags question: http://stackoverflow.com/q/48988182
tags question: http://stackoverflow.com/q/49028416
tags question: http://stackoverflow.com/q/49017257
tags question: http://stackoverflow.com/q/48996597
tags question: http://stackoverflow.com/q/48964883
tags question: http://stackoverflow.com/q/49088365
tags question: http://stackoverflow.com/q/49017069
tags question: http://stackoverflow.com/q/49063290
tags question: http://stackoverflow.com/q/49094854
tags question: http://stackoverflow.com/q/48985352
tags question: http://stackoverflow.com/q/48993339
tags question: http://stackoverflow.com/q/49098155
tags question: http://stackoverflow.com/q/49061575
tags question: http://stackoverflow.com/q/49014129
tags question: http://stackoverflow.com/q/49019037
tags question: http://stackoverflow.com/q/49030479
tags question: http://stackoverflow.com/q/49098779
tags question: http://stackoverflow.com/q/49019531
tags question: http://stackoverflow.com/q/49058507
tags question: http://stackoverflow.com/q/49035011
tags question: http://stackoverflow.com/q/49091145
tags question: http://stackoverflow.com/q/49116205

http://stackoverflow.com/q/49080398
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85166905
tagged with: encryption
tagged with: python
has comment: http://stackoverflow.com/comment/85166706
answer count: 0
score: 0
tagged with: caesar-cipher
has comment: http://stackoverflow.com/comment/85166691
has comment: http://stackoverflow.com/comment/85166822
type: Question
has comment: http://stackoverflow.com/comment/85180904
tagged with: vigenere
has comment: http://stackoverflow.com/comment/85167541
has body: For my programming class, I've been instructed to create two programs, each using the same two helper functions: alphabet_position(letter) and rotate_character(char, rot). One function uses the Caesar cipher to encrypt a message with a number of rotations, each given from the command line. The second program is meant to put more use to my Caesar program by turning it into the Vigenere Cipher. Both programs are meant to ignore (i.e., not rotate) special characters and I don't think numbers matter either. However, if the input letter is capitalized, the rotated output letter should be as well. I've run into several issues with my code: My Caesar program only prints some capital letters. For example, with the arguments Hello, World! and 4, I receive an output of Lipps, svph! and I cannot figure out why that last capital letter isn't printing. When I attempt to pass in pYthon with 26 rotations, my program prints nothing. My Vigenere program is also doing an odd thing with capital letters: with the passed arguments being Hello, World! and boom, I receive Iszxp, mr!. Assignment is due in 48 hours and I'm kind of freaking out. Any and all help, criticism, etc. is welcome! def alphabet_position(letter): """receives a letter and returns the 0-based numerical position of that letter within the alphabet.""" letter = letter.lower() alphabet = "abcdefghijklmnopqrstuvwxyz" numerical_pos = alphabet.find(letter) return numerical_pos def rotate_character(char, rot): """receives a character and an int 'rot', and rotates char by rot number of places to the right.""" alphabet = "abcdefghijklmnopqrstuvwxyz" alpha_dict = dict(enumerate(alphabet)) new_char = "" # ignore and return non-alphabetic characters if char not in alphabet: return char # temporarily convert case to locate in alphabet temp_char = char.lower() if temp_char in alphabet: # get original position of letter orig_pos = alphabet_position(temp_char) # take char, add rot to its index, mod 25 - 1 new_pos = (int(orig_pos) + int…
has comment: http://stackoverflow.com/comment/85166675
has comment: http://stackoverflow.com/comment/85180855
has title: Python Caesar and Vigenere Ciphers
has comment: http://stackoverflow.com/comment/85166653

http://stackoverflow.com/a/49086886
upvote count: 2
type: AcceptedAnswer
has body: I believe you dont need apply, because slow, better is use: V = input_csv['vote_count'] R = input_csv['vote_average'] C = input_csv['vote_average'].mean() m = input_csv['vote_count'].quantile(0.10) input_csv['w_average'] = (V/(V+m) * R) + (m/(m+V) * C) print (input_csv) vote_average vote_count w_average 0 7.2 11800 7.116795 1 6.9 4500 6.821294 2 6.3 4466 6.414272 3 7.6 9106 7.421180 4 6.1 2124 6.377273 5 5.9 3576 6.181167 6 7.4 3330 7.109691 7 7.3 6767 7.145805 8 7.4 5293 7.186525 9 5.7 7004 5.922114 10 5.4 1400 6.156145
type: Answer
answers question: http://stackoverflow.com/q/49086707
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49086707

http://stackoverflow.com/q/49087107
has answer: http://stackoverflow.com/a/49087346
tagged with: python
has title: Adding column in dataframes in Pandas using data in existing Dataframe
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85179587
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49087346
has comment: http://stackoverflow.com/comment/85179662
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I have following Dataframe looks like in below image: I need to add one more column 'Key' to existing Dataframe such as it looks like Dataframe in below image: Is there a way to create a Column "Key" based on columns Field and Seq

http://stackoverflow.com/comment/85133839
type: QuestionComment
has text: to be honest, i am not aware of what it actually does. but that should solve the issue here.
score: 0
comment on: http://stackoverflow.com/q/49063732
type: Comment

http://stackoverflow.com/q/49080880
tagged with: python
has body: I found the following code sample online: # Use R to login to web site import cookielib import urllib import urllib2 url = 'https://www.google.com/accounts/Login' values = {'email-email' : 'email@gmail.com', 'password-password' : 'my_password' } data = urllib.urlencode(values) cookies = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPRedirectHandler(), urllib2.HTTPHandler(debuglevel=0), urllib2.HTTPSHandler(debuglevel=0), urllib2.HTTPCookieProcessor(cookies)) response = opener.open(url, data) the_page = response.read() http_headers = response.info() I entered my actual login creds and got an error that read: Warning in install.packages : package ‘urllib2’ is not available (for R version 3.4.3) Warning in install.packages : package ‘cookielib’ is not available (for R version 3.4.3) I am using Python 3.6.1. Thanks everyone!!
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
score: 0
has title: How to Log Into Website Using Python Script?
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85167389
favorite count: 0
has comment: http://stackoverflow.com/comment/85167477

http://stackoverflow.com/comment/85047805
comment on: http://stackoverflow.com/q/49021027
has text: If `fmt` describes one column it is replicated and joined with the `delimiter`. Alternatively it can describe the whole line as @Stephen shows.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49034230
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/85073346
has answer: http://stackoverflow.com/a/49034333
has title: Remove non-alphabetic characters from a list of lists and maintain structure
has answer: http://stackoverflow.com/a/49034506
tagged with: python
has comment: http://stackoverflow.com/comment/85073214
possible better answer: http://stackoverflow.com/a/49034333
has comment: http://stackoverflow.com/comment/85073311
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49034494
has body: I'm working in python 2.7. I want to remove the non-alphabetic characters from each list in a list of lists without modifying the structure of the lists. Starting example list of lists: csvarticles = [['[Beta-blockers]', 'Magic!', '1980', 'Presse medicale'],['Hypertension in the pregnant woman].', '', '2010', 'Medical'],['Arterial hypertension.', '', '1920', 'La Nouvelle']] print (csvarticles[0]) Desired Output: [['beta blockers', 'magic', '1980', 'presse medicale'],['hypertension in the pregnant woman', '', '2010', 'medical'],['arterial hypertension', '', '1920', 'la nouvelle']] Code 1: csvarticles = [[word.lower().split() for word in nodeList] for nodeList in csvarticles] print (csvarticles[0]) Code 1 Output: ['[Beta-blockers]', 'Magic!', '1980', 'Presse medicale'] [['[beta-blockers]'], ['magic!'], ['1980'], ['presse', 'medicale']] Code 2: csvarticles = [[word.lower().split() for word in nodeList if word.isalpha()] for nodeList in csvarticles] Code 2 Output: [] Code 3: articleTitle = [] for x, y in enumerate(csvarticles): myString = simpleWords(csvarticles[x][0]) if myString is not '': myString = myString.lower() myString = re.sub('[\W_]+', ' ', myString, flags=re.UNICODE) myList = [word for word in myString.split() if len(word) &gt; 3] articleTitle = ' '.join(myList) Code 3 Output: ['beta blockers', 'magic', '1980', 'presse medicale', 'hypertension pregnant woman', '2010', 'medical', 'arterial hypertension', '1920', 'nouvelle'] Code 3 gets close but eliminates the structure of the nested lists.
type: Question
has comment: http://stackoverflow.com/comment/85073207
accepted answer: http://stackoverflow.com/a/49034494
score: -1
tagged with: python-2.7

http://stackoverflow.com/comment/85035262
type: AnswerComment
has text: Thank you, this was what I needed for the google.com part of this question
comment on: http://stackoverflow.com/a/49015018
score: 0
type: Comment

http://stackoverflow.com/a/49070598
answers question: http://stackoverflow.com/q/49068574
accepted answer of: http://stackoverflow.com/q/49068574
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has body: I hav simply copy paste a code and did something stupid: X_train, v1 = make_regression() Just had to remove it.

http://stackoverflow.com/comment/85203416
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49099037
has text: This works with Flask, and I thought it would work for Bottle, but it doesn't: `TypeError('page() takes exactly 1 argument (0 given)',)`
score: 0

http://stackoverflow.com/q/48977129
accepted answer: http://stackoverflow.com/a/48977195
tagged with: docker
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/48977195
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I am developing an app with django cookiecutter (with docker and heroku setup) and have come so far as to deploying it. This is my first ever project, so no prior experience with django, docker or heroku. I've read up on it at cookiecutter docs, heroku and a little on the docker website but I still don't how to deploy. I have downloaded the heroki cli , have set up app on heroku with my own domain and a postgres db and I am planning on getting hobby tier to get the automated certificate. All environment variables are set in the .env file and are set in the heroku config vars in my app at heoku. So everything should be alright as far as code and settings. I am also using git as version control. Am I supposed to upload the whole project (code, settings, docker files etc) to heroku with git or by some other means? I saw there was an option to deploy the project with docker deploys aswell at herokus website. What option is the correct one? I was thinking initially that I would just upload the project through git and run docker-compose -f production.yml up (in the heroku bash)... or something like that and that. I dont know, please help. If some info is missing or is unclear I will try edit it as best as I can.
tagged with: git
has title: How to upload and deploy django cookiecutter project, with docker, to heroku?
type: Question
tagged with: heroku
score: 3

http://stackoverflow.com/q/49105772
downvote count: 1
has title: how to scrape multiple pages from one site
type: Question
has answer: http://stackoverflow.com/a/49105859
has answer: http://stackoverflow.com/a/49106127
has answer: http://stackoverflow.com/a/49105813
score: 0
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/85216493
favorite count: 0
has body: I want to scrap multiple pages from one site.the pattern like this： https://www.example.com/S1-3-1.html https://www.example.com/S1-3-2.html https://www.example.com/S1-3-3.html https://www.example.com/S1-3-4.html https://www.example.com/S1-3-5.html. I tried three method to scrape all of these pages once, but every method only scrape the first page. I show the code below, and anyone can check and tell me what is the problem will be highly appreciated. ===============method 1==================== import requests for i in range(5): # Number of pages plus one url = "https://www.example.com/S1-3-{}.html".format(i) r = requests.get(url) from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'}) ===============method 2============= import urllib2,sys from bs4 import BeautifulSoup for numb in ('1', '5'): address = ('https://www.example.com/S1-3-' + numb + '.html') html = urllib2.urlopen(address).read() soup = BeautifulSoup(html,'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'}) =============method 3============== import requests from bs4 import BeautifulSoup url = 'https://www.example.com/S1-3-1.html' for round in range(5): res = requests.get(url) soup = BeautifulSoup(res.text,'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'}) paging = soup.select('div.paging a') next_url = 'https://www.example.com/'+paging[-1]['href'] # paging[-1]['href'] is next page button on the page url = next_url I checked some answers and checked, but it is not loop problem, please check image shown below,it is only first page results. it is really me annoyed several days please see photo:only first page results, results picture 2
tagged with: python
type: UnansweredQuestion
tagged with: web-scraping

http://stackoverflow.com/q/48981986
has comment: http://stackoverflow.com/comment/84971791
has body: For a homework problem we are asked to Write a program that computes all the eigenvalues of the matrix A, using the Rayleigh Quotient iteration to find each eigenvalue. i. Report the initial guess you used for each eigenvalue. Plot the error at the n iteration against the error at the n+1 iteration for each eigenvalue (in log log). ii. Compute the Rayleigh quotient for x sampled on a discretization of the unit sphere (use spherical coordinates). Plot the result, for example with mesh (Θ,ϕ,r(Θ,ϕ)). Explain the number and location of the critical points. I have completed the first part of the problem, but I am not sure I understand how to complete the second. After some research I have found various ways (Here and Here) to plot spherical coordinates in Python which has provided me some clues. Borrowing from those links and a few other sources I have # The matrix for completness A = np.matrix([[4,3,4], [3,1,3], [4,3,4]]) A = scipy.linalg.hessenberg(A) num_points = 50 theta, phi = np.linspace(0, 2 * np.pi, num_points), np.linspace(0, np.pi, num_points) x = np.sin(phi) * np.cos(theta) y = np.sin(phi) * np.sin(theta) z = np.cos(phi) xyz = np.stack((x, y, z), axis=1) rqs = np.array([np.dot(x, np.dot(A, np.conj(x).T)).item(0) for _,x in enumerate(xyz)]) In the first chunk of code (Θ,ϕ) are created and translated to Cartesian coordinates, effectively a discritization of the unit circle in the R^3. This allows me then to create the x vectors (xyz above) used to calculate the Rayleigh Quotients (rqs above) at each discritization point, the r(Θ,ϕ) of the spherical coordinates. Though, now that I have the radial distance I am not sure how to again recreate x, y, z properly for a meshgrid to plot as a surface. This might be out of the realm of StackOverflow and more for Math.Stack, but I am also not sure if this plot should end up being a "warped plane" or a "warped sphere". In this SO answer, linked above too, I think the answer lies though. In the chunk of code theta, phi = np.…
accepted answer: http://stackoverflow.com/a/48995982
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84988002
tagged with: matplotlib
tagged with: linear-algebra
has answer: http://stackoverflow.com/a/48995982
type: Question
has comment: http://stackoverflow.com/comment/84987325
answer count: 1
has comment: http://stackoverflow.com/comment/84984965
linked to: http://stackoverflow.com/q/36816537
score: 0
linked to: http://stackoverflow.com/q/9600801
tagged with: python
has comment: http://stackoverflow.com/comment/84987736
has title: Plotting in spherical coordinates given the radial distance?
has comment: http://stackoverflow.com/comment/84988743

http://stackoverflow.com/comment/85091760
comment on: http://stackoverflow.com/a/49002194
has text: Still empty. QAQ
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49092527
favorite count: 0
has answer: http://stackoverflow.com/a/65633977
has comment: http://stackoverflow.com/comment/85190685
has title: Illegal instruction(core dumped) tensorflow
tagged with: machine-learning
tagged with: python
linked to: http://stackoverflow.com/q/45877158
has answer: http://stackoverflow.com/a/49169125
type: AnsweredQuestion
has body: I am importing tensorflow in my ubuntu python using following commands- $ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf Illegal instruction (core dumped) And the program exits. Please specify the solution.
upvote count: 26
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85190827
score: 26
possible better answer: http://stackoverflow.com/a/56913646
accepted answer: http://stackoverflow.com/a/49169125
has answer: http://stackoverflow.com/a/56913646
has comment: http://stackoverflow.com/comment/85191060
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/85190874
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85190837

http://stackoverflow.com/comment/85176744
score: 0
has text: At moment Im just wondering how I will do it, dont matter what library I will use ( I think). I picked the example from module graphics but Im thinking use wxpython, Yes, I want how create 2 or 10 or 1000. It will be dependent of a input. Yes, I want some like a loop that create different variables/labels. Point and size are just examples of what I should use to config that label. I have center just because I copied from another example.
comment on: http://stackoverflow.com/q/49085577
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48983480
type: Question
accepted answer: http://stackoverflow.com/a/48983619
has comment: http://stackoverflow.com/comment/84972303
has body: These two strings look identical when printed but they are not equal under the hood. I need to select a dictionary item by this key but I get keyError because obviously they do not match. I have tried using str.encode("utf-8"), str.decode("utf-8"), unicode(str, "utf-8"), repr(). Nothing helped. How can I make them equal just like when they are printed? Thanks. &gt;&gt;&gt; str1 = u"extra\u00f1ar" &gt;&gt;&gt; str2 = u"extrañar" &gt;&gt;&gt; str1 u'extra\xf1ar' &gt;&gt;&gt; str2 u'extran\u0303ar' &gt;&gt;&gt; print str1 extrañar &gt;&gt;&gt; print str2 extrañar &gt;&gt;&gt; str1 == str2 False
has comment: http://stackoverflow.com/comment/84971722
upvote count: 2
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/84972031
has answer: http://stackoverflow.com/a/48983619
has comment: http://stackoverflow.com/comment/84972167
answer count: 1
tagged with: python-2.x
has title: python - encoding, print can't figure out
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/84972036
linked to: http://stackoverflow.com/q/26151641
tagged with: python
has comment: http://stackoverflow.com/comment/84972155
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/comment/85151856
type: Comment
comment on: http://stackoverflow.com/a/49072184
has text: @ACF Can you create new question? Now I am offline, on phone only. Thanks.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84989787
comment on: http://stackoverflow.com/a/48992121
score: 0
type: AnswerComment
has text: @fordy yw :-) happy coding
type: Comment

http://stackoverflow.com/q/49015001
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: exception
type: UnansweredQuestion
has body: The following causes some additional strange output to be printed import warnings def foo(x): if x &gt; 100: msg = "Warning! x is big!" warnings.warn(msg) return True foo(999999) Instead of only printing: UserWarning: Warning! x is big! we get: UserWarning: Warning! x is big! warnings.warn(msg) Sometimes I have even gotten: UserWarning: Warning! x is big! ValueError [blah, blah, blah]
tagged with: python
upvote count: 3
tagged with: error-handling
type: Question
score: 3
has title: How do we prevent warning from printing strange text at the end of its message?
linked to: http://stackoverflow.com/q/26430861
tagged with: warnings
has answer: http://stackoverflow.com/a/49015058
duplicate of: http://stackoverflow.com/q/26430861

http://stackoverflow.com/q/49018025
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/49022289
type: AnsweredQuestion
has title: Beautifulsoup4 - Identifying info by strong tag value only works for some values of the tag
score: 1
tagged with: web-scraping
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49022289
has body: I am working with the following 'block' of HTML: &lt;div class="marketing-directories-results"&gt; &lt;ul&gt; &lt;li&gt; &lt;div class="contact-details"&gt; &lt;h2&gt; A I I Insurance Brokerage of Massachusetts Inc &lt;/h2&gt; &lt;br/&gt; &lt;address&gt; 183 Davis St &lt;br/&gt; East Douglas &lt;br/&gt; Massachusetts &lt;br/&gt; U S A &lt;br/&gt; MA 01516-113 &lt;/address&gt; &lt;p&gt; &lt;a href="http://www.agencyint.com"&gt; www.agencyint.com &lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;span data-toggle=".info-cov-0"&gt; Additional trading information &lt;i class="icon plus"&gt; &lt;/i&gt; &lt;/span&gt; &lt;ul class="result-info info-cov-0 cc"&gt; &lt;li&gt; &lt;strong&gt; Accepts Business From: &lt;/strong&gt; &lt;ul class="cc"&gt; &lt;li&gt; U.S.A &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;strong&gt; Classes of business &lt;/strong&gt; &lt;ul class="cc"&gt; &lt;li&gt; Engineering &lt;/li&gt; &lt;li&gt; NM General Liability (US direct) &lt;/li&gt; &lt;li&gt; Property D&amp;amp;F (US binder) &lt;/li&gt; &lt;li&gt; Terrorism &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;strong&gt; Disclaimer: &lt;/strong&gt; &lt;p&gt; Please note that while coverholders may have been approved by Lloyd's to accept business from the regions shown: &lt;/p&gt; &lt;p&gt; it is the responsibility of the parties, including the coverholder and any Lloyd's managing agent appointing them to ensure that the coverholder complies with all local regulatory and legal requirements; and &lt;/p&gt; &lt;p&gt; the coverholder may not provide cover for all classes they are approved to underwrite in all territories where they have approval. &lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="contact-details"&gt; &lt;h2&gt; ABCO Insurance Underwriters Inc &lt;/h2&gt; &lt;br/&gt; &lt;address&gt; ABCO Building, 350 Sevilla Avenue, Suite 201 &lt;br/&gt; Coral Gables &lt;br/&gt; Florida &lt;br/&gt; U S A &lt;br/&gt; 33134 &lt;/address&gt; &lt;p&gt; &lt;a href="http://www.abcoins.c…

http://stackoverflow.com/q/49052588
has title: How to convert from c3d file to csv
favorite count: 0
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49052759
type: Question
tagged with: numpy
has body: Hi i have a project were the user uploads a .c3d file to be able to display the data on charts, so i am making it for when the user uploads a the file it gets converted into a .csv file so i can get the values but i am having no luck trying to convert from the .c3d file to the .csv extension. i have used the following documentation http://c3d.readthedocs.io/en/stable/ but there much isn't much information on this out there this is the following code i use to print the data: import c3d reader = c3d.Reader(open('file.c3d', 'rb')) for i, points, analog in reader.read_frames(): print('frame {}: {}'.format(i, points.round(2)))
accepted answer: http://stackoverflow.com/a/49052759
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49102978
type: AnsweredQuestion
has body: The github issue 2446 says if we want to train from scratch, we need to comment this line in the model.config: #fine_tune_checkpoint: "PATH_TO_BE_CONFIGURED/model.ckpt" from_detection_checkpoint: true I followed this issue and commented this line for training the SSD_mobilenet in my own dataset. It can train and the loss can reduce, but the accuracy keep at 0.0. I used the object detection api before with pre-train model from model zoo, it works well at mAP=90%, the only difference between these two tasks is the comment line in model.config. I want to know how to train a detection model from scratch using the object detection api in TensorFlow. Thanks!
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/49105854
type: Question
score: 5
upvote count: 5
has title: How to train from scratch in TensorFlow object detection API?
tagged with: deep-learning
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49105854
tagged with: python
has comment: http://stackoverflow.com/comment/99901501
tagged with: object-detection

keras
tags question: http://stackoverflow.com/q/49009386
tags question: http://stackoverflow.com/q/49005616
tags question: http://stackoverflow.com/q/49052621
tags question: http://stackoverflow.com/q/48976413
tags question: http://stackoverflow.com/q/49100680
tags question: http://stackoverflow.com/q/49100959
tags question: http://stackoverflow.com/q/49108256
tags question: http://stackoverflow.com/q/49011306
tags question: http://stackoverflow.com/q/49018861
tags question: http://stackoverflow.com/q/49008862
tags question: http://stackoverflow.com/q/49102300
tags question: http://stackoverflow.com/q/49034250
tags question: http://stackoverflow.com/q/49031309
tags question: http://stackoverflow.com/q/49019383
tags question: http://stackoverflow.com/q/49107489
tags question: http://stackoverflow.com/q/49069195
tags question: http://stackoverflow.com/q/48999585
tags question: http://stackoverflow.com/q/49117712
tags question: http://stackoverflow.com/q/48982715
tags question: http://stackoverflow.com/q/49096281
tags question: http://stackoverflow.com/q/49020509
tags question: http://stackoverflow.com/q/49005892
tags question: http://stackoverflow.com/q/49038622
tags question: http://stackoverflow.com/q/48979830
tags question: http://stackoverflow.com/q/49058777
tags question: http://stackoverflow.com/q/49091553
tags question: http://stackoverflow.com/q/48997418
tags question: http://stackoverflow.com/q/49076032
tags question: http://stackoverflow.com/q/49112683
tags question: http://stackoverflow.com/q/49081813
tags question: http://stackoverflow.com/q/49072359
tags question: http://stackoverflow.com/q/49048758
tags question: http://stackoverflow.com/q/49058179
tags question: http://stackoverflow.com/q/49093797
tags question: http://stackoverflow.com/q/49047990
tags question: http://stackoverflow.com/q/49006083
tags question: http://stackoverflow.com/q/49066006
tags question: http://stackoverflow.com/q/49079115
tags question: http://stackoverflow.com/q/49007066
tags question: http://stackoverflow.com/q/48994155
tags question: http://stackoverflow.com/q/49089775
tags question: http://stackoverflow.com/q/49075760
tags question: http://stackoverflow.com/q/49120961
tags question: http://stackoverflow.com/q/49037211
tags question: http://stackoverflow.com/q/48997385
tags question: http://stackoverflow.com/q/49111590
tags question: http://stackoverflow.com/q/48987959
tags question: http://stackoverflow.com/q/49103531
tags question: http://stackoverflow.com/q/48964861
tags question: http://stackoverflow.com/q/49063535
tags question: http://stackoverflow.com/q/48971221
tags question: http://stackoverflow.com/q/49002562
tags question: http://stackoverflow.com/q/49118273
tags question: http://stackoverflow.com/q/48964836
tags question: http://stackoverflow.com/q/49083198
tags question: http://stackoverflow.com/q/48982092
tags question: http://stackoverflow.com/q/49008074
tags question: http://stackoverflow.com/q/49109014
tags question: http://stackoverflow.com/q/49081129
tags question: http://stackoverflow.com/q/48988309
tags question: http://stackoverflow.com/q/49023063
tags question: http://stackoverflow.com/q/49099700
tags question: http://stackoverflow.com/q/49050306
tags question: http://stackoverflow.com/q/49016530
tags question: http://stackoverflow.com/q/49017331
tags question: http://stackoverflow.com/q/49069026
tags question: http://stackoverflow.com/q/49062592
tags question: http://stackoverflow.com/q/49035200
tag name: keras
tags question: http://stackoverflow.com/q/48991644
tags question: http://stackoverflow.com/q/49097124
tags question: http://stackoverflow.com/q/49065008
tags question: http://stackoverflow.com/q/48978609
tags question: http://stackoverflow.com/q/49080405
tags question: http://stackoverflow.com/q/49118388
tags question: http://stackoverflow.com/q/49006686
type: Tag
tags question: http://stackoverflow.com/q/49044398
tags question: http://stackoverflow.com/q/49078266
tags question: http://stackoverflow.com/q/48972735

http://stackoverflow.com/comment/133229473
comment on: http://stackoverflow.com/a/49051189
type: AnswerComment
has text: A last colon is wrong there.
score: 0
type: Comment

http://stackoverflow.com/a/49094745
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49093292
answers question: http://stackoverflow.com/q/49093292
has comment: http://stackoverflow.com/comment/85273385
has body: Jacques's answer is correct, but it doesn't mention an important point: the state of LSTM layer almost always equals to the output. The difference becomes important when the chain of LSTM cells is long and not all input sequences have equal length (and hence are padded). That's when you should distinguish the state and output. See the runnable example in my answer on a similar question (it uses BasicRNNCell, but you'll get the same result with LSTMCell).
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48998246
has comment: http://stackoverflow.com/comment/85021956
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/85011999
tagged with: numpy
has comment: http://stackoverflow.com/comment/85021145
score: 0
has answer: http://stackoverflow.com/a/49009732
answer count: 1
has title: mashing 2D domain and streamplot
has comment: http://stackoverflow.com/comment/85018359
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85015875
has body: can someone tell me how can i get mesh for domain showed in picture below? this is example of meshing simple rectangular domain x_start, x_end = 0. , 10. y_start , y_end = 0. , 8. i = np.linspace(x_start, x_end, 80) j = np.linspace(y_start, y_end, 50) X,Y = np.meshgrid(i,j) Dx = x_end/(np.size(i)-1) Dy = y_end/(np.size(j)-1) beta = Dx/Dy nx = np.size(i) ny = np.size(j) plt.figure() plt.plot(X,Y) plt.show() How can i get mesh grid only for this rectangular domain:

http://stackoverflow.com/q/49016294
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85042818
has body: I have a Pyomo model and I'd like to get the gradient and Hessian of the objective. A related SO question asks the same question. When I try the solution proposed there from pyomo.core.base.symbolic import differentiate from pyomo.core.base.expr import identify_variables varList = list(identify_variables(zipfe.loglikelihood.expr)) firstDerivs = differentiate(zipfe.loglikelihood.expr, wrt_list=varList) I get the following error: Traceback (most recent call last): File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-9-6f2637b1fe13&gt;", line 1, in &lt;module&gt; firstDerivs = differentiate(zipfe.loglikelihood.expr, wrt_list=varList) File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/pyomo/core/base/symbolic.py", line 122, in differentiate tmp_expr, locals=dict((str(x), x) for x in sympy_vars) ) File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/sympy/core/sympify.py", line 354, in sympify expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate) File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/sympy/parsing/sympy_parser.py", line 894, in parse_expr return eval_expr(code, local_dict, global_dict) File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/sympy/parsing/sympy_parser.py", line 807, in eval_expr code, global_dict, local_dict) # take local objects in preference File "&lt;string&gt;", line 1, in &lt;module&gt; TypeError: 'Symbol' object does not support indexing Here is how my objective looks like (first few lines): zipfe.loglikelihood.pprint() loglikelihood : Size=1, Index=None, Active=True Key : Active : Sense : Expression None : True : minimize : log( 1 + exp( alpha1[0] + 2.0*alpha1[1] + alpha1[4] + 2.8986705607108596*( delta[0] + 2.0*delta[1] ) ) ) - ( 2.0*beta1[0] + beta1[3] + 2.8986705607108596*( gamma[0] + 2.0*gamma[1] ) )…
tagged with: python
type: UnansweredQuestion
score: 1
has title: Get Gradient and Hessian of objective in Pyomo
upvote count: 1
has answer: http://stackoverflow.com/a/49023605
type: Question
tagged with: pyomo
linked to: http://stackoverflow.com/q/46570022
tagged with: sympy

http://stackoverflow.com/comment/85114129
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49054534
has text: if you run your project properly instead of hacking-it-all-up, it will find it. Obviously if he wants to have scripts instead of package, then it's another story.
score: 0

http://stackoverflow.com/q/49091089
has answer: http://stackoverflow.com/a/49691779
has title: How to rename files with python?
type: UnansweredQuestion
tagged with: python
score: -5
has body: I need help correcting this error import os def rename_file () : # 1. get file names from a folder file_list = os.listdir(r"E:\Downloads\prank\prank") #print (file_list) saved_path = os.getcwd() print ("current working directory is "+saved_path) os.chdir (r"E:\Downloads\prank\prank") # 2. for each file, rename filename for file_name in file_list: os.rename(file_name, file_name.translate(None,"0123456789")) os.chdir(saved_path) rename_file() Thanks in advance for all the help.
type: Question
has comment: http://stackoverflow.com/comment/85190202
upvote count: 0
downvote count: 5
tagged with: python-2.7
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48987503
type: Question
upvote count: 1
answer count: 1
has title: How to insert item selected from one treeview to another treeview
favorite count: 0
has answer: http://stackoverflow.com/a/48988784
accepted answer: http://stackoverflow.com/a/48988784
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
has body: I have this code to select item from tkinter treeview to another tkinter treeview but when i select the item to insert it the id of item selected is inserted rather but not the content of the id. when i insert in the tree2 with this tree2.insert("", tk.END, values=n) it insert the last content of the List blow no matter what item i select. from tkinter import ttk import tkinter as tk blow = [("january", "2013"),("february", "2014"),("march", "2015"),("april", "2016"),("may", "2017")] def append_select(): for my in tree.selection(): tree2.insert("", tk.END, values=my) # tree2.insert("", tk.END, values=n) # this insert last content in the list root = tk.Tk() root.geometry("500x500") tree = ttk.Treeview(columns=("columns1", "columns"), show="headings", selectmode="browse") tree.heading("#1", text="Month") tree.heading("#2", text="Year") for n in blow: tree.insert("", tk.END, values=(n)) tree.pack() b1 = tk.Button(text="append", command=append_select) b1.pack() tree2 = ttk.Treeview(columns=("Month", "Year"), show="headings") tree2.heading("#1", text="First name") tree2.heading("#2", text="Surname") tree2.pack() root.mainloop()
score: 1

http://stackoverflow.com/comment/85030286
comment on: http://stackoverflow.com/a/48996453
score: 0
type: AnswerComment
type: Comment
has text: @Netwave You should be using [`timeit`](https://docs.python.org/2/library/timeit.html) module to measure the performance. And as far as I know, these are best *(most performance efficient)* ways to achieve there respective tasks.

http://stackoverflow.com/comment/85235412
has text: I don't understand your case. Why are you calling it in a loop?
comment on: http://stackoverflow.com/q/49114306
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84951367
comment on: http://stackoverflow.com/q/48973202
type: QuestionComment
has text: Have you tried Google ?
score: 4
type: Comment

http://stackoverflow.com/comment/85089080
comment on: http://stackoverflow.com/a/49041920
type: Comment
has text: Great,Thank you for the help, its working as i want now :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/104287089
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48978569
has text: @wwii if really huge dataframe thwn you are right. first filter by condition which remove the most rows, assign to dataframe. then filter by second and similar...
score: 0

frontend
tags question: http://stackoverflow.com/q/49114479
tag name: frontend
type: Tag

http://stackoverflow.com/q/48969009
possible better answer: http://stackoverflow.com/a/48969123
has comment: http://stackoverflow.com/comment/84943625
score: 1
has answer: http://stackoverflow.com/a/48969030
accepted answer: http://stackoverflow.com/a/48969030
has body: I am having a very strange issue, with the following code (removed all irrelevant parts, so the code probably looks like it does nothing): def get_items(cred, items): for i in range(0, len(items)): for j in range(0, len(items)): if items[i] + items[j] == cred: result = [i + 1, j + 1] result.sort() break else: result = [None, None] return result def main(): for idx, val in enumerate(content): cred = 200 items = [150, 24, 79, 50, 88, 345, 3] output = get_items(cred, items) The problem I am having is with the if items[i] + items[j] == cred: line, because it should be true (when i = 0 and j = 3), but it never evaluates to true, depsite the fact that I have tried printing out both items[i] + items[j] and cred right before the if statement, and they both show up as 200. Yet the get_items method returns [None, None]. They are both definitely integers, so I am completely lost as to how this is happening?
answer count: 2
has comment: http://stackoverflow.com/comment/84943616
upvote count: 1
linked to: http://stackoverflow.com/q/42913798
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48969123
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
has title: Comparison operator not recognizing two identical numbers
type: Question

http://stackoverflow.com/a/49002820
answers question: http://stackoverflow.com/q/49002726
score: 1
downvote count: 0
has body: Try this: wkr_hours = str("""select * from dbo.month_step where mont_id in \ (%s) and tier = 'Sil';""")%(",".join(map(lambda x:"'"+x+"'",months_list[no_of_months:])))
type: Answer
upvote count: 1

opencv
tags question: http://stackoverflow.com/q/49049746
type: Tag
tags question: http://stackoverflow.com/q/49005158
tags question: http://stackoverflow.com/q/49065313
tags question: http://stackoverflow.com/q/49121072
tags question: http://stackoverflow.com/q/49008854
tags question: http://stackoverflow.com/q/49100256
tags question: http://stackoverflow.com/q/49098147
tags question: http://stackoverflow.com/q/49031879
tags question: http://stackoverflow.com/q/49099956
tags question: http://stackoverflow.com/q/48995767
tags question: http://stackoverflow.com/q/48975874
tags question: http://stackoverflow.com/q/48988503
tags question: http://stackoverflow.com/q/49048111
tags question: http://stackoverflow.com/q/49050397
tags question: http://stackoverflow.com/q/49010883
tags question: http://stackoverflow.com/q/48969022
tags question: http://stackoverflow.com/q/48965404
tags question: http://stackoverflow.com/q/49043070
tags question: http://stackoverflow.com/q/49045481
tags question: http://stackoverflow.com/q/49012323
tags question: http://stackoverflow.com/q/49071592
tags question: http://stackoverflow.com/q/49098518
tags question: http://stackoverflow.com/q/49033670
tags question: http://stackoverflow.com/q/48999493
tags question: http://stackoverflow.com/q/48991494
tags question: http://stackoverflow.com/q/48996044
tags question: http://stackoverflow.com/q/49069317
tags question: http://stackoverflow.com/q/49049318
tags question: http://stackoverflow.com/q/49079685
tags question: http://stackoverflow.com/q/49094009
tags question: http://stackoverflow.com/q/49029751
tags question: http://stackoverflow.com/q/49114573
tags question: http://stackoverflow.com/q/48966465
tags question: http://stackoverflow.com/q/49056020
tag name: opencv
tags question: http://stackoverflow.com/q/49058179
tags question: http://stackoverflow.com/q/49111578
tags question: http://stackoverflow.com/q/49096804
tags question: http://stackoverflow.com/q/48972062
tags question: http://stackoverflow.com/q/49068444
tags question: http://stackoverflow.com/q/49102073
tags question: http://stackoverflow.com/q/49109946
tags question: http://stackoverflow.com/q/49099424
tags question: http://stackoverflow.com/q/49093729
tags question: http://stackoverflow.com/q/49060054
tags question: http://stackoverflow.com/q/49036849
tags question: http://stackoverflow.com/q/49098137
tags question: http://stackoverflow.com/q/48976002
tags question: http://stackoverflow.com/q/49025795
tags question: http://stackoverflow.com/q/49042424
tags question: http://stackoverflow.com/q/49101544
tags question: http://stackoverflow.com/q/48979219
tags question: http://stackoverflow.com/q/49088100
tags question: http://stackoverflow.com/q/49024118
tags question: http://stackoverflow.com/q/49059035
tags question: http://stackoverflow.com/q/49049518
tags question: http://stackoverflow.com/q/49001370
tags question: http://stackoverflow.com/q/49073906
tags question: http://stackoverflow.com/q/49029687
tags question: http://stackoverflow.com/q/49029310
tags question: http://stackoverflow.com/q/49084143
tags question: http://stackoverflow.com/q/48973777
tags question: http://stackoverflow.com/q/48984583
tags question: http://stackoverflow.com/q/48970272
tags question: http://stackoverflow.com/q/49013007
tags question: http://stackoverflow.com/q/49091198
tags question: http://stackoverflow.com/q/49075670
tags question: http://stackoverflow.com/q/49062816
tags question: http://stackoverflow.com/q/49104023
tags question: http://stackoverflow.com/q/49117362
tags question: http://stackoverflow.com/q/49095446
tags question: http://stackoverflow.com/q/49111804
tags question: http://stackoverflow.com/q/48992833
tags question: http://stackoverflow.com/q/49102778
tags question: http://stackoverflow.com/q/49083643
tags question: http://stackoverflow.com/q/49118029
tags question: http://stackoverflow.com/q/49108505
tags question: http://stackoverflow.com/q/49038464
tags question: http://stackoverflow.com/q/49119090

http://stackoverflow.com/comment/85117275
comment on: http://stackoverflow.com/a/49055880
type: AnswerComment
score: 0
type: Comment
has text: Yes exactly, the two dictionaries do have different sets of emails. So I am looking to add the contents of the smaller second dictionary to the first dictionary, keeping in mind that the emails added must transfer to the correct system, and must prioritize the 3 systems with the lowest count (SysMin variable)

http://stackoverflow.com/comment/85189516
type: Comment
type: QuestionComment
has text: Well I do run "cost" which should call "prediction" and subsequently the flow of control should go within conv_net(). That's how tensorflow works
comment on: http://stackoverflow.com/q/49091401
score: 0

http://stackoverflow.com/a/49116788
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49113523
has comment: http://stackoverflow.com/comment/85300399
score: 2
has comment: http://stackoverflow.com/comment/85311212
has comment: http://stackoverflow.com/comment/85245360
downvote count: 0
answers question: http://stackoverflow.com/q/49113523
has body: To expand on the comments made by @Adirio You could make a decorator that accomplishes this dynamically. In this particular implementation, when the decorated method is called it will do a partial bind of the provided arguments to the method and uses the method's signature to determine what parameters have not been provided. For any unspecified argument, if the calling object has an attribute matching the unspecified parameter name, the object's attribute value will be injected into the function. import inspect class BindableConstructor(object): def __init__(self, meth): self.meth = meth self.sig = inspect.signature(self.meth) def __get__(self, obj, klass=None): if obj is not None: print('Method ', repr(self.meth), ' called from instance ', repr(obj)) if klass is None: klass = type(obj) def newmeth(*args, **kwargs): ba = self.sig.bind_partial(*args, **kwargs) ba.apply_defaults() for paramname in self.sig.parameters: if paramname not in ba.arguments and hasattr(obj, paramname): ba.arguments[paramname] = getattr(obj, paramname) return self.meth(klass, *ba.args, **ba.kwargs) return newmeth Then suppose you have the following class using this decorator class MyClass(object): def __init__(self, y): self.y = y @BindableConstructor def my_constructor(cls, x, y): return cls(x + y) Then the following behavior would be observed &gt;&gt;&gt; a = MyClass(5) &gt;&gt;&gt; b = MyClass.my_constructor(3, 2) &gt;&gt;&gt; b &lt;__main__.MyClass object at 0x0605C770&gt; &gt;&gt;&gt; b.y 5 &gt;&gt;&gt; c = b.my_constructor(3) # c.y == b.y + 3 Method &lt;function MyClass.my_constructor at 0x05396420&gt; called from instance &lt;__main__.MyClass object at 0x0605C770&gt; &gt;&gt;&gt; c.y 8 In this particular case ba.apply_defaults is called before checking the object's attributes to inject. If you want the object's attributes to take precedence over defaults, call ba.apply_defaults after the parameter injection logic.
has comment: http://stackoverflow.com/comment/85246165

http://stackoverflow.com/comment/86629742
comment on: http://stackoverflow.com/a/49501641
type: AnswerComment
type: Comment
score: 1
has text: Yep, that's the current recommendation. The caveat is that it costs you a thread, which in some scenarios is more than some developers want to pay.

http://stackoverflow.com/q/49072822
type: UnansweredQuestion
tagged with: python
tagged with: text
tagged with: list
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85153158
has answer: http://stackoverflow.com/a/49073388
has body: I have a list with numerical data. Numbers are separated with a dot "." and a space " " unless they are negative, in which case the space " " is replaced by the negative sign "-". I've been having trouble getting out all of the information, which should fit in a 2982x16 matrix, because the numbers are not separated in the same fashion. Part of the list is something like this: 1. 1.3884e-17. 0.0000e+00. 1.1913e+00. 1.3996e+00.-7.7122e-01.-1.8788e-01.-5.3170e-16. 1.0076e-31. 0.0000e+00. 3.9673e+05.-1.9531e+05.-3.6224e+04.-7.2504e-11. 1.3740e-26. 0.0000e+00 2. 1.3573e-17. 7.3889e-02. 1.3726e+00. 1.6331e+00. 1.2526e+00. 1.5132e+00.-1.3979e-16.-5.3936e-32.-2.9361e-16. 5.9535e+05. 4.9158e+05. 5.6265e+05.-1.9062e-11.-7.3549e-27.-4.0038e-11 So far, I've only been able to extract the first two columns with something like this: mat[i,1]=ast.literal_eval(line[3+k:13+k].replace(" ","")) with the first piece aimed at converting text into float and the last part aimed at eliminating a space in the text. In this case, the number '1.3884e-17' and '1.3573e-17' would be placed in the second column of my matrix, but this doesn't really work for the following, of course changing the indices of the list. Any help would be appreciated.
has answer: http://stackoverflow.com/a/49073128
score: 0
has title: How to extract data from a list with a for loop
has comment: http://stackoverflow.com/comment/85151456
tagged with: extract

http://stackoverflow.com/comment/85237544
score: 0
type: Comment
type: QuestionComment
has text: i would just use the angle -- but remember that if the angles are 180 degrees (*pi* radians) different, they're also parallel
comment on: http://stackoverflow.com/q/49115765

http://stackoverflow.com/a/49082043
has comment: http://stackoverflow.com/comment/85288352
accepted answer of: http://stackoverflow.com/q/49081980
answers question: http://stackoverflow.com/q/49081980
has body: In a class definition, Python transforms __x into _classname__x. This is called name mangling. Its purpose is to support class local references so that subclasses don't unintentionally break the internal logic of the parent class.
score: 2
has comment: http://stackoverflow.com/comment/85169586
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/84999993
type: Comment
comment on: http://stackoverflow.com/a/48996799
score: 0
type: AnswerComment
has text: @cool_beans, in my full example, output is a list of strings, e.g. `['KFC CHicken Gravy Coke Biscuit This is my Order lf lf']`

http://stackoverflow.com/comment/85003166
score: 3
has text: You don't need to escape double quotes to send them over a TCP socket.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48998881

http://stackoverflow.com/comment/85030400
type: Comment
score: 1
comment on: http://stackoverflow.com/a/49011962
type: AnswerComment
has text: Hello Abraham, thanks for your answer!! That definitely helps and makes sense, i could just add "/creator_bio" behind all the urls and then scrape from there right? Didn't think about this haha, thanks a lot.

http://stackoverflow.com/q/48996194
has answer: http://stackoverflow.com/a/48996354
answer count: 2
has answer: http://stackoverflow.com/a/48996535
tagged with: pandas
has comment: http://stackoverflow.com/comment/84997990
tagged with: python
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85000972
has body: I'd like to know how one would go about shuffle in-place the values in a specified "rectangle" of values in a DataFrame. For example, say I'd like to shuffle the values in the rectangle of data defined by columns 4 to 7 AND rows 12 to 18, inclusive. The idea is to scramble the values in those cells WITHOUT affecting the values outside the rectangle.
type: Question
has title: Shuffle a row-column block within a pandas DataFrame

http://stackoverflow.com/a/49023382
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48997998
upvote count: 2
has body: try this with replaceWith functionality soup = BeautifulSoup(feature1, "lxml") tag=soup.find("span", {"class":"google-src-text"}) tag.replaceWith('') feature2 = soup.get_text() you can also use tag.decompose() instead of tag.replaceWith('')
has comment: http://stackoverflow.com/comment/85119217
type: Answer
has comment: http://stackoverflow.com/comment/136680915

http://stackoverflow.com/a/67432349
upvote count: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49087990
has body: I had the same problem because they implemented cloudfare in the api, I solved it this way import cloudscraper import json scraper = cloudscraper.create_scraper() r = scraper.get("MY API").text y = json.loads(r) print (y)
score: 5

http://stackoverflow.com/comment/85145008
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49069887
has text: What if you don't `| tee inputTest.txt`?
type: Comment

image
tags question: http://stackoverflow.com/q/49083840
tags question: http://stackoverflow.com/q/49086447
tags question: http://stackoverflow.com/q/48969104
tags question: http://stackoverflow.com/q/49065008
tags question: http://stackoverflow.com/q/48973335
tags question: http://stackoverflow.com/q/48969813
tags question: http://stackoverflow.com/q/49112027
tags question: http://stackoverflow.com/q/49116389
tags question: http://stackoverflow.com/q/49096804
tags question: http://stackoverflow.com/q/48983027
tags question: http://stackoverflow.com/q/48979219
tags question: http://stackoverflow.com/q/49035086
tags question: http://stackoverflow.com/q/49073950
tags question: http://stackoverflow.com/q/49070242
tags question: http://stackoverflow.com/q/49025832
tags question: http://stackoverflow.com/q/49069219
tags question: http://stackoverflow.com/q/49117783
tags question: http://stackoverflow.com/q/49024632
tag name: image
tags question: http://stackoverflow.com/q/49107716
tags question: http://stackoverflow.com/q/49000860
type: Tag
tags question: http://stackoverflow.com/q/49094535
tags question: http://stackoverflow.com/q/48983246

http://stackoverflow.com/comment/85144482
has text: The layout of widgets is always vertical in single line in django app(Column 1: 1,2,3,4,5,6,7,8) but when I run just the html file they appear as expected (Row 1:1,2,3,4) (Row 2:5,6,7,8) etc
comment on: http://stackoverflow.com/q/49036546
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49102229
type: Answer
has body: In Windows 10, you can enable long-path support for the system by setting a DWORD named "LongPathsEnabled" in "HKLM\System\CurrentControlSet\Control\FileSystem". This allows applications that declare support for long paths in their manifest to use the maximum path length that's supported by the kernel (about 32,760 characters, depending on the final resolved path), without even requiring the "\\?\" prefix. Python 3.6+ is manifested to support long paths. That said, prior to Windows 10, the working directory and relative paths cannot exceed MAX_PATH (260) characters, which includes the trailing backslash and NUL terminator. The current documentation is misleading on this point. Apparently someone added the disclaimer "to extend this limit to 32,767 wide characters..." to the docs for SetCurrentDirectory. No, there's no extending the limit. Here's what it said circa 2016. The current working directory of a process is a DOS path, as opposed to a native kernel path (*). A DOS path is any path that's non-Unicode, or uses forward slashes, DOS devices (e.g. logical drive letters, CON, NUL, etc), or UNC syntax. DOS paths have to be translated to native paths by runtime-library functions in ntdll.dll. If long-path support isn't available, this implicit translation is limited to at most MAX_PATH characters. Working around this requires using a fully-qualified Unicode path that begins with the "\\?\" prefix. This prefix tells the runtime-library to bypass path translation. Instead it simply replaces the "\\?\" prefix with the kernel's "\??\" virtual directory for DOS device links, and the path ultimately resolves to a real NT device (e.g. "\\?\UNC" => "\??\UNC" => "\Device\Mup"). (*) The kernel namespace uses a singly-rooted tree for all kernel objects, not just device objects. It also has a more reliable way of handling relative paths; see the RootDirectory field of OBJECT_ATTRIBUTES.
accepted answer of: http://stackoverflow.com/q/49054305
answers question: http://stackoverflow.com/q/49054305
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48966164
has body: the commands you show are not the steps suggested by the author of fastai. He suggests you: 1) Run Anaconda Prompt 2) Clone the repo 3) Run conda env update (which you seem to do after creating and activating a virtualenv) 4) Activate the new virtual environment. That said, you may want to look into updating your Anaconda: 1) conda update conda 2) conda update anaconda I tried this on my Windows 10 install, had the same error as you, updating did the trick. Good luck! PS: there is one difference between our systems: I see you are on Anaconda2, while I use Anaconda3. If all else fails, you may want to look into switching versions.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48964177
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48964177

http://stackoverflow.com/a/49039268
has body: @hpaulj thanks, your comment made me reload the file as I think it was somehow corrupted . I cannot trace what happened to it but the solution to this question was to check the file. The steps listed above in the question are correct. (I'm new to Stackoverflow and I'm pretty sure you cannot accept a comment as an answer so hopefully you will get credit here because I tagged your name?)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49038022

http://stackoverflow.com/comment/85034502
type: Comment
comment on: http://stackoverflow.com/a/49014801
type: AnswerComment
score: 0
has text: "I'd rather do a shuffle on a list of integers than the huge lines." Why? What advantage does that give you?

http://stackoverflow.com/q/49051492
score: 12
type: Question
answer count: 2
upvote count: 12
has comment: http://stackoverflow.com/comment/85107460
downvote count: 0
has comment: http://stackoverflow.com/comment/85176710
has comment: http://stackoverflow.com/comment/85107618
favorite count: 0
has comment: http://stackoverflow.com/comment/85107535
linked to: http://stackoverflow.com/q/16228248
type: UnansweredQuestion
tagged with: python
has body: I'm trying to rewrite this Python2 code to Python3 accepted syntax. The .index() methods generates the following error: AttributeError: 'dict_values' object has no attribute 'index' This is because .index() is no valid syntax in Python3. I've read that a list should be used to work around the problem, but I can't figure out how to do it. Anyone any idea how to work around the problem? words1 = [self._word_to_id.keys()[self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1)] indices = [i for i, w in enumerate(words1) if w in PUNCTUATIONS] for i in indices: words1[i], words1[i-1] = words1[i-1], words1[i] words2 = [self._word_to_id.keys([self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1, len(data_x))] all_words = words1 + [puncts[-1]] + words2 content = ' '.join(all_words) min_step = len(puncts)
has title: .index() generates AttributeError: 'dict_values' object has no attribute 'index'
has answer: http://stackoverflow.com/a/49051608
has answer: http://stackoverflow.com/a/49170090

http://stackoverflow.com/comment/85153034
type: Comment
comment on: http://stackoverflow.com/a/49073128
type: AnswerComment
has text: I must have been confused by the spec that it should fit in a m by 16 matrix. That first _number_ did look like a row number.
score: 0

http://stackoverflow.com/a/49142542
has comment: http://stackoverflow.com/comment/85316326
has comment: http://stackoverflow.com/comment/85317162
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85294311
has comment: http://stackoverflow.com/comment/85316905
has body: You have three errors in your algorithm: I don't know why you multiplied the absolute error by the value of the feature; this makes the error function quadratic, but you didn't compensate with any sqrt. Similarly, you failed to average the error amount before your weight adjustment; this effectively magnifies the changes by a factor equal to the number of training rows. Your loop order is inverted: you want to train the features in turn, one iteration each. You did it by training the intercept dummy first, then trying to take that value as an absolute and training the slope size afterward. You need to alternate them. After updates (and a couple of textual improvements): for j in range(100): for i in range(len(model)): errordelta = np.sum([(rental_price[x] - (model[0]*dummy[x] + model[1]*sqft[x])) for x in range(len(sqft))]) / len(sqft) print(model, errordelta) model[i] = model[i] + alpha*errordelta print(" sqft coeff", model[0]) print("dummy coeff", model[1]) Output: [0, 0] 455.5 [0.91100000000000003, 0] 454.589 [0.91100000000000003, 0.90917800000000015] -203.201283 [0.5045974339999999, 0.90917800000000015] -202.794880434 [0.5045974339999999, 0.50358823913200013] 90.649311554 [0.68589605710799573, 0.50358823913200013] 90.4680129309 ... [0.62996765105739105, 0.62870771575527662] -1.70530256582e-14 [0.62996765105739105, 0.62870771575527662] -1.70530256582e-14 sqft coeff 0.629967651057 dummy coeff 0.628707715755
upvote count: 1
answers question: http://stackoverflow.com/q/49075305
score: 1

http://stackoverflow.com/comment/85052037
has text: Scrapping [_Facebook_](https://www.facebook.com/) is against the [_ToS_](https://www.facebook.com/legal/terms) and you are liable to be questioned and may even land up in [_Facebook Jail_](https://www.facebook.com/help/community/question/?id=804287426255468). Use _Facebook API_ instead.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49010895

http://stackoverflow.com/comment/85000471
comment on: http://stackoverflow.com/q/48995995
type: Comment
has text: you need to know that when you are iterating over ``summary_data``, then ``i`` will not give you index. It will give you the elements directly. For example, if you have a list, ``lst = [6, 8, 5]``, in the first interation of ``for i in lst:``, you will have ``i==6``, in the second ``i==8``, in the third ``i==5``. This means that it does not make any sense to use ``i`` as an index.
type: QuestionComment
score: 0

http://stackoverflow.com/a/49094303
answers question: http://stackoverflow.com/q/49093473
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85194037
score: 1
has body: Can you try this? names = [df001, df002] for name in names: name.iloc[1,1]
accepted answer of: http://stackoverflow.com/q/49093473

http://stackoverflow.com/comment/85035696
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49014896
has text: What do you want to see in this window?
score: 0

http://stackoverflow.com/a/49039490
has comment: http://stackoverflow.com/comment/85084447
has body: In [27]: history.add(current, fill_value=0)[history.columns] Out[27]: above below asn country 12345 MX 7.0 3.0 US 5.0 4.0 54321 MX 4.0 6.0 US 1.0 0.0
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85090047
type: Answer
has comment: http://stackoverflow.com/comment/85091024
answers question: http://stackoverflow.com/q/49039402
upvote count: 9
accepted answer of: http://stackoverflow.com/q/49039402
score: 9

http://stackoverflow.com/q/48986640
has comment: http://stackoverflow.com/comment/84994568
has comment: http://stackoverflow.com/comment/84996169
upvote count: 3
has title: How to deal with large amount of HDF5 files in Google Cloud Machine Learning?
linked to: http://stackoverflow.com/q/44881895
tagged with: tensorflow
linked to: http://stackoverflow.com/q/37620330
has comment: http://stackoverflow.com/comment/84993825
has answer: http://stackoverflow.com/a/48996036
linked to: http://stackoverflow.com/q/42339876
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48992075
score: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: h5py
has comment: http://stackoverflow.com/comment/84994701
has comment: http://stackoverflow.com/comment/84994230
tagged with: google-cloud-ml
answer count: 2
has body: I have approximately 5k raw data input files and 15k raw data test files, several GB in total. Since those are raw data files, I had to process them iteratively in Matlab in order to obtain features that I want to train my actual classifier on (CNN). As a result, I produced one HDF5 mat file for each of the raw data files. I developed my model locally with usage of Keras and modified DirectoryIterator in which I had something like for i, j in enumerate(batch_index_array): arr = np.array(h5py.File(os.path.join(self.directory, self.filenames[j]), "r").get(self.variable)) # process them further Files structure is | |--train | |--Class1 | | |-- 2,5k .mat files | | | |--Class2 | |-- 2,5k .mat files |--eval | |--Class1 | | |-- 2k .mat files | | | |--Class2 | |-- 13k .mat files This is the files structure that I have right now in my Google ML Storage bucket. It was working locally with python with a small model but now I'd like to utilize Google ML hyper params tuning capabilities since my model is a lot bigger. The problem is that I read on the Internet that HDF5 files cannot be read directly and easily from the Google ML Storage. I tried to modify my script like this: import tensorflow as tf from tensorflow.python.lib.io import file_io for i, j in enumerate(batch_index_array): with file_io.FileIO((os.path.join(self.directory, self.filenames[j], mode='r') as input_f: arr = np.array(h5py.File(input_f.read(), "r").get(self.variable)) # process them further but it's giving me the error similar to this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte just with other hex and positon 512. I also had something like this: import tensorflow as tf from tensorflow.python.lib.io import file_io for i, j in enumerate(batch_index_array): with file_io.FileIO((os.path.join(self.directory, self.filenames[j], mode='rb') as input_f: arr = np.fromstring(input_f.read()) # process them further but it also doesn't work. Question How can I modify my…
has comment: http://stackoverflow.com/comment/84996219
tagged with: python
has comment: http://stackoverflow.com/comment/84996376

http://stackoverflow.com/q/49062737
favorite count: 0
has comment: http://stackoverflow.com/comment/85156197
has comment: http://stackoverflow.com/comment/85153058
has answer: http://stackoverflow.com/a/49077125
answer count: 1
downvote count: 1
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/85173144
has title: What are good implementations of high dimensional volume estimation in Python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85149536
score: 3
has comment: http://stackoverflow.com/comment/85156503
tagged with: math
has comment: http://stackoverflow.com/comment/85156572
type: Question
has body: I wanted to estimate the volume of a high dimensional shape in Python. I have an oracle for querying if I am inside the shape or not. I am in high dimension (at least 32*32=1024 dimensions). I ideally don't want to implement it myself because: seems highly technical with papers ranging in https://arxiv.org/pdf/1401.0120.pdf and it seems something a non expert can get easily wrong it seems to be a standard mathematics question (estimating volumes in high dims) so it seems sensible to assume a better optimized code than what I can hack in python might exist. Does someone know what is a good way to solve this? Should I go ahead an implement the one in the paper I linked? Not sure what what the mathematical technical constraints may be but: I have access to an oracle that says +1 or -1 depending if I'm inside the shape or not. I want to estimate the shape of a convex shape Right now I am just tempted to go ahead an implement something like: decide on a really bid sphere that most probably contains the shape I want to estimate sample many points (it would be nice to know how many I need to sample have a good estimate of my shape) however, since it seems a subtle technical field, I'd rather not get too hacky if I can avoid it (especially if I can get theoretical guarantees on the # of samples) Related links before I posted question: https://www.quora.com/unanswered/What-are-the-fastest-algorithms-to-implement-in-practice-that-estimate-high-dimensional-volumes https://arxiv.org/pdf/1401.0120.pdf https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html https://cstheory.stackexchange.com/questions/9573/computing-volume-of-high-dimensional-convex-polyhedra http://www.qhull.org/

http://stackoverflow.com/a/49013890
has comment: http://stackoverflow.com/comment/85033221
answers question: http://stackoverflow.com/q/49013719
has body: Your encryption method encryptor.encrypt() very likely accepts bytes as argument, not str. It also returns bytes very likely. So I suggest you to use the encode/decode methods as follows (example of utf-8 coding): out_file.write(encryptor.encrypt(chunk.encode('utf-8')).decode('utf-8'))
downvote count: 0
has comment: http://stackoverflow.com/comment/85033034
type: Answer
has comment: http://stackoverflow.com/comment/85032759
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85032582

http://stackoverflow.com/comment/85062608
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49029226
has text: Post some portion of the list on which your code fails.

http://stackoverflow.com/q/49048560
tagged with: ajax
has title: How can I implement the Django Admin Foreign Key's Add button?
has comment: http://stackoverflow.com/comment/89625440
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: django
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/49194727
linked to: http://stackoverflow.com/q/28068168
upvote count: 1
has body: I would like to implement the add button we have beside a ForeignKey field, so that we can add data to the field/database. I have been following a couple tutorials, but none of them help me actually add data to the field, and in turn, my database. I have also been looking everywhere but I can't seem to find anyone that has accomplished this task. A good tutorial I have been following is this one: https://djangopy.org/how-to/reverse-engineering-of-the-django-admin-foreign-keys-addedit-button/ However, the tutorial is very good until the end. He only implements the edit button, and not the add button. So I'm not sure which AJAX call I need to make in order to replicate that of which the admin add button does, when adding data for the ForeignKey. For the sake of brevity, all code from the tutorial is exactly what I have, I just need to implement a function for the add button. If anyone has any ideas or could point me into the right direction, that would be greatly appreciated.
tagged with: django-admin
type: UnansweredQuestion

http://stackoverflow.com/a/49084969
upvote count: 1
has body: Use getattr: def _do_something(o1, o2, keyatt): x = getattr(o1, keyatt) y = getattr(o2, keyatt) return x == y class A: def __init__(self, a, b): self.a = a self.b = b srcObj = A(1, 2) destObj = A(1, 10) print(_do_something(srcObj, destObj, 'a')) print(_do_something(srcObj, destObj, 'b')) Output: True False
score: 1
answers question: http://stackoverflow.com/q/49084920
accepted answer of: http://stackoverflow.com/q/49084920
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85175472

http://stackoverflow.com/a/50556493
has body: Here's a generic decorator that works with instance methods as well as functions (refer to Numpy's documentation for otypes and signature): from functools import wraps import numpy as np def vectorize(otypes=None, signature=None): """Numpy vectorization wrapper that works with instance methods.""" def decorator(fn): vectorized = np.vectorize(fn, otypes=otypes, signature=signature) @wraps(fn) def wrapper(*args): return vectorized(*args) return wrapper return decorator You may use it to vectorize your method as follows: class Dummy(object): def __init__(self, val=1): self.val = val @vectorize(signature="(),()-&gt;()") def f(self, x): if x == 0: return self.val else: return 2 def test_3(): assert list(Dummy().f([0, 1, 2])) == [1, 2, 2] The key is to make use of the signature kwarg. Parenthesized values to the left of -&gt; specify input parameters and values to the right specify output values. () represents a scalar (0-dimensional vector); (n) represents a 1-dimensional vector; (m,n) represents a 2-dimensional vector; (m,n,p) represents a 3-dimensional vector; etc. Here, signature="(),()-&gt;()" specifies to Numpy that the first parameter (self) is a scalar, the second (x) is also a scalar, and the method returns a scalar (either self.val or 2, depending on x). $ pytest /tmp/instance_vectorize.py ======================= test session starts ======================== platform linux -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0 rootdir: /tmp, inifile: collected 1 item ../../tmp/instance_vectorize.py . [100%] ==================== 1 passed in 0.08 seconds ======================
downvote count: 0
answers question: http://stackoverflow.com/q/48981501
type: Answer
upvote count: 5
score: 5

http://stackoverflow.com/comment/85139612
comment on: http://stackoverflow.com/q/49067127
type: QuestionComment
has text: @Kasramvd Re-opening because this question additionally needs the masking for the elements that are not present in `searched_values`. Hope that looks fair.
score: 0
type: Comment

http://stackoverflow.com/a/49070526
type: Answer
score: 1
has body: from etree Documentation find(match) Finds the first subelement matching match. match may be a tag name or path. Returns an element instance or None. So you should try xpath. This should work: print(root.find('.//{http://www.mediawiki.org/xml/export-0.10/}title').text)
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49069758
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85148967
accepted answer of: http://stackoverflow.com/q/49069758

http://stackoverflow.com/a/49046422
accepted answer of: http://stackoverflow.com/q/49046242
type: AcceptedAnswer
score: 0
type: Answer
has body: This is because you do not match all characters.If you remove anchors you will get a match.See demo. https://regex101.com/r/uRdqZj/2
answers question: http://stackoverflow.com/q/49046242

http://stackoverflow.com/comment/85003884
comment on: http://stackoverflow.com/q/48999291
type: Comment
has text: Use an extended slice, which allows you to specify a step value: `result = list[5::5]`
type: QuestionComment
score: 2

http://stackoverflow.com/q/49087371
tagged with: broadcast
downvote count: 0
has title: python broadcasting message via server
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85187315
has body: I am trying to broadcast a message to the subnet and i am giving the subnet address to the server to connect and the client throws error saying name or service unknown and not receiving the packet. Could anyone please tell me how do i broadcast message to my subnet such that client can also get that message or packet. exactly in the address area. My main doubts are about. which address is given at the client side and server side. Error i get at client side is : sending Traceback (most recent call last): File "/Threaded-server.py", line 11, in <module> sent=s.sendto(msg.encode(),address) socket.gaierror: [Errno -2] Name or service not known closing socket Process finished with exit code 1 Thanks client import socket import sys import json connected = False #connect to server client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((' ',10000)) connected = True while connected == True: #wait for server commands to do things, now we will just display things data = client_socket.recv(1024) cmd = json.loads(data) #we now only expect json if(cmd['type'] == 'bet'): bet = cmd['value'] print('betting is: '+bet) elif (cmd['type'] == 'result'): print('winner is: '+str(cmd['winner'])) print('payout is: '+str(cmd['payout'])) ##Server import socket, time, sys import threading import pprint TCP_IP = '192.168.1.255' TCP_PORT = 10000 BUFFER_SIZE = 1024 clientCount = 0 class server(): def __init__(self): self.CLIENTS = [] def startServer(self): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(10) while 1: client_socket, addr = s.accept() print ('Connected with ' + addr[0] + ':' + str(addr[1])) global clientCount clientCount = clientCount+1 print (clientCount) # register client self.CLIENTS.append(client_socket) threading.Thread(target=self.playerHandler, args=(client_socket,)).start() s.close() except socket.error as msg: print ('Could Not Start Server Thread. Error Code : ') #+ str(msg[0]) + ' Message ' + ms…
score: 1
type: Question
tagged with: server

http://stackoverflow.com/comment/85223907
score: 0
type: AnswerComment
has text: Thank you for your answer. It works. Have a beautiful day :)
type: Comment
comment on: http://stackoverflow.com/a/49106713

http://stackoverflow.com/a/48971388
has comment: http://stackoverflow.com/comment/84954306
accepted answer of: http://stackoverflow.com/q/48970040
score: 5
answers question: http://stackoverflow.com/q/48970040
has comment: http://stackoverflow.com/comment/84954334
type: AcceptedAnswer
upvote count: 5
type: Answer
has body: The format of namespaced attribute name in lxml is {namespace-uri}local-name. So for xsi:schemaLocation, you basically want to add attribute with name: '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation' The {namespace-uri} part can be achieved using format() and the triple opening and closing braces which can be read as: {{: escaped opening braces; outputs literal { {pre}: placeholder; will be replaced by the value of variable xsi as specified in .format(pre=xsi) }}: escaped closing braces; outputs literal }
downvote count: 0

http://stackoverflow.com/q/49023079
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49023566
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I am writing a function to update the week number of any year date falls in between Dec29-Jan3. I tried as below and called function, but its showing exception as ('strptime() argument 1 must be string, not Series', u'occurred at index 0') def week_number_update(x): dec_day = [29,30,31] jan_day = [1,2,3] input_date = datetime.datetime.strptime(x, "%Y-%m-%d") input_month = input_date.month input_day = input_date.day if input_month == 12: if input_day in dec_day: week_number = datetime.date(input_date.year, 12, 28).isocalendar()[1] elif input_month == 1: if input_day in jan_day: week_number = datetime.date(input_date.year, 1, 4).isocalendar()[1] else: week_number = x['date'].dt.week return(week_number); Calling: df['week'] = df.apply(lambda x: week_number_update(x), axis=1) Thanks.
has title: Function to update the week number in python
has comment: http://stackoverflow.com/comment/85051295
tagged with: python
has answer: http://stackoverflow.com/a/49023566
score: 1
upvote count: 1

http://stackoverflow.com/a/49115748
has body: The default values for format properties are almost all 0/False. See the initialization code for a format object.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49112356
downvote count: 0
type: Answer

http://stackoverflow.com/q/49048086
has body: Here is my code. The field default_SampleType's value is shown for 2 seconds or so and then get lost.Question is why the value is not being preserved? The declaration the field as follows fields.Many2one(string='SampleType', comodel_name='olims.sample_type', required=True ), fields.Many2one(string='SampleType1', comodel_name='olims.sample_type', required=False ), fields.Many2one(string='SampleType2', comodel_name='olims.sample_type', required=False ), fields.Many2one(string='SampleType3', comodel_name='olims.sample_type', required=False ), When I replace sampleType with SampleType1 in context, then this value is shown and it does not get lost. I dont know what is the problem with SampleType field. result = { 'name': 'Analysis Request', 'view_type': 'form', 'res_model': 'olims.analysis_request', 'view_id': sample_record, 'context': {'default_SampleType': sample_type.id , 'default_Client': client.id, 'default_Sample_id': sample_id, 'default_SamplingDate': sampling_date, 'default_ClientReference': client_reference, 'default_ClientSampleID': client_sample_ID, 'default_SamplePoint': sample_point.id,'default_StorageLocation': storage_location.id, 'default_SamplingDeviation': sampling_deviation.id, 'default_SampleCondition': sample_condition.id, 'default_LotID': lot_id}, 'type': 'ir.actions.act_window', 'view_mode': 'form', } return result
tagged with: python-2.7
has title: Why some of the field are being lost when launching ir.actions.act.window from python code in odoo 9?
has comment: http://stackoverflow.com/comment/85100867
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85101038
type: Question
has comment: http://stackoverflow.com/comment/85102475
has comment: http://stackoverflow.com/comment/85102831
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/85100792
has answer: http://stackoverflow.com/a/49049356
tagged with: odoo
score: 0
tagged with: odoo-9
has comment: http://stackoverflow.com/comment/85102949
accepted answer: http://stackoverflow.com/a/49049356

http://stackoverflow.com/comment/85274548
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49092918
has text: A couple questions that may or may not help debug this: 1. What's the `if` statement in the last call of your traceback? 2. Are you running on Windows?

http://stackoverflow.com/q/49112008
upvote count: 3
has title: Iterate through row if statement and add to new columns [Pandas/Python]
tagged with: pandas
downvote count: 1
answer count: 1
favorite count: 0
has body: I have a dataframe with 3 columns Hospital 2009-10 2010-11 Aberystwyth Mental Health Unit 19 19 Bro Ddyfi Community Hospital 16 10 Bronglais General Hospital 160 148 Caebryn Mental Health Unit 37 39 Carmarthen Mental Health Unit 38 31 I am trying to create a function that checks if a word is in the hospital column if so it puts the word in the new column like so: Hospital 2009-10 2010-11 Hospital Type Aberystwyth Mental Health Unit 19 19 Mental Bro Ddyfi Community Hospital 16 10 Community Bronglais General Hospital 160 148 General Caebryn Mental Health Unit 37 39 Mental Carmarthen Mental Health Unit 38 31 Mental Heres the code I have tried: def find_type(x): if df['Hospital'].str.contains("Mental").any(): return "Mental" if df['Hospital'].str.contains("Community").any(): return "Community" else: return "Other" df['Hospital Type'] = df.apply(find_type) The output I get instead is this: Hospital 2009-10 2010-11 Hospital Type Aberystwyth Mental Health Unit 19 19 NaN Bro Ddyfi Community Hospital 16 10 NaN Bronglais General Hospital 160 148 NaN Caebryn Mental Health Unit 37 39 NaN Carmarthen Mental Health Unit 38 31 NaN How can I get it so it comes out like the expected output? Thank you!
tagged with: python
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/49112055
accepted answer: http://stackoverflow.com/a/49112055

http://stackoverflow.com/comment/85075305
type: QuestionComment
has text: Thank you for the answers! You are right about the _ni_label.pyx I cannot read cython, is anyone able to tell me which approach is used here? https://github.com/scipy/scipy/blob/master/scipy/ndimage/src/_ni_label.pyx The commenting is not very instructive after the beginning (forground extraction). That would be wonderful!
score: 0
comment on: http://stackoverflow.com/q/48996148
type: Comment

http://stackoverflow.com/q/49002229
downvote count: 1
has answer: http://stackoverflow.com/a/49002532
has title: Adding a column to a dataframe in pandas with proper indexing
accepted answer: http://stackoverflow.com/a/49002532
favorite count: 0
possible better answer: http://stackoverflow.com/a/49002370
tagged with: python
has answer: http://stackoverflow.com/a/49002370
has comment: http://stackoverflow.com/comment/85009227
type: AnsweredQuestion
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85009205
has body: I have two data frames each of one column. One data frame is "contained" in the other in the sense that the index values and corresponding data are included in the other. In a way, the sub-data frame is just filtered data from the first. I want to take the data from the sub-data frame and append it to a new column on the super-data frame where the index values in common have the corresponding shared data and the index values that are not in the sub-data frame simply have an np.nan as data. So far I have df2 "contained" in df1 (i.e. the filtered data). column1 = df1[0] column2 = df2[0] indx1 = df1.index indx2 = df2.index n = len(df1[column1]) m = len(df2[column2]) a = a = np.zeros(n) a[:] = np.nan df1['filtered'] = pd.Series(a, index=indx1) i = 0 j = 0 while i &lt; n: while j &lt; m: if indx1.values[i] == indx2.values[j]: df1['filtered'].set_value(indx1[i], df2[column2].get_value(indx2[j])) t = j break i = i+1 j = t+1 However this is not working for me, so any advice would be much appreciated. since it is syntactically correct (assuming I wrote it down here correctly), but it just runs forever. Thanks
score: 0
tagged with: pandas
upvote count: 1

http://stackoverflow.com/q/49039473
answer count: 2
has comment: http://stackoverflow.com/comment/85084365
tagged with: class
score: 0
tagged with: types
favorite count: 0
has comment: http://stackoverflow.com/comment/85085131
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I'm trying to implement new data type "Fractions" in Python to represents fractions, where numenator and denominator are both integers. Moreover, I have to implement four basic arithmetic operations. The trick is, I can't use classes in this task. I thoght maybe tuples can be a good idea but I really don't know how to approach this. Is there an easy way to solve such a problem? Any hint would really help me.
downvote count: 1
tagged with: fractions
has comment: http://stackoverflow.com/comment/85084675
has answer: http://stackoverflow.com/a/49039719
has comment: http://stackoverflow.com/comment/85084309
has comment: http://stackoverflow.com/comment/85084337
has answer: http://stackoverflow.com/a/49040272
type: Question
has title: Implementing new data type in Python - without classes

http://stackoverflow.com/q/49111908
has title: Comparing numerical results between mathematical operations performed with two different languages
possible better answer: http://stackoverflow.com/a/49115648
type: Question
answer count: 2
tagged with: numerical-methods
has comment: http://stackoverflow.com/comment/85230435
downvote count: 0
has body: I'm currently trying to port an algorithm from IDL to Python 3 and while comparing results I came across the following questioning: How do I look at the numbers and determine if I'm effectively reproducing the results? Assuming that different languages will deal slightly differently with pointing float precision it is expected that the results should be a bit different but up to which point this is acceptable? In the figure below I will use the mean values of the data sets produced by IDL and python to illustrate my point: While in some of the calculations I can see that the values are similar in others they don't quite hit the mark. Looking at the step below where a trace of the set of matrices that will be used to is used to determine if there are points where the solution is ill posed I had the following results for both IDL and Python: Which looks quite good (may I say that?). The (100, y-dimension, x-dimension) matrices where this trace was calculated from are then re-organised to calculate a least square fitting that is ultimately where the values that will create the means will arise. I'm using those comparisons to find clues on what need to be changed and improved on the python version therefore I appreciate any thoughts that can lead me in this direction. In advance I thank for your time.
favorite count: 0
tagged with: precision
accepted answer: http://stackoverflow.com/a/49112311
tagged with: python
has comment: http://stackoverflow.com/comment/85229166
has comment: http://stackoverflow.com/comment/85228955
upvote count: 1
type: AnsweredQuestion
tagged with: idl-programming-language
has answer: http://stackoverflow.com/a/49115648
has answer: http://stackoverflow.com/a/49112311
score: 1

http://stackoverflow.com/q/49093956
has answer: http://stackoverflow.com/a/51617288
score: 0
duplicate of: http://stackoverflow.com/q/12332975
tagged with: python
tagged with: module
accepted answer: http://stackoverflow.com/a/51617288
upvote count: 1
downvote count: 1
type: Question
type: AnsweredQuestion
has body: I have some code that uses modules that are not installed by default (eg. Numpy), and I want to give the program to a friend of mine who does not have that module. I do not want him to have to go through the tedious process of using cmd to install the module. Is there any way to install the module from within the code itself? Like: import pip pip.install('numpy') (completely hypothetical) BTW: I am using Windows 10
answer count: 1
linked to: http://stackoverflow.com/q/12332975
tagged with: python-3.6
has title: How to install modules using IDLE
favorite count: 0

http://stackoverflow.com/q/49064826
upvote count: 5
tagged with: oauth-2.0
accepted answer: http://stackoverflow.com/a/49065506
type: Question
has title: Using Google People API with Service Account
answer count: 2
score: 5
downvote count: 0
tagged with: google-api-python-client
possible better answer: http://stackoverflow.com/a/68585923
favorite count: 0
tagged with: google-people-api
has answer: http://stackoverflow.com/a/68585923
has answer: http://stackoverflow.com/a/49065506
has body: I'm using the Google People API to access my contacts. I activated it in the Google Developers Console and created a project, a service account (ending with ....iam.gserviceaccount.com) and a key for authentication which is stored in JSON format. When I access the contacts, it seems to take the contacts of my service account address rather than my Google account which results in an empty list. How can I tell the API to use my account rather than the service account? This is the code I have so far: from google.oauth2 import service_account from googleapiclient.discovery import build # pip install google-auth google-auth-httplib2 google-api-python-client SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] KEY = '~/private.json' credentials = service_account.Credentials.from_service_account_file( KEY, scopes=SCOPES) service = build( serviceName='people', version='v1', credentials=credentials) connections = service.people().connections().list( resourceName='people/me', personFields='names').execute() print(connections) # result: {}
tagged with: google-api
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85021273
type: Comment
comment on: http://stackoverflow.com/q/49007421
has text: Since there is no array element that corresponds to the center for an even sized structuring element, why not use the lower right one of the four. Try (4, 4) or (3, 2), (3, 4), (3, 6) to see that this is consistent.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49069317
has comment: http://stackoverflow.com/comment/85148326
has comment: http://stackoverflow.com/comment/85146457
tagged with: python
has comment: http://stackoverflow.com/comment/85147658
favorite count: 0
has comment: http://stackoverflow.com/comment/85146687
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85147304
has comment: http://stackoverflow.com/comment/85149209
has comment: http://stackoverflow.com/comment/85149715
has comment: http://stackoverflow.com/comment/85148825
has comment: http://stackoverflow.com/comment/85149330
has comment: http://stackoverflow.com/comment/85144910
tagged with: opencv
has title: No image from the camera using cv2.VideoCapture
has comment: http://stackoverflow.com/comment/85144744
has comment: http://stackoverflow.com/comment/85146448
has comment: http://stackoverflow.com/comment/85149037
has comment: http://stackoverflow.com/comment/85145325
has comment: http://stackoverflow.com/comment/85148704
has comment: http://stackoverflow.com/comment/85146913
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49072288
has body: I use WebCam(Genius FaceCam 1020),Python(3.6.4), OpenCV(3.4.0.12), and Opencv documentation code, this one: import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() Runs without errors, but the image does not appear in the window. The indicator on the camera lights up. I have tried copy opencv_ffmpeg.dll, Rename the opencv_ffmpeg.dll in this manner: For OpenCV version X.Y.Z opencv_ffmpeg.dll ==&gt; opencv_ffmpegXYZ.dll For 64-bit OpenCV version X.Y.Z opencv_ffmpeg.dll ==&gt; opencv_ffmpegXYZ_64.dll Namely opencv_ffmpeg34012.dll and opencv_ffmpeg34012_64.dll. But it does not help.
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/48827085
score: 4
has comment: http://stackoverflow.com/comment/85148713

http://stackoverflow.com/a/49063525
has comment: http://stackoverflow.com/comment/85132599
has comment: http://stackoverflow.com/comment/85133046
accepted answer of: http://stackoverflow.com/q/49063237
has body: This code parses the downloaded "fixtures" file that you can download at the top of the url you gave. I know it's not the way to seem to prefer but the information seems fairly up to date. For example, the website shows matches that seem to have been played already (from February) but the .ics file starts with a match that is to be played tomorrow (March 2nd). &gt;&gt;&gt; import re ... from datetime import datetime ... ... REGEX = re.compile(r'''\ ... SUMMARY:(?P&lt;team&gt;.+)\n ... DTSTART:(?P&lt;start&gt;.+)\n ... DTEND:(?P&lt;end&gt;.+)\n ... LOCATION:(?P&lt;location&gt;.+)\n''', re.VERBOSE) ... ... ... def to_datetime(s): ... return datetime.strptime(s, '%Y%m%dT%H%M00Z') ... ... ... result = [] ... with open('Pakistan_Super_League.ics', 'r') as f: ... for m in REGEX.finditer(f.read()): ... current = m.groupdict() ... start = to_datetime(current['start']) ... result.append({ ... 'team': current['team'], ... 'date': start.strftime('%a %b %d'), ... 'time': start.strftime('%H:%M') ... }) ... &gt;&gt;&gt; for event in result: ... print(event) ... {'team': '11th Match Multan Sultans v Karachi Kings', 'date': 'Fri Mar 02', 'time': '11:30'} {'team': '12th Match Lahore Qalandars v Islamabad United', 'date': 'Fri Mar 02', 'time': '16:00'} {'team': '13th Match Multan Sultans v Quetta Gladiators', 'date': 'Sat Mar 03', 'time': '11:30'} {'team': '14th Match Peshawar Zalmi v Lahore Qalandars', 'date': 'Sat Mar 03', 'time': '16:00'} {'team': '15th Match Islamabad United v Karachi Kings', 'date': 'Sun Mar 04', 'time': '16:00'} {'team': '16th Match Peshawar Zalmi v Multan Sultans', 'date': 'Tue Mar 06', 'time': '16:00'} {'team': '17th Match Multan Sultans v Quetta Gladiators', 'date': 'Wed Mar 07', 'time': '16:00'} {'team': '18th Match Islamabad United v Lahore Qalandars', 'date': 'Thu Mar 08', 'time': '11:30'} {'team': '19th Match Karachi Kings v Quetta Gladiators', 'date': 'Thu Mar 08', 'time': '16:00'} {'team': '20th Match Multan Sultans v Lahore Qalandars', 'date': 'Fri Ma…
type: Answer
answers question: http://stackoverflow.com/q/49063237
has comment: http://stackoverflow.com/comment/85133376
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/49029406
answers question: http://stackoverflow.com/q/49029196
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85063147
type: Answer
has body: The session is not saved by default. Add request.session.modified = True: def question_filter(request): if request.method == 'POST': print('before validation', request.POST) request.session['question_data'] = request.POST request.session.modified = True return HttpResponseRedirect(reverse('qapp:question_preview')) https://docs.djangoproject.com/en/2.0/topics/http/sessions/#when-sessions-are-saved Edit: You can hack it using json: import json def question_filter(request): if request.method == 'POST': print('before validation', request.POST) request.session['question_data'] = json.dumps(request.POST) return HttpResponseRedirect(reverse('qapp:question_preview')) def question_preview(request): all_questions = Questions.objects.all() question_data = json.loads(request.session.get('question_data')) print(question_data) question_pk_list = question_data['question_pk'] preview_questions = all_questions.filter(id__in=question_pk_list) ... return render(request,'apps/qapp/question_preview.html', {somecontext})

http://stackoverflow.com/a/48971406
has comment: http://stackoverflow.com/comment/84948382
score: 1
has comment: http://stackoverflow.com/comment/84948308
type: Answer
has comment: http://stackoverflow.com/comment/84948235
answers question: http://stackoverflow.com/q/48971361
upvote count: 1
has body: You can use this to remove the single quote from the output: print('[', ', '.join(doclist), ']', sep='') Output: [doc1, doc2, doc3, doc4, doc5]
downvote count: 0

http://stackoverflow.com/comment/85075786
score: 0
type: AnswerComment
type: Comment
has text: OK, unfortunately I can't replicate your error. I can't see the types of your dataframe objects. The code above with the input data as I've created seems to work.
comment on: http://stackoverflow.com/a/49035073

http://stackoverflow.com/q/49082933
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49083492
tagged with: xpath
has body: I am trying to scrape all the links on https://www.etsy.com/market/happiness_bracelet and then the product descriptions from within each link extracted. I am using a chrome extension called Scraper to input the xpath, obtained from right-clicking the element in Chrome Dev Tools. But not getting the desired result. Problem: Can't find proper xpath for the links. What would be the proper setup to get the xpath of the links on that webpage and extract the product descriptions from within them? Is there's a way to do it just using Chrome Dev Tools and the proper Xpath, or would I need Python/bs4/selenium for this task? Thanks for your help.
tagged with: selenium
tagged with: web-scraping
type: Question
tagged with: google-chrome-devtools
score: 0
has title: Using Xpath to scrape links and descriptions from this Etsy product listings page
answer count: 1

http://stackoverflow.com/comment/84938916
has text: Suggest you try with 64-bit Python 3.5 or higher. Seems ibm_db.c barfs when PyUnicode_FromObject() returns null or Py_None.
score: 0
comment on: http://stackoverflow.com/q/48966135
type: QuestionComment
type: Comment

doc2vec
tags question: http://stackoverflow.com/q/48994062
tag name: doc2vec
type: Tag

http://stackoverflow.com/q/48976562
possible better answer: http://stackoverflow.com/a/48977185
score: -1
type: Question
upvote count: 0
has title: How do i extract text from double quotes and add it to string ? python 3.x
favorite count: 0
answer count: 3
has body: import re response_text = '{"captchaData":"[binary]","captchaMime":"image/jpeg","captchaToken":"ALXfmJpxoaxq6LYBXm-kJzIl0Yd5mHG1XbttsBX-EKxMYtYNIc6uTv89fmRxeWZGEgpi2L9sjXYlkm6Vplav_wy2KjdB5J4j3i5fB6CEuPOMXIjEql6mPBJ8-YJTCpOzzk8kOcW5nuBbuLOdMVyVxquLbWjqLZzHeN0iT4Jm4SIZ9mQNfapNGkE","status":"CAPTCHA"}' love = '"captchaData":"mydata"' session_token_temp = re.search(r'(\"captchaData\":\")(\w*)', response_text).group() session_token = str(session_token_temp) i want to extract value of captchaData and captchaToken and add the data to string like this extracted_data = (value_of_captchaData) extracted_data2 = (value_of_captchaToken)
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48976581
tagged with: python-requests
has answer: http://stackoverflow.com/a/48977185
downvote count: 1
has comment: http://stackoverflow.com/comment/84958382
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48976581
has answer: http://stackoverflow.com/a/48976636

http://stackoverflow.com/q/49038464
possible better answer: http://stackoverflow.com/a/58807474
answer count: 4
favorite count: 0
downvote count: 0
has title: OpenCV - Calibrate fisheye lens error (Ill-conditioned matrix)
has answer: http://stackoverflow.com/a/65730192
tagged with: python
has body: I am trying to calibrate a fisheye lens following these instructions https://medium.com/@kennethjiang/calibrate-fisheye-lens-using-opencv-333b05afa0b0 where you can find the full code I'm using for the calibration part. I arrive at this point where: N_OK = len(objpoints) K = np.zeros((3, 3)) D = np.zeros((4, 1)) rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)] tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)] rms, _, _, _, _ = \ cv2.fisheye.calibrate( objpoints, imgpoints, gray.shape[::-1], K, D, rvecs, tvecs, calibration_flags, (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-3) ) print("Found " + str(N_OK) + " valid images for calibration") print("DIM=" + str(_img_shape[::-1])) print("K=np.array(" + str(K.tolist()) + ")") print("D=np.array(" + str(D.tolist()) + ")") I get this error: Traceback (most recent call last) &lt;ipython-input-10-deaca9981fe4&gt; in &lt;module&gt;() 13 tvecs, 14 calibration_flags, ---&gt; 15 (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-3) 16 ) 17 print("Found " + str(N_OK) + " valid images for calibration") error: C:\ci\opencv_1512688052760\work\modules\calib3d\src\fisheye.cpp:1414: error: (-3) CALIB_CHECK_COND - Ill-conditioned matrix for input array 0 in function cv::internal::CalibrateExtrinsics I don't understand what's going on and I could only find so little information around the internet, does anyone have experienced something similar and know how to solve this? Thanks These are the images of the checkerboard I'm using: https://i.sstatic.net/goHIg.jpg https://i.sstatic.net/kja3O.jpg https://i.sstatic.net/XbIzh.jpg https://i.sstatic.net/uQ9Gr.jpg https://i.sstatic.net/N8aLJ.jpg https://i.sstatic.net/JMmmZ.jpg https://i.sstatic.net/QJ8wn.jpg https://i.sstatic.net/NmiFQ.jpg https://i.sstatic.net/sQHdd.jpg https://i.sstatic.net/DNBuD.jpg https://i.sstatic.net/vFtOo.jpg https://i.sstatic.net/lhkF5.jpg
score: 14
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58807474
has answer: http://stackoverflow.com/a/59400942
linked to: http://stackoverflow.com/q/34316306
type: Question
accepted answer: http://stackoverflow.com/a/49449108
upvote count: 14
has answer: http://stackoverflow.com/a/49449108

http://stackoverflow.com/q/48996679
accepted answer: http://stackoverflow.com/a/48996721
downvote count: 2
score: -2
has title: How to reverse each character of a string in a strings list and concatenate them
tagged with: string
has answer: http://stackoverflow.com/a/48996721
has comment: http://stackoverflow.com/comment/84998779
linked to: http://stackoverflow.com/q/48952467
tagged with: reverse
answer count: 1
has body: For instance, myList = (['string21', 'string43', 'string65'])... now I want my result to be this (without [ ] and , ): '12gnirts 34gnirts 56gnirts' I've found few examples on how to reverse strings in general but not specific to this problem ... I'm bit confused on how to do a reverse of strings that are in a list. Below is my code: reverseEachCharacter = [x[::-1] for x in myList] print "Result: ", reverseEachCharacter # prints this:['1gnirts', '2gnirts', '3gnirts']
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84998778
upvote count: 0
linked to: http://stackoverflow.com/q/12453580
duplicate of: http://stackoverflow.com/q/12453580
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84999237
tagged with: substring
type: Question

http://stackoverflow.com/q/49015994
has comment: http://stackoverflow.com/comment/85037320
linked to: http://stackoverflow.com/q/2180415
favorite count: 0
has comment: http://stackoverflow.com/comment/85039853
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85077910
score: 8
has comment: http://stackoverflow.com/comment/85037434
has comment: http://stackoverflow.com/comment/85036890
downvote count: 0
upvote count: 8
type: Question
duplicate of: http://stackoverflow.com/q/2180415
tagged with: django-models
has comment: http://stackoverflow.com/comment/85037013
has comment: http://stackoverflow.com/comment/85036930
has body: I have a non django project for which i would like to use the django models for data access layer. Added the models lib in requirements.txt django-model-utils==3.1.1 And code set it up like below: from django.conf import settings from django.db import models settings.configure( DATABASE_ENGINE='django.db.backends.mysql', DATABASE_NAME='***', DATABASE_USER='***', DATABASE_PASSWORD='***', DATABASE_HOST='***', DATABASE_PORT='***') class Bus(models.Model): class Meta: db_table = 'my_custom_bus' bus_name = models.CharField(max_length=20) bus_description = models.CharField(max_length=100) But when i ran the above code, i am getting the following error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. In order to fix the above error, i ran: import django django.setup() Now when i try, i get: Bus doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS Am i missing some setting here or is there any light weight model only lib in python?
answer count: 1
has answer: http://stackoverflow.com/a/53863818
has title: Django model outside of django

http://stackoverflow.com/q/49107640
has answer: http://stackoverflow.com/a/49108278
answer count: 5
has title: slicing dictionary with values
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49107957
tagged with: ordereddictionary
score: 1
has comment: http://stackoverflow.com/comment/85220261
accepted answer: http://stackoverflow.com/a/49108278
type: Question
has answer: http://stackoverflow.com/a/49108111
downvote count: 0
has body: I have a dictionary like: d = {1: 'a', 2:'b', 3:'c', 4:'c', 5:'c', 6:'c'} I want to slice this dictionary such that if the values in the end are same, it should return only the first value encountered. so the return is: d = {1: 'a', 2:'b', 3:'c'} I'm using collections.defaultdict(OrderedDict) to maintain sorting by the keys. Currently, I'm using a loop. Is there a pythonic way of doing this? UPDATE the dictionary values can also be dictionaries: d = {1: {'a': 'a1', 'b': 'b1'}, 2:{'a': 'a1', 'b': 'b2'}, 3:{'a': 'a1', 'b': 'c1'}, 4:{'a': 'a1', 'b': 'c1'}, 5:{'a': 'a1', 'b': 'c1'}, 6:{'a': 'a1', 'b': 'c1'}} output: d = {1: {'a': 'a1', 'b': 'b1'}, 2:{'a': 'a1', 'b': 'b2'}, 3:{'a': 'a1', 'b': 'c1'}}
has answer: http://stackoverflow.com/a/49107871
possible better answer: http://stackoverflow.com/a/49107845
has answer: http://stackoverflow.com/a/49107845
has comment: http://stackoverflow.com/comment/85220847
tagged with: python
tagged with: dictionary
favorite count: 0

http://stackoverflow.com/q/48999970
tagged with: eigenvalue
favorite count: 0
has comment: http://stackoverflow.com/comment/85006011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85085496
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/85022246
has answer: http://stackoverflow.com/a/49022451
has comment: http://stackoverflow.com/comment/85006265
downvote count: 0
has comment: http://stackoverflow.com/comment/85086205
tagged with: scipy
has comment: http://stackoverflow.com/comment/85039304
has comment: http://stackoverflow.com/comment/85078115
type: Question
tagged with: numpy
tagged with: linear-algebra
has body: I construct a 100*100 matrix k and want to use numpy.linalg.eig to diagonalize it. k=np.zeros((100,100)) np.fill_diagonal(k,-2) np.fill_diagonal(k[1:,:-1],1.5) np.fill_diagonal(k[:-1,1:],0.5) when I try smaller matrix, such as w,v=np.linalg.eig(k[:10,:10]) the eigenvalue w and eigenvector v are real. But when I try bigger matrix or the whole complete matrix w,v=np.linalg.eig(k) w and v turn out to be complex numbers, and the imaginary part is non-negligible. I also try scipy.linalg.eig, it has similar issue. I want to take the natural logarithm of the eigenvalues and eigenvectors. There's no physical meaning of complex numbers in my model. How can I only have independent real number eigenvalues and eigenvectors? If not, how to change the complex eigenvalues and eigenvectors to real ones by python?
has answer: http://stackoverflow.com/a/49041867
upvote count: 2
has title: How to get real eigenvalues and eigenvectors for a tridiagonal Toeplitz matrix?
answer count: 2
has comment: http://stackoverflow.com/comment/85005459

http://stackoverflow.com/q/48980691
has comment: http://stackoverflow.com/comment/84966512
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48982169
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/84966624
type: AnsweredQuestion
has title: Simplify Python Turtle plotting of similar functions
type: Question
has body: Is there a way to simplify this function, in terms of less if statements and typing the same code over and over? This function creates sine graphs based on the number the user requests. There is a lot of repeating code. I tried to use lists to store the objects, but get an error when trying to access them. How can I fix this? def createWaves(amp, count): even_num = [2, 4, 6, 8, 10, 12] alpha = createTurtle("turtle", "darkcyan", 2) alpha.ht() beta = createTurtle("turtle", "purple", 2) beta.ht() gamma = createTurtle("turtle", "orange", 2) gamma.ht() delta = createTurtle("turtle", "magenta", 2) delta.ht() epsilon = createTurtle("turtle", "deepskyblue", 2) epsilon.ht() zeta = createTurtle("turtle", "green", 2) zeta.ht() omega = createTurtle("turtle", "black", 3) omega.ht() if count == 0: alpha.st() for x in range(361): y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0]))) alpha.goto(x, y_alpha) elif count == 1: alpha.st() beta.st() omega.st() for x in range(361): y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0]))) y_beta = (amp/even_num[1]) *(math.sin(math.radians(x*even_num[1]))) y_omega = y_alpha + y_beta alpha.goto(x, y_alpha) beta.goto(x, y_beta) omega.goto(x, y_omega) elif count == 2: alpha.st() beta.st() gamma.st() omega.st() for x in range(361): y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0]))) y_beta = (amp/even_num[1]) *(math.sin(math.radians(x*even_num[1]))) y_gamma = (amp/even_num[2]) *(math.sin(math.radians(x*even_num[2]))) y_omega = y_alpha + y_beta + y_gamma alpha.goto(x, y_alpha) beta.goto(x, y_beta) gamma.goto(x, y_gamma) omega.goto(x, y_omega)
has answer: http://stackoverflow.com/a/48982169
answer count: 1
has comment: http://stackoverflow.com/comment/84966661
score: 0
has comment: http://stackoverflow.com/comment/84966574
has comment: http://stackoverflow.com/comment/84966622
tagged with: python

http://stackoverflow.com/q/49023711
has comment: http://stackoverflow.com/comment/85052279
favorite count: 0
has comment: http://stackoverflow.com/comment/85052259
score: 0
accepted answer: http://stackoverflow.com/a/49025821
tagged with: python
tagged with: python-3.x
tagged with: list
has comment: http://stackoverflow.com/comment/85052294
has title: How to reorder a binary list but keep 1's roughly evenly spread apart from each other in the list?
upvote count: 1
has comment: http://stackoverflow.com/comment/85052271
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85052335
possible better answer: http://stackoverflow.com/a/49024451
has body: I basically want to reorder(don't think this is a shuffling task) a list of 100 binary numbers. The following properties should hold after the reorder: the fixed frequency of 1's should remain, which is 10 and the 1's should be roughly spread apart from each other as shown below, so every 9th, 10th, or 11th digit is a 1. I want this reordering to be random. The trivial approach I had in mind is to track the index of the first 1 in the input list and generate a new start index. Any ideas on other solutions? x = [1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
has answer: http://stackoverflow.com/a/49025821
has answer: http://stackoverflow.com/a/49024451
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/q/48973117
tagged with: scrapy
linked to: http://stackoverflow.com/q/48897704
type: Question
upvote count: 1
answer count: 1
has title: Django auto create slug and integrity error
tagged with: scrapy-pipeline
favorite count: 0
tagged with: postgresql
downvote count: 2
has answer: http://stackoverflow.com/a/49011304
has body: I'm not understanding this. I have seen the posts here Django - Slugs - Key (slug)=() is duplicated and here Django: Key (slug)=(*) already exists. Here is my error message: django.db.utils.IntegrityError: duplicate key value violates unique constraint "caseAT_case_slug_key" DETAIL: Key (slug)=() already exists. In the docs it says: https://docs.djangoproject.com/en/1.8/howto/writing-migrations/#migrations-that-add-unique-fields Applying a “plain” migration that adds a unique non-nullable field to a table with existing rows will raise an error because the value used to populate existing rows is generated only once, thus breaking the unique constraint. But this is NOT a migration. This is a djangoitem pipeline. The model has the slug being created automatically from the title. Therefore, I did not put slug in the pipeline. If it is expecting to create slug, and balks because it is already there, why isn't it also expecting to create all the other keys? If it isn't in the pipeline, why is it trying to create it now? Because it expects to create it? So I should remove the auto create on that field? Then how is it going to get created? I did want my slugs to be unique. It seems circular and crazy to me, but what difference does that make? None. Your assistance appreciated.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17257031
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84951224
score: -1
linked to: http://stackoverflow.com/q/31162620

http://stackoverflow.com/q/49089450
has title: Membership test for iterators
has answer: http://stackoverflow.com/a/49089536
tagged with: python
has answer: http://stackoverflow.com/a/49089589
has body: Can somebody explain me the behaviour of membership test in the last 3 lines of my code bellow, why is it False? Why is the membership test different for iterators and iterables? c = [1,2,3,4,5,6,7,8,9,10,11,12] print(3 in c) # True print(3 in c) # True d = iter(c) print(2 in d) # True print(4 in d) # True print(4 in d) # False ??? print(6 in d) # False ??? print(10 in d) # False ???
upvote count: 3
type: UnansweredQuestion
type: Question
score: 3
has answer: http://stackoverflow.com/a/76285793
has comment: http://stackoverflow.com/comment/85184509
tagged with: iterator
answer count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48969346
tagged with: python
tagged with: dictionary
score: 2
has answer: http://stackoverflow.com/a/48969364
downvote count: 0
linked to: http://stackoverflow.com/q/6777485
tagged with: loops
has answer: http://stackoverflow.com/a/48969485
type: Question
has answer: http://stackoverflow.com/a/48969366
upvote count: 2
answer count: 3
linked to: http://stackoverflow.com/q/1637807
has title: Delete dictionary keys that are out of bounds (python)
favorite count: 0
has body: If you have a dictionary of integers: d = { 1:[0], 2:[1], 3:[0,1,2,3,4], 4:[0], 5:[1], 6:[0,1,2,3,4], 11:[0], 22:[1], 33:[0,1,2,3,4], 44:[0], 55:[1], 66:[0,1,2,3,4] } You want to: Validate that the keys are between 0 and 25. Delete any keys that are outside of the range as they are not valid and will ruin the data set. Dictionary keys are not naturally sorted. Given, how would validate that your keys are in the required range? My try: for x,y in d.items(): if x&lt;0 or x&gt;25: del d[x] When ran I get the error: RuntimeError: dictionary changed size during iteration How would I compensate for this?
type: UnansweredQuestion

http://stackoverflow.com/q/49006699
score: 15
tagged with: pandas
upvote count: 15
favorite count: 0
downvote count: 0
tagged with: python
type: AnsweredQuestion
has body: I want to plot two pandas dataframes side by side, each plot should be in subplot form. I am using following lines: import numpy as np import pandas as pd import matplotlib.pyplot as plt # create dummy pandas dataframes pd1 = pd.DataFrame({'a':np.random.random(22),'b':np.random.random(22),'c':np.random.random(22)}) pd2 = pd.DataFrame({'J':np.random.random(22),'K':np.random.random(22),'P':np.random.random(22)}) #create subplot figure with having two side by side plots fig, axes = plt.subplots(nrows=1,ncols=2,figsize=(12,6)) # plot first pandas frame in subplot style pd1.plot(ax = axes[0],subplots=True) # plot second pandas frame in subplot style pd2.plot(ax = axes[1],subplots=True) Without subplot option, side by side plots are drawn but I want in subplot style. Is there any other option to get it done? Precisely, I want to plot pandas in the following manner:
accepted answer: http://stackoverflow.com/a/49007720
tagged with: matplotlib
linked to: http://stackoverflow.com/q/34933905
has comment: http://stackoverflow.com/comment/85018871
type: Question
has answer: http://stackoverflow.com/a/49007720
has title: Plot two pandas data frames side by side, each in subplot style
answer count: 1
has comment: http://stackoverflow.com/comment/85017992

http://stackoverflow.com/comment/85242181
comment on: http://stackoverflow.com/a/49118298
type: AnswerComment
has text: I can't see your folder directory but I'm seeing you call your file randomNumbers.txt when your code said randomNumber.txt (note without 's') could be the problem if its the same in your directory.
score: 0
type: Comment

http://stackoverflow.com/a/49104233
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85215482
answers question: http://stackoverflow.com/q/49088670
accepted answer of: http://stackoverflow.com/q/49088670
type: AcceptedAnswer
downvote count: 0
has body: Simply changing the second last line of your main function solves the problem: img_pil = transforms.ToPILImage()(img.squeeze()) img.squeeze() makes the tensor shape (1, 4, 300, 300) to (4, 300, 300).

http://stackoverflow.com/q/49071831
downvote count: 0
tagged with: python-3.6
linked to: http://stackoverflow.com/q/47155569
has body: I am trying to display some points using matplotlib, Although I can display them using print command but matplotlib gives error. The command that works is also there(commented). import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline data = np.array([[-1,-1,'C1'],[-2,-1,'C1'],[-3,-2,'C1'],[1,1,'C2'],[2,1,'C2'],[3,2,'C2']]) query=[-2.5,-1.5] df=pd.DataFrame(data) df.columns =['x','y','Cat'] df for i in range(6): if(df.ix[i]['Cat'] == 'C1'): plt.scatter(df.iloc[i]['x'], df.iloc[i]['y'], s=150, c='r') #error line #working linke below #print(df.iloc[i]['x'],df.iloc[i]['y']) else: plt.scatter(df.iloc[i]['x'], df.iloc[i]['y'], s=150, c='b') #working line below #print(df.iloc[i]['x'],df.iloc[i]['y']) Please help. Thanks in advance Thanks @Haleemur Ali for your help I am able to run it now but still not fully functional. Not all points are showing not sure why? import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline data = np.array([[-1,-1,'r'],[-2,-1,'r'],[-3,-2,'r'],[1,1,'b'],[2,1,'b'],[3,2,'b'],[-2.5,-1.5,'y']]) query=[-2.5,-1.5] df=pd.DataFrame(data) df.columns =['x','y','Cat'] print(df) plt.scatter(df.x, df.y, s=150, c=df.Cat) Graph generated
has answer: http://stackoverflow.com/a/49074653
has comment: http://stackoverflow.com/comment/85149386
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49072505
has title: Matplotlib key error with dataframe
has comment: http://stackoverflow.com/comment/85154355
upvote count: 1
tagged with: python
score: 1
tagged with: matplotlib
type: Question
answer count: 2

http://stackoverflow.com/comment/84966724
has text: Sorry, I edited the wrong place, your answer is definite right. Can you see my question again, I just altered some of the code. Thank you very much!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48980239
type: Comment

http://stackoverflow.com/comment/85142938
type: QuestionComment
has text: Not a time series, but the order is important. The x represents a sensor value for a rotating scan. So value 315 is actually left of value 0. Hopefully that makes sense
comment on: http://stackoverflow.com/q/49068022
score: 0
type: Comment

http://stackoverflow.com/q/48973087
has comment: http://stackoverflow.com/comment/84953871
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84953523
tagged with: python
has comment: http://stackoverflow.com/comment/84953629
tagged with: keep-alive
answer count: 0
tagged with: httplib
has body: I am using the httplib library (python 2.7), and as you are probably aware, it needs to make a TCP handshake every time a new connection is made, and this can take a few seconds, which I have been trying to negate for some considerable time . I do use a Keep-Alive header with my requests, but the REST server I am consuming has a very short timeout (&lt;30 seconds), so I need to either refresh the current connection, or make a new one, hence a new wait (out of the question in this case). In the past, as a way around this I have used (admittedly bizzare), something like the following: #script 1 import zmq #Set PUSH socket context = zmq.Context() ventilator_send = context.socket(zmq.PUSH) ventilator_send.bind("tcp://127.0.0.1:5557") def SOCKET_SENDS(INFO): try: ventilator_send.send(INFO,zmq.NOBLOCK) except Exception, e: print "Socket failure - check client", e #send content msg = json.dumps({'MKT':{'A':123,'B':456}}) SOCKET_SENDS(msg) And then I send the requests to the following: #script 2 context = zmq.Context() work_receiver = context.socket(zmq.PULL) work_receiver.connect("tcp://127.0.0.1:5557") poller = zmq.Poller() poller.register(work_receiver, zmq.POLLIN) #make initial handshake conn = httplib.HTTPSConnection('site') while True: socks = dict(poller.poll(25000)) if socks: if socks.get(work_receiver) == zmq.POLLIN: RESP = json.loads(work_receiver.recv(zmq.NOBLOCK)) if RESP.has_key('MKT'): conn.request(GET, POST, PUT..., params, {'Connection' :'Keep-Alive'}) write_pickle(conn.getresponse()) if RESP.has_key('LMT'): conn.request(GET, POST, PUT..., params, {'Connection' :'Keep-Alive'}) write_pickle(conn.getresponse()) if RESP.has_key('TPP'): conn.request(GET, POST, PUT..., params, {'Connection' :'Keep-Alive'}) write_pickle(conn.getresponse()) ... else: conn.request(GET, POST, PUT..., params, {'Connection' :'Keep-Alive'}) consume_scrap_response = conn.getresponse()) So, all this to keep a HTTP connection persistent, this is overkill right? (and to say it's prone to er…
type: Question
has comment: http://stackoverflow.com/comment/84953943
has comment: http://stackoverflow.com/comment/84953787
tagged with: python-2.7
score: 0
has title: Make a httplib connection persistent, everwhere

http://stackoverflow.com/q/49017958
downvote count: 0
linked to: http://stackoverflow.com/q/44489126
score: 1
has comment: http://stackoverflow.com/comment/85043129
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54973046
tagged with: numba
has comment: http://stackoverflow.com/comment/85045288
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/85042680
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85042279
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85056587
has body: I am trying to define an @njit function which at several points needs to calculate the minimum. Doing this as follows works: min(arg1, arg2,...) However when I go to calculate the minimum of an iterable I seem to have a problem no matter how that iterable is defined. I've reproduced this with a small function below: itrbl = [5.0, 0.4, 4.5, 3.5, 6.4] @njit def funct(itrbl): return min(itrbl) funct(itrbl) and get the following error: TypingError: Invalid usage of Function(&lt;built-in function min&gt;) with parameters (reflected list(float64)) * parameterized It doesn't seem to like when I structure itrbl as an array either... How do I need to structure itrbl to make this simple function work?
has title: @njit issues with iterable definition for min function
tagged with: min

http://stackoverflow.com/q/49046956
upvote count: 1
has answer: http://stackoverflow.com/a/49073511
tagged with: tensorflow
type: Question
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49055288
downvote count: 0
score: 1
favorite count: 0
has title: Tensorflow + google ml-engne local predict: How CSV quotes should be processed?
type: UnansweredQuestion
tagged with: google-cloud-ml
tagged with: python
has body: I have trained a CNN model for predicting 0/1 values and using google ml-engine local predict for testing it. My test file contains 2 lines: some text "some text" and I know that this should give me 1 and 1 as predicted result. But output is 1 and 0. So double quotes matter for some reason. While training pandas.read_csv is used for vocabulary creation. pd.read_csv(filename, header=None, sep=',', names=['source', 'title'],encoding='utf-8', na_filter=False,engine='python') For prediction following command is used: gcloud ml-engine local predict --model-dir=.... --text-instances=... --format=json Am I missing some parameter while reading csv for training or is this google ml-engine's issue?

http://stackoverflow.com/a/49090608
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/49090579
upvote count: 3
answers question: http://stackoverflow.com/q/49090579
has body: The call signature of plot is plot(*args,*kwargs) Hence you need to call ax.plot(xval, yval, marker = 'o', ...) Also note that if X is your array you can directly plot ax.plot(X[:,0],X[:,1], ...)

http://stackoverflow.com/comment/85146155
type: Comment
type: QuestionComment
has text: i dont know i just added a print statment after that
comment on: http://stackoverflow.com/q/49066831
score: 0

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/49069071
tags question: http://stackoverflow.com/q/49038145
tags question: http://stackoverflow.com/q/49081097
tags question: http://stackoverflow.com/q/49070798
tags question: http://stackoverflow.com/q/49111696
tags question: http://stackoverflow.com/q/49000198
tags question: http://stackoverflow.com/q/49010538
tags question: http://stackoverflow.com/q/48973101
tags question: http://stackoverflow.com/q/49036563
tags question: http://stackoverflow.com/q/49087139
tags question: http://stackoverflow.com/q/48989601
tags question: http://stackoverflow.com/q/48982869
tags question: http://stackoverflow.com/q/49109920
tags question: http://stackoverflow.com/q/49032834
tags question: http://stackoverflow.com/q/49118954
tags question: http://stackoverflow.com/q/49084214
tags question: http://stackoverflow.com/q/48978272
tags question: http://stackoverflow.com/q/49093115
tags question: http://stackoverflow.com/q/49113278
tags question: http://stackoverflow.com/q/49017670
tags question: http://stackoverflow.com/q/49061821
tags question: http://stackoverflow.com/q/49051373
tags question: http://stackoverflow.com/q/49114995
tags question: http://stackoverflow.com/q/49041870
tags question: http://stackoverflow.com/q/49040720
tags question: http://stackoverflow.com/q/49051814
tags question: http://stackoverflow.com/q/49009995
type: Tag
tags question: http://stackoverflow.com/q/49027872
tags question: http://stackoverflow.com/q/49010415
tags question: http://stackoverflow.com/q/49100943
tags question: http://stackoverflow.com/q/49086903
tags question: http://stackoverflow.com/q/49050848
tags question: http://stackoverflow.com/q/49099565
tags question: http://stackoverflow.com/q/49118592
tags question: http://stackoverflow.com/q/49107520
tags question: http://stackoverflow.com/q/49044960
tags question: http://stackoverflow.com/q/49053777
tags question: http://stackoverflow.com/q/49017580
tags question: http://stackoverflow.com/q/49003637
tags question: http://stackoverflow.com/q/49019996
tags question: http://stackoverflow.com/q/49072681
tags question: http://stackoverflow.com/q/49084842
tag name: json
tags question: http://stackoverflow.com/q/49026104
tags question: http://stackoverflow.com/q/49073571
tags question: http://stackoverflow.com/q/49082081
tags question: http://stackoverflow.com/q/49091459
tags question: http://stackoverflow.com/q/49107594
tags question: http://stackoverflow.com/q/48998834
tags question: http://stackoverflow.com/q/49019202
tags question: http://stackoverflow.com/q/48969052
tags question: http://stackoverflow.com/q/49034083
tags question: http://stackoverflow.com/q/48993168
tags question: http://stackoverflow.com/q/49101541
tags question: http://stackoverflow.com/q/49088742
tags question: http://stackoverflow.com/q/49050306
tags question: http://stackoverflow.com/q/48969984
tags question: http://stackoverflow.com/q/49092307
tags question: http://stackoverflow.com/q/48969595
tags question: http://stackoverflow.com/q/49090957
tags question: http://stackoverflow.com/q/49082568
tags question: http://stackoverflow.com/q/49054909
tags question: http://stackoverflow.com/q/49114714
tags question: http://stackoverflow.com/q/49059551
tags question: http://stackoverflow.com/q/49003440
tags question: http://stackoverflow.com/q/49072183
tags question: http://stackoverflow.com/q/49077684
tags question: http://stackoverflow.com/q/49059757
tags question: http://stackoverflow.com/q/48987882
tags question: http://stackoverflow.com/q/49064275
tags question: http://stackoverflow.com/q/49054888
tags question: http://stackoverflow.com/q/49102975
tags question: http://stackoverflow.com/q/49061366
tags question: http://stackoverflow.com/q/48982404
tags question: http://stackoverflow.com/q/49095497
tags question: http://stackoverflow.com/q/49056941
tags question: http://stackoverflow.com/q/49063655
tags question: http://stackoverflow.com/q/48998624
tags question: http://stackoverflow.com/q/49100662

http://stackoverflow.com/q/48999542
favorite count: 0
tagged with: gini
tagged with: python
accepted answer: http://stackoverflow.com/a/49571213
upvote count: 13
has comment: http://stackoverflow.com/comment/85004535
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39512260
tagged with: weighted
linked to: http://stackoverflow.com/q/53748540
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48999797
has title: More efficient weighted Gini coefficient in Python
score: 13
has comment: http://stackoverflow.com/comment/94349968
possible better answer: http://stackoverflow.com/a/48999797
has answer: http://stackoverflow.com/a/49571213
answer count: 2
linked to: http://stackoverflow.com/q/48981516
downvote count: 0
has body: Per https://stackoverflow.com/a/48981834/1840471, this is an implementation of the weighted Gini coefficient in Python: import numpy as np def gini(x, weights=None): if weights is None: weights = np.ones_like(x) # Calculate mean absolute deviation in two steps, for weights. count = np.multiply.outer(weights, weights) mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum() rmad = mad / np.average(x, weights=weights) # Gini equals half the relative mean absolute deviation. return 0.5 * rmad This is clean and works well for medium-sized arrays, but as warned in its initial suggestion (https://stackoverflow.com/a/39513799/1840471) it's O(n2). On my computer that means it breaks after ~20k rows: n = 20000 # Works, 30000 fails. gini(np.random.rand(n), np.random.rand(n)) Can this be adjusted to work for larger datasets? Mine is ~150k rows.

http://stackoverflow.com/comment/85197008
type: QuestionComment
has text: can you post some examples? also what have you tried so far?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49096040

http://stackoverflow.com/a/49075317
answers question: http://stackoverflow.com/q/49061458
upvote count: 1
downvote count: 0
type: Answer
score: 1
has body: "Updating the position of a button after clicking? (Tkinter Python GUI)" Here's a minimal example that does just that: try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 except ImportError: import Tkinter as tk def on_button_press(widget): import random widget_size = (widget.winfo_width(), widget.winfo_height()) window_size = (widget.winfo_toplevel().winfo_width(), widget.winfo_toplevel().winfo_height()) random_x = random.randint(0, window_size[0] - widget_size[0]) random_y = random.randint(0, window_size[1] - widget_size[1]) widget.place(x=random_x, y=random_y) def main(): root = tk.Tk() button = tk.Button(root, text="Place Randomly!") button['command'] = lambda w=button: on_button_press(w) button.place(x=0, y=0) tk.mainloop() if __name__ == '__main__': main()

http://stackoverflow.com/comment/85389489
has text: Thank you , both of the suggestions helped :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49094057

http://stackoverflow.com/q/48964998
has comment: http://stackoverflow.com/comment/84935886
tagged with: python-3.x
has title: (Edit) ValueError: not enough values to unpack (expected 3, got 2), trying to add an if statement to it
tagged with: python
has comment: http://stackoverflow.com/comment/84936071
has comment: http://stackoverflow.com/comment/84936110
has comment: http://stackoverflow.com/comment/84935909
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84935962
has comment: http://stackoverflow.com/comment/84935953
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/84936332
score: 0
linked to: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/48965275
accepted answer: http://stackoverflow.com/a/48965275
has body: I understand the error but I'm trying to add an if statement to it. def repeat(): message = input("command: ").split(" ") if len(message) == 2: #if there is a first parameter cmd,param = message #add it to the message elif len(message) == 3: #if there is a first and second parameter cmd,param,param2 = message #add it to the message else: #if there is no first and second parameter cmd = message #add just the command to the message if cmd == "local": if len(message) == 2 or len(message) == 3: #if there is a first or second parameter print("error: no first or second parameter in command 'local'") #error repeat() else: #if there are no parameters print("test") #execute the command repeat() else: print("unrecognized command") repeat() repeat() Edit: When I add a second parameter to the command 'local' it returns the error on line 11, but when I do not add a first or second parameter it prints "unrecognized command" used on line 17.

http://stackoverflow.com/a/49078607
has body: The more I look at this problem the more I believe you want an object-oriented solution. Here is one implementation: import random, string from datetime import datetime class Flight(object): def __init__(self, dest, origin, not_available_seats, available_seats, uid, date): self.dest = dest self.origin = origin self.not_available_seats = not_available_seats self.available_seats = available_seats self.uid = uid self.date = date self.price = (51 - self.available_seats) * 10 def set_available_seats(self, available_seats): self.available_seats = available_seats self.price = (51 - self.available_seats) * 10 return None You can create a class instance as easily as adding a dictionary item: F1 = Flight("".join(random.choice(string.ascii_uppercase) for n in range(3)), "".join(random.choice(string.ascii_uppercase) for n in range(3)), [], 50, 123456789, datetime.now()) Updating available seats causes the price to update: print(F1.price) # 10 F1.set_available_seats(30) print(F1.price) # 210
upvote count: 1
has comment: http://stackoverflow.com/comment/85192041
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49077802
answers question: http://stackoverflow.com/q/49077802

http://stackoverflow.com/comment/85079752
type: QuestionComment
has text: Note, your `promotion` method doesn't do anything. It merely increments a local variable and returns `None`. Likely, `employee_lvl` should be an instance variable
comment on: http://stackoverflow.com/q/49037304
type: Comment
score: 0

http://stackoverflow.com/q/49095096
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 0
downvote count: 2
tagged with: machine-learning
tagged with: python
has body: I have 4 sets of features X1,X2,X3&amp;X4 and I have 8-10 possible outcomes i.e Y1-Y8. How would i train the model to fit this data? Should I for a particular output keep Yn as 1 and keep other Ys as 0?. If i do this while serving the model how do I ensure that I receive only discreet output values i.e 0 OR 1. How do I implement this in skilearn random forest classifier?
has title: How to train a random forest classification model for classifying multiclass data using scikit?
type: Question
tagged with: random-forest
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85211255
has comment: http://stackoverflow.com/comment/85211091
has comment: http://stackoverflow.com/comment/85213357

http://stackoverflow.com/comment/85215359
has text: @n33rma is that a 3.7 method or is it available in older ones too?
comment on: http://stackoverflow.com/a/49104818
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48963665
has answer: http://stackoverflow.com/a/53186646
tagged with: python
downvote count: 0
has title: How to use PyCharm with Google compute engine
score: 24
type: Question
has answer: http://stackoverflow.com/a/53049936
answer count: 3
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/68564677
upvote count: 24
favorite count: 0
has body: I have a compute engine instance running on Google cloud platform. I would like to use the Python interpreter of the compute engine as a remote interpreter with Pycharm. This means that I would be using Pycharm on my local machine and running computations remotely. Any clue on how to achieve this?
tagged with: pycharm
has comment: http://stackoverflow.com/comment/85020525
type: UnansweredQuestion

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/49117383
type: Tag

http://stackoverflow.com/q/49067260
downvote count: 4
upvote count: 0
has body: As a programmer it's important to know that what are the in-built types in the programming language which we want to learn.So as a beginner in python programming language I'm very much interested to know what are the python's inbuilt modules and libraries either it is python2 or python3.So I'm requesting anybody will give me a possible way.
answer count: 1
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/85139804
tagged with: windows
has title: How to see the all in-built python modules and libraries?
favorite count: 0
type: UnansweredQuestion
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/85139499
has answer: http://stackoverflow.com/a/49475509
type: Question

http://stackoverflow.com/a/49082052
has comment: http://stackoverflow.com/comment/85171795
answers question: http://stackoverflow.com/q/49081942
type: Answer
accepted answer of: http://stackoverflow.com/q/49081942
has comment: http://stackoverflow.com/comment/85171926
has comment: http://stackoverflow.com/comment/85172058
has body: In fact this is the default behavior of the underlying stdio functions. When the output is to console, the stream will be automatically flushed when a newline is encountered, but not other characters. If the output is not a console, then even newline won't trigger a flush. If you want to make sure about flush, you can tell the print() explicitly: print("Rewinding.......",end = '',flush=True)
has comment: http://stackoverflow.com/comment/85171834
has comment: http://stackoverflow.com/comment/85171877
has comment: http://stackoverflow.com/comment/85172006
has comment: http://stackoverflow.com/comment/85171904
has comment: http://stackoverflow.com/comment/132139351
type: AcceptedAnswer
downvote count: 1
score: 8
upvote count: 9

http://stackoverflow.com/comment/85126729
score: 0
type: Comment
has text: Thanks for posting. When I run solution 1, I am getting an name error: 'first' is not defined at this line: result.append(min(g, key=first)).
comment on: http://stackoverflow.com/a/49060795
type: AnswerComment

http://stackoverflow.com/comment/84963198
has text: In `Y `you have one item per day sines 01.01.1991?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48978803

http://stackoverflow.com/comment/85158308
type: QuestionComment
comment on: http://stackoverflow.com/q/49063404
has text: What would you mean by that?
score: 0
type: Comment

http://stackoverflow.com/comment/85248274
type: QuestionComment
comment on: http://stackoverflow.com/q/49121365
has text: Possible duplicate of [What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python)
score: 0
type: Comment

http://stackoverflow.com/comment/85052018
type: Comment
comment on: http://stackoverflow.com/a/49021472
score: 0
has text: Put the code in a function with argument `a`, run the function on each of the 100 lines (which you can put in a list).
type: AnswerComment

http://stackoverflow.com/comment/85023185
comment on: http://stackoverflow.com/a/49004977
type: Comment
has text: So I tried this but I kinda don't know what to give in with day and so on, does it matter? apparently there aren't standard dates and from the beginning of my problem I don't know what date it is see her clock (the wrong one) can still be day before
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85065849
comment on: http://stackoverflow.com/q/49030691
has text: What are `VAR0`, `VAR1`, `VAR2`, etc.?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/49040735
has comment: http://stackoverflow.com/comment/85088183
has title: How can I get table values from a website with Python
has comment: http://stackoverflow.com/comment/85497933
has answer: http://stackoverflow.com/a/53998133
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85540321
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85526341
has comment: http://stackoverflow.com/comment/85474537
has comment: http://stackoverflow.com/comment/85095871
type: Question
tagged with: python
answer count: 1
has body: I am using a python script to get a certain text from a website (http://www.opensiteexplorer.org/) or (https://beswick.net/api-code/state-of-digital-example.php) or (https://smallseotools.com/domain-authority-checker/) I would like to get all result values like "Page Authority" and "Domains Authority" and filter them out. I am using python2.7 and BeautifulSoup to extract the data. I am using this code: def parse_url() url = "https://beswick.net/api-code/state-of-digital-example.php" domain = 'http://www.google.com' mozID=" " mozSEC=" " def parse_url(): r = requests.post(url, {'moz-member':mozID,'moz-secret': mozSEC, 'url_form': domain, 'Check Metrics': 'submit'}) soup = BeautifulSoup(r.content,"lxml") for table in soup.find_all('table'): print table.text parse_url() and def PageDomainAuthority(): url = "https://smallseotools.com/domain-authority-checker/" domain = 'www.google.com' r = requests.post(url, {'urls': domain, 'check': 'submit'}) soup = BeautifulSoup(r.content,"lxml") for p in soup.find_all("div",{"class":"col-sm-12 noP"}): print(p.text) PageDomainAuthority() here is the output(i can only get the headers) : Web Page DA PA Moz Rank IP Address IP Location how can I get the values as well?
score: 0
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/85557469

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/49034824
tags question: http://stackoverflow.com/q/49055680
tags question: http://stackoverflow.com/q/49100088
tags question: http://stackoverflow.com/q/49037039
type: Tag

http://stackoverflow.com/comment/100112961
comment on: http://stackoverflow.com/a/51177895
score: 1
has text: Event loops usually only expect their own events. You generally cannot mix events and event loops across libraries; the events shown here only work with the event loop shown. In specific, asyncio only uses None (i.e. a bare yield) as a signal for the event loop. Events directly interact with the event loop object to register wakeups.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85175923
type: Comment
type: QuestionComment
has text: but what is the difference @vaultah?
comment on: http://stackoverflow.com/q/49085243
score: 0

http://stackoverflow.com/comment/85029980
type: AnswerComment
comment on: http://stackoverflow.com/a/49011593
type: Comment
score: 2
has text: @yoram that is nonsense. There is no meaning defined for double forward slashes as you show. And the backslash string is still broken, and can't possibly work as path because the user is clearly on a mac, and the mac doesn't use backward slashes as path separaters. Look at `os.sep`. Just because a path is not working does not mean you get it to work by randomly doing things to it.

http://stackoverflow.com/comment/103535006
type: AnswerComment
has text: @HelloGoodbye, this page should explain it: https://stackoverflow.com/questions/44102738/why-cant-i-import-opencv3-even-though-the-package-is-installed
type: Comment
comment on: http://stackoverflow.com/a/52032374
score: 3

http://stackoverflow.com/comment/84944208
score: 0
type: Comment
has text: Thanks. I didn't know np.insert can insert multiple elements at a time.
comment on: http://stackoverflow.com/a/48969076
type: AnswerComment

http://stackoverflow.com/q/49102424
has body: I am doing something very simple but it seems that it does not work. I am importing a SAS table into pandas's dataframe. for the date column. I have NA which is actually using '9999dec31'd to represent it, which is 2936547 in numeric value. Python Pandas.read_sas() cant work with this value because it is too big. Any workaround? Thank you,
tagged with: sas
has comment: http://stackoverflow.com/comment/85211077
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python Pandas , Date '9999dec31'd
score: -1
has answer: http://stackoverflow.com/a/50023202
downvote count: 1
type: Question

http://stackoverflow.com/q/49013181
tagged with: python
tagged with: computer-vision
tagged with: object-detection
has body: I've training dataset which has co-ordinates for the bounding boxes of the objects to be detected in an image. Now, I want to train my CNNs, that given an image they output the corresponding co-ordinates of the bounding boxes for the object detected in the complete image. Training data format ID labels x1 y1 x2 y2 144503924.jpg Horse 38 12 234 142
has comment: http://stackoverflow.com/comment/85032505
tagged with: conv-neural-network
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85032394
has title: Object Detection with Bounding Boxes
has comment: http://stackoverflow.com/comment/85033855
has comment: http://stackoverflow.com/comment/85037481
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/85135890

http://stackoverflow.com/a/74774038
upvote count: 1
type: Answer
has body: Use this code: role = discord.utils.get(ROLE_ID) member.add_roles(role) Important: bot can't manage roles that above him
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49076798

http://stackoverflow.com/q/49023099
has answer: http://stackoverflow.com/a/49023284
has body: In my terminal, when I run: pip -V It gives: pip 9.0.1 from /home/abhor/anaconda3/lib/python3.6/site-packages (python 3.6) And when I run: pip3 -V It gives: pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.6) I want only 1 python3.6 to be there in my system, in case there are problems in the future. How to do this?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: How to resolve between two python 3 installations?
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: pip
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85051149
tagged with: python-3.6

http://stackoverflow.com/a/49054598
answers question: http://stackoverflow.com/q/49054538
has body: train_pct_index = int(0.8 * len(X)) X_train, X_test = X[:train_pct_index], X[train_pct_index:] y_train, y_test = y[:train_pct_index], y[train_pct_index:] It's one of those situations where it's just better not to involve sklearn helpers. Very straightforward, readable, and not dependent on knowing internal options of sklearn helpers, which code readers may not have experience with.
score: 5
accepted answer of: http://stackoverflow.com/q/49054538
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer

http://stackoverflow.com/q/49061864
has title: Check if numpy array rows are in another 2d array
has comment: http://stackoverflow.com/comment/85129441
type: UnansweredQuestion
tagged with: python
has body: How can I find those row indices of numpy array a that are not already in ref? For instance for this example: ref = np.asarray([[1.1, 2.2, 3.3], [4, 5, 6]]) a = np.asarray([[0, 1, 2], [1.1, 2.2, 3.3], [4, 5, 5]]) A result of [0, 2] would be correct, because these rows in a are not in ref. A possible solution would be to iterate over each row in a and check if it's in ref, but I was hoping there's a more efficient and elegant (1-liner?) way. Note: This answer doesn't work because it is assuming integer elements of the array (in my case I use floating point numbers).
linked to: http://stackoverflow.com/q/40055835
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/40055835
score: 0
has comment: http://stackoverflow.com/comment/85131349
has comment: http://stackoverflow.com/comment/85131078
answer count: 0

http://stackoverflow.com/comment/85097815
comment on: http://stackoverflow.com/q/49046397
has text: You could use a dictionary comprehension to grab keys and values by index.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49027131
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85059279
tagged with: python
has answer: http://stackoverflow.com/a/49030853
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85058929
has comment: http://stackoverflow.com/comment/85060681
downvote count: 0
tagged with: inheritance
has body: Suppose I want to create my own version of an existing class. Let's pick the builtin float class. In this example, I'll create a float like class that do not raise an error when dividing by zero but instead returns the string 'inf' (Remember this is just an example. Avoiding division by zero error is not the main point of this question). class myfloat(float): def __truediv__(self, b): if b == 0: return 'inf' else: return myfloat(self.__float__() / b) It works also when the division is coupled with int or float. In[88]: a = myfloat(10) In[89]: a / 2 Out[89]: 5.0 In[90]: a / 0 Out[90]: 'inf' However, due to the inheritance from the float class, when I carry any other operation (i.e. method) the result will be a float. For example: In[92]: b = myfloat(20) In[93]: (a + b) / 0 ZeroDivisionError Traceback (most recent call last) &lt;ipython-input-6-f769cd843514&gt; in &lt;module&gt;() ----&gt; 1 (a + b) / 0 ZeroDivisionError: float division by zero The addition method, still unaltered from the one inherited from the parent float class, obviously returns a float. So my question: Is there a neat way to make all inherited methods in the child class to return a result which is in the child class, without the need to rewrite all methods? I'm thinking something like a decorator @myfloat being automatically applied to all (applicable) inherited methods to convert their result from the type float to the type myfloat.
tagged with: class
has title: Class inheritance - Can all inherited methods be casted to child class type?
linked to: http://stackoverflow.com/q/6307761
answer count: 1
has comment: http://stackoverflow.com/comment/85062816
has comment: http://stackoverflow.com/comment/85061148
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/49030196
has comment: http://stackoverflow.com/comment/85065612
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85064993
has comment: http://stackoverflow.com/comment/85064773
has comment: http://stackoverflow.com/comment/85065322
favorite count: 0
has comment: http://stackoverflow.com/comment/85065619
tagged with: serial-port
has comment: http://stackoverflow.com/comment/85068032
tagged with: python
has comment: http://stackoverflow.com/comment/85065288
has comment: http://stackoverflow.com/comment/85066431
score: 2
has comment: http://stackoverflow.com/comment/85066801
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85068128
type: Question
has title: Can't write multiple times to same port (pyserial)
has answer: http://stackoverflow.com/a/49030362
has comment: http://stackoverflow.com/comment/85067638
has comment: http://stackoverflow.com/comment/85065989
linked to: http://stackoverflow.com/q/16701401
has comment: http://stackoverflow.com/comment/85065017
has body: Solved: dsrdtr=True shouldn't have been used for software, only on the hardware being used Hi I'm trying to write telegrams to serial port and can send one successfully. If I send more than one nothing happens. The script has to be closed at which point the first telegram is successfully received. The manufacturer suggests a break of 50ms between telegrams, even with breaks >5s it still fails. s = serial.Serial( port='COM3', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, timeout=0, bytesize=serial.SEVENBITS, dsrdtr=True ) buttonUP=b'\x54\x30\x34\x0D' s.write(buttonUP) time.sleep(0.05) s.write(buttonUP) time.sleep(0.05) s.write(buttonUP) If instead I write s.write(buttonUP) s.close() s.open() s.write(buttonUP) This works but the delay caused by closing/opening is too long for our requirements. Does anyone have any ideas about what could be causing this issue? Thank you very much for your help
tagged with: pyserial

http://stackoverflow.com/comment/85105514
comment on: http://stackoverflow.com/q/49049467
type: QuestionComment
has text: I'm sorry that i can't help you any further, since I'm tired a* and would do exactly the same you have to do now...
score: 0
type: Comment

http://stackoverflow.com/comment/85056234
score: 1
comment on: http://stackoverflow.com/q/49025790
type: Comment
type: QuestionComment
has text: What is `a` and `b` here?

http://stackoverflow.com/comment/85493672
has text: Okay! Time for me to try once again... Looks like the second one will do... I will let you know as soon as I try... Thanks Peter!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49087479

http://stackoverflow.com/q/49036237
upvote count: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54581213
tagged with: python
has comment: http://stackoverflow.com/comment/85079111
downvote count: 1
type: Question
has body: I have a pandas dataframe containing the below data, and i would like to add a new column which, for each date, returns the most frequently occurring 'weather_type' over the previous 3 days. Where the result is a tie, i'd like the most recent 'weather_type' to be returned. d = {'date': ['17/02/2017', '18/02/2017', '19/02/2017', '20/02/2017', '21/02/2017', '22/02/2017'], 'precipmm': [1, 0, 3, 2, 7, 8], 'weather_type': ['rain', 'sun', 'rain', 'snow', 'snow', 'rain']} df = pd.DataFrame(data=d) df['date']=pd.to_datetime(df['date'], format='%d/%m/%Y') df['rollingsum_precipmm']=df['precipmm'].rolling(window=3).sum() I've already managed to create a new column containing the sum of the total 'precipmm' over the last 3 days using the below: df['rollingsum_precipmm']=df['precipmm'].rolling(window=3).sum() I suspect the answer revolves around this, but as yet i've been unable to find a solution. Any help much appreciated as always Colin
score: 7
has comment: http://stackoverflow.com/comment/85077509
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/85077904
has title: Python pandas most common value over rolling date window
has answer: http://stackoverflow.com/a/49036490
favorite count: 0
has comment: http://stackoverflow.com/comment/85077954

http://stackoverflow.com/q/49060383
has title: Key error when joining dfs in Pandas
has answer: http://stackoverflow.com/a/49061218
has comment: http://stackoverflow.com/comment/85125805
accepted answer: http://stackoverflow.com/a/49061218
tagged with: pandas
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85125964
has comment: http://stackoverflow.com/comment/85125827
type: Question
tagged with: python
upvote count: 3
answer count: 1
has body: I have a dataframe with these columns: df1: Index(['cnpj', '#CNAE', 'Estado', 'Capital_Social', '#CNAEpai', '#CNAEvo', '#CNAEbisavo', 'Porte'], dtype='object') I have another dataframe with these columns: df2: Index(['#CNAEpai', 'ROA_t12_Peers_CNAEpai', 'MgBruta_t12_Peers_CNAEpai', 'MgEBITDA_t12_Peers_CNAEpai', 'LiqCorrente_t12_Peers_CNAEpai', 'Crescimento_t12_Peers_CNAEpai', 'MgLucro_t12_Peers_CNAEpai', 'Custo/Receita_t12_Peers_CNAEpai', 'Passivo/EBITDA_t12_Peers_CNAEpai', 'ROE_t12_Peers_CNAEpai', 'RFinanceiro/Receita_t12_Peers_CNAEpai', 'cnpj_t12_Peers_CNAEpai', 'LiqGeral_t12_Peers_CNAEpai'], dtype='object') I'm trying to join them, using this line: df1=df1.join(df2,on=['#CNAEpai'],how='left',rsuffix='_bbb') But I'm getting this error: KeyError: '#CNAEpai' Since #CNAEpai is a column in both dfs that shouldn't be happening right? What's going on?

http://stackoverflow.com/comment/85031682
type: Comment
comment on: http://stackoverflow.com/a/49012571
has text: Thank you! This worked, but now I've got a separate problem.. I can't seem to write the scraped items to a csv. I will update my original post.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85155918
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48998839
has text: Nothing! But the instructor said no with this kind of solution! ;) Thank you!
score: 0

http://stackoverflow.com/a/49009026
score: 0
answers question: http://stackoverflow.com/q/49005158
has body: You can set the output file as /dev/stdout (you might need to specify the output format with -f) Then you redirect your output to your python script like so ffmpeg options /dev/stdout | python your_script.py Then you can read this question to see how you can read an image from a file object. Just replace StringIO with sys.stdin
type: Answer

http://stackoverflow.com/q/49085245
has answer: http://stackoverflow.com/a/49085592
has answer: http://stackoverflow.com/a/49085285
type: AnsweredQuestion
tagged with: dataframe
type: Question
has title: Python Pandas insert row data in one line
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49085285
favorite count: 0
tagged with: pandas
score: 3
tagged with: python
tagged with: python-3.x
upvote count: 3
has body: I have a list messages of messages, when each message in this list, is an object with a 5 items - name, message, action, date, location. I want to fill my data frame with this information. Currently, I'm doing it like the following: j = 1 df = pd.DataFrame(index=range(1, len(messages)+1), columns=['name','message','action','date', 'location']) for message in messages: df.ix[j]['name'] = message.name df.ix[j]['message'] = message.message df.ix[j]['action'] = message.action df.ix[j]['date'] = message.date df.ix[j]['location'] = message.location j += 1 I feel like indexing is not the best solution I can think of. Any other way to do this? perhaps without using df.ix[j] a few times.
possible better answer: http://stackoverflow.com/a/49085592

http://stackoverflow.com/a/48984697
has body: The problem when converting to Excel’s “base 26” is that for Excel, a number ZZ is actually 26 * 26**1 + 26 * 26**0 = 702 while normal base 26 number systems would make a 1 * 26**2 + 1 * 26**1 + 0 * 26**0 = 702 (BBA) out of that. So we cannot use the usual ways here to convert these numbers. Instead, we have to roll our own divmod_excel function: def divmod_excel(n): a, b = divmod(n, 26) if b == 0: return a - 1, b + 26 return a, b With that, we can create a to_excel function: import string def to_excel(num): chars = [] while num &gt; 0: num, d = divmod_excel(num) chars.append(string.ascii_uppercase[d - 1]) return ''.join(reversed(chars)) For the other direction, this is a bit simpler import string from functools import reduce def from_excel(chars): return reduce(lambda r, x: r * 26 + x + 1, map(string.ascii_uppercase.index, chars), 0) This set of functions does the right thing: &gt;&gt;&gt; to_excel(26) 'Z' &gt;&gt;&gt; to_excel(27) 'AA' &gt;&gt;&gt; to_excel(702) 'ZZ' &gt;&gt;&gt; to_excel(703) 'AAA' &gt;&gt;&gt; from_excel('Z') 26 &gt;&gt;&gt; from_excel('AA') 27 &gt;&gt;&gt; from_excel('ZZ') 702 &gt;&gt;&gt; from_excel('AAA') 703 And we can actually confirm that they work correctly opposite of each other by simply checking whether we can chain them to reproduce the original number: for i in range(100000): if from_excel(to_excel(i)) != i: print(i) # (prints nothing)
has comment: http://stackoverflow.com/comment/84974218
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48983939
type: Answer
answers question: http://stackoverflow.com/q/48983939
score: 29
has comment: http://stackoverflow.com/comment/84974230
upvote count: 29
has comment: http://stackoverflow.com/comment/84974273

http://stackoverflow.com/a/49077699
score: 2
downvote count: 0
has body: In this case, you could just use absolute imports instead of relative imports, but depending on the dependencies between your modules, it could result in some odd behavior, where objects and classes are technically being defined twice (once in your __main__ script, and once when another module imports your module) The proper way to do this would be to create a proper python package with a setup.py script and use the console_scripts entry point feature to expose a function as a command line script. Your project should be organized something like this. /subwayclock /subwayclock __init__.py subwayclock.py ... setup.py Your setup.py would look like this from setuptools import setup, find_packages setup(name='subwayclock', version='0.1', packages=find_packages(), zip_safe=False, entry_points = { 'console_scripts': ['subwayclock_script_name=subwayclock.subwayclock:rawFEED'], } ) Then you just install the package $ python setup.py install (you can also use develop mode so you can still work on it) $ python setup.py develop And you will be able to run that command line script $ subwayclock_script_name
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49077539

http://stackoverflow.com/q/49013158
accepted answer: http://stackoverflow.com/a/49024009
downvote count: 0
has title: Python exchangelib: check if item is a message or not
score: 2
type: AnsweredQuestion
tagged with: exchangelib
favorite count: 0
has answer: http://stackoverflow.com/a/49024009
type: Question
upvote count: 2
tagged with: python
answer count: 1
has body: I got an error when retrieve items using exchangelib. Is there any method to detect whether the item is an email, and if not, just ignore it? The following code raises AttributeError: 'MeetingRequest' object has no attribute 'flag') since meeting requests don't have a flag field. Or is there any method to view the type of the item? import re import sys from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \ EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \ Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \ HTMLBody, Build, Version from datetime import datetime, timedelta import pytz tz = EWSTimeZone.timezone('Asia/Hong_Kong') creds = Credentials( username='domain\userID', password='password') ) account = Account( primary_smtp_address='myemail@domain', credentials=creds, autodiscover=True, access_type=DELEGATE) class Flag(ExtendedProperty): property_tag = 0x1090 property_type = 'Integer' Message.register('flag', Flag) if(len(sys.argv) == 1): yesterday = tz.localize(EWSDateTime.now() - timedelta(days=3)) today = tz.localize(EWSDateTime.now()) fYear= yesterday.year fMonth= yesterday.month fDay= yesterday.day tYear = today.year tMonth = today.month tDay = today.day elif(len(sys.argv) == 3): fromDate = sys.argv[1] toDate = sys.argv[2] fYear = fromDate[:4] fMonth = fromDate[4:6] fDay = fromDate[-2:] tYear = toDate[:4] tMonth = toDate[4:6] tDay = toDate[-2:] for item in account.inbox.filter(datetime_received__range=( #tz.localize(EWSDateTime.now() - timedelta(days=1)), #tz.localize(EWSDateTime.now()) tz.localize(EWSDateTime(int(fYear), int(fMonth), int(fDay))), tz.localize(EWSDateTime(int(tYear), int(tMonth), int(tDay))) )): subA=item.subject snd=item.sender.email_address fg=str(item.flag) str(item.datetime_received.astimezone(pytz.timezone('Asia/Hong_Kong')).strftime("%a %b %d %H:%M:%S %Y")) rT = str(item.datetime_received.astimezone(pytz.timezone('Asia/Hong_Kong')).strftime("%Y-%m-%d %H:%M:%S")…

http://stackoverflow.com/comment/122817712
type: AnswerComment
has text: Unfortunately both links in this answer are now dead
type: Comment
comment on: http://stackoverflow.com/a/49042165
score: 1

http://stackoverflow.com/comment/130946243
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49065506
has text: This other answer https://stackoverflow.com/a/68585923/3107689 is not correct? Can't you give the service account domain wide access, then impersonate the user and access whatever resource he has including contacts, youtube, etc?
type: Comment

http://stackoverflow.com/comment/85114729
has text: You can simply remove newlines by replacing them with an empty string then convert it to int. `int(num.replace('\n', ''))`
score: 5
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49055073

http://stackoverflow.com/comment/85160037
score: 0
type: AnswerComment
has text: Perfect! Thank you!
type: Comment
comment on: http://stackoverflow.com/a/49077026

http://stackoverflow.com/a/48974189
has comment: http://stackoverflow.com/comment/84994067
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48974059
has comment: http://stackoverflow.com/comment/84975359
answers question: http://stackoverflow.com/q/48974059
type: Answer
has body: I am not sure what you wanted completely, however I think I know what you are trying to do. I added a list that holds the scores for the couples from 1-5 called couplescores. I then add the score of that couple to the corresponding place in the list, and at then at the end print it. judges = ["judge 1", "judge 2", "judge 3", "judge 4", "judge 5",] couples = [1, 2, 3, 4, 5] couplescores = [0,0,0,0,0] # Holds scores for the couples 1-5 x=0 j=0 done = False def judging(j, x, judges, couples,): print ("Scoring couple",couples[j],) for i in couples: print("Score couples" ,couples[j],judges[x],"out of 30 minimum 1") score = int(input(": ")) couplescores[j] = couplescores[j] + score # Adds the score to the list x=x+1 j=j+1 if j == 5: done = True else: x = 0 judging(j, x, judges, couples) judging(j, x, judges, couples) print(couplescores) # Prints scores

http://stackoverflow.com/comment/85197523
type: Comment
has text: Thanks for you response. The problem is when I want the tittle 'Annual Reports of Education, Health and Sport 9781329899971' I can´t find with the line containers = page_soup.findAll('div',{'class':'ng-binding'})
comment on: http://stackoverflow.com/a/49096255
type: AnswerComment
score: 0

http://stackoverflow.com/q/49084821
has title: Identifying specific number in a string using python
has comment: http://stackoverflow.com/comment/85174934
has answer: http://stackoverflow.com/a/49084870
score: 1
type: Question
has answer: http://stackoverflow.com/a/49084863
downvote count: 0
accepted answer: http://stackoverflow.com/a/49084870
tagged with: python
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/49085005
possible better answer: http://stackoverflow.com/a/49084873
has comment: http://stackoverflow.com/comment/85175112
has body: I want to extract a number after every ":" (colon) in a string using python 3.5 my string is: x= "RTD - Shanghai Indices - STD DLY - Indices - 11054 - ID:1053 (INACTIVE) RTD - SIX Swiss incl. SWX Europe - STD L1 - Equity - 10969 - ID:1096 (INACTIVE)" I have used: re.findall('\d+', x) but this returns all the number which is: ['11054', '1053', '1', '10969', '1096'] But the final result should be: [1053, 1096]
has answer: http://stackoverflow.com/a/49084873
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/49091189
has comment: http://stackoverflow.com/comment/85187874
has body: You could try like this: a=6 b=7 res = [x for x in range(10) if abs(x-a)==1] print(b in res)
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85188030
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49091163

appjar
type: Tag
tags question: http://stackoverflow.com/q/48986533
tag name: appjar

http://stackoverflow.com/q/49018026
upvote count: 0
type: UnansweredQuestion
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/49020525
tagged with: attributeerror
tagged with: models
has comment: http://stackoverflow.com/comment/85041792
has comment: http://stackoverflow.com/comment/85045992
score: -1
has comment: http://stackoverflow.com/comment/85041611
has body: I am running my django server and I am getting a 500 code with the error AttributeError: type object 'EventPurpose' has no attribute 'objects' the model however was created correctly and other models with the same implementation are working fine. Here is the full code from model creation to use. model creation class EventPurpose(models.Model): purpose = models.CharField(max_length=200) view class GetAllSettingsObjects(APIView): def get(self, request, format=None): eventpurposequeryset = EventPurpose.objects.all() and that is were I get the error: The error in full line 24, in get eventpurposequeryset = EventPurpose.objects.all() AttributeError: type object 'EventPurpose' has no attribute 'objects' [27/Feb/2018 20:57:55] "GET /&lt;super cool url object that I dont want to share with you&gt;/ HTTP/1.1" 500 16404 I still haven't figured this out so here is the full trace back: Internal Server Error: /api/dependancy/suitsadmin/settings/ Traceback (most recent call last): File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/rickus/Documents/softwareProjects/211hospitality/suits…
has title: django not reconizing default objects manager for model
linked to: http://stackoverflow.com/q/35543695
answer count: 1
downvote count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/85045249
favorite count: 0
has comment: http://stackoverflow.com/comment/85055595
tagged with: python

http://stackoverflow.com/q/49115298
tagged with: url
has title: django authentification error
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85270544
has comment: http://stackoverflow.com/comment/85236320
tagged with: django
tagged with: python
has body: I am running into an error where I am logging in a user and it is supposed to redirect to details.html but instead the the url gets parsed but it stays at login.html. I believe there is a problem with the views.py. If there is a better way of doing this please let me know. Thanks views.py @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def patientDetails(request, personalInfo_id): current_user = request.user if personalInfo_id == current_user.id: return render(request, 'personalInfo/details.html', {}) else: return render(request, 'personalInfo/login.html', {}) @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def after_login(request): return HttpResponseRedirect('/personalInfo/details/%d/'%request.user.id) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/$', views.after_login, name='patient'), url(r'^details/(?P&lt;personalInfo_id&gt;[0-9]+)/$', views.patientDetails), ] Picture of what is going wrong
tagged with: view
answer count: 0
has comment: http://stackoverflow.com/comment/85235754
type: Question
has comment: http://stackoverflow.com/comment/85238046
score: 0

http://stackoverflow.com/a/49015830
has comment: http://stackoverflow.com/comment/85038811
score: 3
has comment: http://stackoverflow.com/comment/85039183
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49015686
has body: How do I utilize the innertext,"T-Mobile", to click the button? find_elements_by_link_text would be appropriate for this case. elements = driver.find_elements_by_link_text('T-Mobile') for elem in elements: elem.click() There's also a by_partial_link_text locator as well if you don't have the full exact text. How would I execute the onclick event? The simplest way would be to simply call .click() on the element as shown above and the event should, naturally, execute at that time. Alternatively, you can retrieve the onclick attribute and use driver.execute_script to run the js. for elem in elements: script = elem.get_attribute('onlcick') driver.execute_script(script) Edit: note that in your code you did element.click -- this does nothing. element.click() (note the parens) calls the click method. is there a way to utilize browser.execute_script() for the onclick event execute_script can fire the equivalent event, but there may be more listeners that you miss by doing this. Using the element click method is the most sound. There may very well be many implementation details of the site that may hinder your automation efforts, but those possibilities are endless. Without seeing the actual context, it's hard to say. You can use JS methods to click an element or otherwise interact with the page, but you may miss certain event listeners that occur when using the site 'normally'; you want to emulate, more or less, the normal use as closely as possible.
has comment: http://stackoverflow.com/comment/85037087
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85628875
type: Answer
answers question: http://stackoverflow.com/q/49015686
has comment: http://stackoverflow.com/comment/85628984

http://stackoverflow.com/comment/84977591
comment on: http://stackoverflow.com/a/48985994
type: AnswerComment
score: 0
type: Comment
has text: so... give me a link :)

http://stackoverflow.com/comment/85071703
score: 0
type: Comment
type: QuestionComment
has text: What part of "Copy the contents of the file named src to a file named dst" is not clear?
comment on: http://stackoverflow.com/q/49032610

http://stackoverflow.com/q/49048508
accepted answer: http://stackoverflow.com/a/49048562
has body: I have a file with the following text: Oh, speak again, bright angel, for thou art As glorious to this night, being o'er my head As is a winged messenger of heaven Unto the white-upturned wondering eyes Of mortals that fall back to gaze on him When he bestrides the lazy-puffing clouds And sales upon the bosom in the air The task is: I have to replace the lines that begin with "As" with an empty line and then save the output into a new file. So far, I've figured out how to replace the words. Here's my last code: def change_strings(): with open ("file1.txt") as file1: strings = file1.readlines() for string in strings: if not string.startswith("As"): with open("file2.txt", "w") as file2: file2.write(string) However, I only get the last line saved into a new file. What am I doing wrong?
possible better answer: http://stackoverflow.com/a/49048589
has title: How to replace a string with an empty one (in a file)
has comment: http://stackoverflow.com/comment/85101206
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49048562
tagged with: python
has comment: http://stackoverflow.com/comment/85101262
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49048589

http://stackoverflow.com/q/49088880
has body: **Update** =================================================== Ok guys, so far so good. I have code that allows me to scrape images, but it stores them in a strange way. It downloads first 40+ images, then creates another 'kittens' folder within previously created 'kittens' folder and starts over (downloading the same images as in first folder). How can I change it? Here is the code: from selenium import webdriver from selenium.webdriver import Chrome from selenium.common.exceptions import WebDriverException from bs4 import BeautifulSoup as soup import requests import time import os image_tags = [] driver = webdriver.Chrome() driver.get(url='https://www.pexels.com/search/kittens/') last_height = driver.execute_script('return document.body.scrollHeight') while True: driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') time.sleep(1) new_height = driver.execute_script('return document.body.scrollHeight') if new_height == last_height: break else: last_height = new_height sp = soup(driver.page_source, 'html.parser') for img_tag in sp.find_all('img'): image_tags.append(img_tag) if not os.path.exists('kittens'): os.makedirs('kittens') os.chdir('kittens') x = 0 for image in image_tags: try: url = image['src'] source = requests.get(url) with open('kitten-{}.jpg'.format(x), 'wb') as f: f.write(requests.get(url).content) x += 1 except: pass =========================================================================== im trying to write a spider to scrape images of kittens from some page. I've got small problem, because my spider only gets first 15 images. I know it's probably because the page is loading more images after scrolling down. How can I resolve this issue? Here is the code: import requests from bs4 import BeautifulSoup as bs import os url = 'https://www.pexels.com/search/cute%20kittens/' page = requests.get(url) soup = bs(page.text, 'html.parser') image_tags = soup.findAll('img') if not os.path.exists('kittens'): os.makedirs('kittens') os.chdir('kit…
type: Question
downvote count: 0
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/49088982
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85189897
has comment: http://stackoverflow.com/comment/85183357
linked to: http://stackoverflow.com/q/20986631
has title: Scraping all results from page with BeautifulSoup
tagged with: web-scraping

http://stackoverflow.com/comment/85177019
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49085781
type: AnswerComment
has text: other than {a-z}

http://stackoverflow.com/a/49031084
has comment: http://stackoverflow.com/comment/85074993
has body: Hope this would help, component.py class Component: def __init__(self, owner, data): self.owner = owner self.name = data['name'] car.py from component import Component class Car: def __init__(self, data): self.components = [] self.type = data['type'] self.color = data['color'] def add_car_components(self, data): self.components.append(Component(self, data)); c = Car({'type': 'bus', 'color': 'red'}) c.add_car_components({'name': 'frontdoor'}) c.add_car_components({'name': 'reardoor'}) for component in c.components: print(component.owner.type, component.owner.color, component.name) Result: -&gt;python car.py bus red frontdoor bus red reardoor
has comment: http://stackoverflow.com/comment/85072840
downvote count: 0
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49023836
has comment: http://stackoverflow.com/comment/85074785
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49023836
has comment: http://stackoverflow.com/comment/85074907
has comment: http://stackoverflow.com/comment/85074847
has comment: http://stackoverflow.com/comment/85090981
has comment: http://stackoverflow.com/comment/85072835
type: Answer

http://stackoverflow.com/q/49046972
score: 0
has title: Python -> TypeError: list indices must be integers, not str
favorite count: 0
has answer: http://stackoverflow.com/a/49047112
tagged with: typeerror
has comment: http://stackoverflow.com/comment/85098473
tagged with: python
possible better answer: http://stackoverflow.com/a/49047112
answer count: 4
has answer: http://stackoverflow.com/a/49047140
tagged with: integer
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49047141
tagged with: file
upvote count: 1
has comment: http://stackoverflow.com/comment/85098547
downvote count: 1
type: Question
has body: I have a list/array str4 in python, I want to access it with a variable which I strongly believe is an int because I test it with the function isdigit() and I also made a manual debug and checked that all the option come out correctly with the only number. temp = "variableX" file2 = open('file.txt','r') for line in file2: if line.find(temp) =! -1: posArray = line.split(temp)[1][1:3] if ")" in posArray: posArray = posArray[:-1] if posArray.isdigit(): num = posArray print temp+"("+num+")" print num print str4[num] The above code is used to debug, my problem is in the str4[num], the result of the above code is: variableX(1) 1 "this is position 1" Traceback (most recent call last): File "orderList.py", line34, in &lt;module&gt; print str4[num] TypeError: list indices must be integers, not str Why num is a digit but python tells me it is a string? What am I doing wrong?
has comment: http://stackoverflow.com/comment/85098456
accepted answer: http://stackoverflow.com/a/49047141
has answer: http://stackoverflow.com/a/49047167
tagged with: python-2.7

http://stackoverflow.com/q/49066162
has comment: http://stackoverflow.com/comment/85137332
accepted answer: http://stackoverflow.com/a/49066562
possible better answer: http://stackoverflow.com/a/49067008
has comment: http://stackoverflow.com/comment/85137480
has answer: http://stackoverflow.com/a/49066562
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85137751
has body: # Given three ints, a b c, print True if b is greater than a, # and c is greater than b. However, with the exception that if # "bOk" is True, b does not need to be greater than a. a = int(input()) b = int(input()) c = int(input()) bOk = bool(input()) print(((bOk and c &gt; b) or (b &gt; a and c &gt; b))) My program works for all combinations besides "3 2 4 False" I don't understand why it prints True for this combination. The first closed set should return False since bOk = False, and the second closed set should return False as well since b > a is False. Explanation would be much appreciated.
has title: Boolean logic in Python statement
type: Question
tagged with: boolean
has answer: http://stackoverflow.com/a/49067008
has comment: http://stackoverflow.com/comment/85137717
has answer: http://stackoverflow.com/a/49066844
tagged with: boolean-logic
score: 0
answer count: 3
tagged with: python

http://stackoverflow.com/q/49059917
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/49060683
has answer: http://stackoverflow.com/a/49060090
possible better answer: http://stackoverflow.com/a/49059974
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/49060177
type: AnsweredQuestion
score: -1
type: Question
tagged with: numpy
tagged with: for-loop
linked to: http://stackoverflow.com/q/49058472
has body: This is a follow-up post from a previous question of mine: Referring to arrays in a for-loop. I would like to generalize the solution proposed there in order to be able to complete more complex tasks, such as attaching a column to each array that contains the result of some calculation: import numpy as np list=[one, two, three] for arr in list: arr=np.column_stack([arr,5*arr[:,2]-arr[:,1])]) All three arrays have the same dimensions.
has answer: http://stackoverflow.com/a/49059974
tagged with: arrays
favorite count: 0
accepted answer: http://stackoverflow.com/a/49060683
has title: Iterating over a list of arrays while making changes to each array
answer count: 4

http://stackoverflow.com/comment/85068214
has text: Output is only coming 5 rows although in features it is 306 are there...!
comment on: http://stackoverflow.com/a/49026547
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49106472
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: python
linked to: http://stackoverflow.com/q/31387980
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49107092
score: 1
linked to: http://stackoverflow.com/q/7389759
upvote count: 1
tagged with: sqlalchemy
type: Question
has title: Python 3 writing large (300+ mb) XML with lxml
has body: I've been googling for past few days, but I simply couldn't find any remotely simillar problem :( My script in Python 3 has simple objective: connect to MySQL database and fetch data create XML with lxml save that XML to file Usually I had no problems with XML files containing 5000+ elements, but in this case I'm hitting max memory usage for my VPS (Amazon EC2 micro). My code (core part): engine = create_engine(config('DB_URI')) Session = sessionmaker(bind=engine) session = Session() query = session.query(Trips.Country, Trips.Region, Trips.Name, Trips.Rebate, Trips.Stars, Trips.PromotionName, Trips.ProductURL, Trips.SubProductURL, Trips.Date, Trips.City, Trips.Type, Trips.Price, TripsImages.ImageURL) \ .join(TripsImages) \ .all() # define namespace xmlns:g XMLNS = "{http://base.google.com/ns/1.0}" NSMAP = {"g": "http://base.google.com/ns/1.0"} # create root rss and channel rss = etree.Element("rss", nsmap=NSMAP, attrib={"version": "2.0"}) channel = etree.SubElement(rss, "channel", attrib={"generated": str(datetime.now())}) # add &lt;channel&gt; title and description channel_title = etree.SubElement(channel, "title") channel_link = etree.SubElement(channel, "link") channel_description = etree.SubElement(channel, "description") channel_title.text = "Trips" channel_link.text = "https://example.com" channel_description.text = "Description" # generate xml elements for count, elem in enumerate(query): item = etree.SubElement(channel, "item") url = "/".join(["https://example.com", elem.ProductURL, elem.SubProductURL, datetime.strftime(elem.Date, '%Y%m%d') ]) price_discounted = round(elem.Price - elem.Price * (elem.Rebate / 100)) etree.SubElement(item, XMLNS + "id").text = str(count) etree.SubElement(item, XMLNS + "title").text = elem.Country etree.SubElement(item, XMLNS + "description").text = elem.Product etree.SubElement(item, XMLNS + "link").text = url etree.SubElement(item, XMLNS + "image_link").text = elem.ImageURL etree.SubElement(item, XMLNS + "condition").text = "n…
downvote count: 0
accepted answer: http://stackoverflow.com/a/49107092
tagged with: lxml
answer count: 1

http://stackoverflow.com/comment/85183160
type: QuestionComment
has text: You're confusing a Module with a class it contains. You also have to create an object first.
score: 1
comment on: http://stackoverflow.com/q/49088836
type: Comment

http://stackoverflow.com/comment/84998899
type: Comment
comment on: http://stackoverflow.com/a/48979033
score: 0
type: AnswerComment
has text: Thank you so much for your help however I am still quite new to python so I was trying put use the function getAviNameWithDate however I struggle to find the write place to put the code and use it ( or run it all together )

http://stackoverflow.com/q/49051507
linked to: http://stackoverflow.com/q/3985214
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85108326
has comment: http://stackoverflow.com/comment/85110899
has answer: http://stackoverflow.com/a/49053920
accepted answer: http://stackoverflow.com/a/49053920
type: Question
tagged with: database
has comment: http://stackoverflow.com/comment/85111447
has comment: http://stackoverflow.com/comment/85107830
has comment: http://stackoverflow.com/comment/85107946
score: 0
tagged with: mongodb
tagged with: sql
answer count: 1
has title: How to use find() nested documents for two levels or more?
has comment: http://stackoverflow.com/comment/85108155
has comment: http://stackoverflow.com/comment/85111540
has body: Here is my sample mongodb database database image for one object The above is a database with an array of articles. I fetched only one object for simplicity purposes. database image for multiple objects ( max 20 as it's the size limit ) I have about 18k such entries. I have to extract the description and title tags present inside the (articles and 0) subsections. The find() method is the question here.. i have tried this : for i in db.ncollec.find({'status':"ok"}, { 'articles.0.title' : 1 , 'articles.0.description' : 1}): for j in i: save.write(j) After executing the code, the file save has this : _id articles _id articles and it goes on and on.. Any help on how to print what i stated above? My entire code for reference : import json import newsapi from newsapi import NewsApiClient import pymongo from pymongo import MongoClient client = MongoClient() db = client.dbasenews ncollec = db.ncollec newsapi = NewsApiClient(api_key='**********') source = open('TextsExtractedTemp.txt', 'r') destination = open('NewsExtracteddict.txt', "w") for word in source: if word == '\n': continue all_articles = newsapi.get_everything(q=word, language='en', page_size=1) print(all_articles) json.dump(all_articles, destination) destination.write("\n") try: ncollec.insert(all_articles) except: pass

http://stackoverflow.com/comment/84976016
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48985466
has text: @ArpitSolanki how can I access to a single cell value in a similar way than Excel?

fabric
tags question: http://stackoverflow.com/q/49078795
tag name: fabric
type: Tag
tags question: http://stackoverflow.com/q/49040154

http://stackoverflow.com/comment/85000322
type: AnswerComment
score: 0
has text: Actually I just read the question again and yeah it's still a valid question. But I'm no good in regex so you'll have to get help elsewhere sorry ;)
type: Comment
comment on: http://stackoverflow.com/a/48997269

http://stackoverflow.com/comment/85221130
comment on: http://stackoverflow.com/q/49108090
has text: Does that number come DB id?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49056612
type: Answer
score: 0
has body: You just need a simple indexing: In [11]: a[i[:, 0], i[:, 1]] Out[11]: array([1, 4]) The first column of i is number of rows and the second one denotes the column number.
answers question: http://stackoverflow.com/q/49056388

http://stackoverflow.com/a/49005386
downvote count: 0
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/49005228
upvote count: 6
has comment: http://stackoverflow.com/comment/85016689
answers question: http://stackoverflow.com/q/49005228
has comment: http://stackoverflow.com/comment/85017208
has body: Please edit the answer providing your code. Its not clear now if its fluke of flake8 or problem with you style flake8 is usually not "too strict", its just pep8 compliance Try to format your code with yapf manually. If you'll still have the same issue - its the problem with yapf config. If not - its problem with vscode-yapf integration. Check yapf config in style section and "Custom arguments to Yapf " in vscode docs
type: AcceptedAnswer

http://stackoverflow.com/comment/84950062
has text: I want to calculate moving average but every 10 values.
score: 0
comment on: http://stackoverflow.com/q/48972271
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49019853
type: Answer
has comment: http://stackoverflow.com/comment/85047599
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/49019551
score: 1
has body: Here's one without explicit for loop. Not really recommended, though (side-effect in map which is a no-no to many): &gt;&gt;&gt; import itertools as it &gt;&gt;&gt; out = {} &gt;&gt;&gt; any(map(out.update, it.starmap(dict.fromkeys, map(reversed, my_dict.items())))) False &gt;&gt;&gt; out {1: 'key_a', 3: 'key_a', 4: 'key_a', 0: 'key_b', 2: 'key_b'}

http://stackoverflow.com/comment/94030763
type: AnswerComment
has text: When it comes about predictions. Do you need to perform transformation before? Example: dataset: {'age': int, 'country': str}, I followed your advise of doing conversion for train and eval, but when it comes to prediction we may need to convert the data to same format I trained right?
comment on: http://stackoverflow.com/a/51483908
score: 0
type: Comment

http://stackoverflow.com/comment/84937018
type: Comment
type: QuestionComment
has text: Yes............
comment on: http://stackoverflow.com/q/48965561
score: 0

http://stackoverflow.com/q/48968861
duplicate of: http://stackoverflow.com/q/24076297
has comment: http://stackoverflow.com/comment/84943571
has answer: http://stackoverflow.com/a/48969003
score: 2
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/84943381
downvote count: 1
has title: Python : AttributeError: 'str' object has no attribute '1s'
has body: I am trying to print the first letter of the inputted middle name, and print that, instead of the entire middle name first_name = str(input("Please enter your first name: ")) middle_name = str(input("Please enter your middle name: ")) last_name = str(input("Please enter your last name: ")) first_name = first_name.capitalize() first_name = middle_name.capitalize() last_name = last_name.capitalize() name_format = "{first} {middle.1s} {last}" print(name_format.format(first=first_name, middle=middle_name, last=last_name)) Whenever I run the script in Cmd it states AttributeError: 'str' object has no attribute '1s'.
has comment: http://stackoverflow.com/comment/84943338
has comment: http://stackoverflow.com/comment/84943696
linked to: http://stackoverflow.com/q/24076297
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48968985

http://stackoverflow.com/comment/85227677
comment on: http://stackoverflow.com/q/49111258
has text: @gbtimmon The OP said explicitly that the boundary is not convex.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/49089834
type: Question
has comment: http://stackoverflow.com/comment/85185170
has comment: http://stackoverflow.com/comment/85186020
has answer: http://stackoverflow.com/a/49090211
has body: Suppose a location in a file at given offset is always 32 bits: | 00 01 02 03 04 -----|--------------- 0x30 | 99 9E 36 00 AC How would someone retrieve the hex value that spans multiple bytes (Case 1)? Now also given is the hex value needs to be reversed, the wanted outcome should be 0xAC00369E99 (Case 2). What is either a fast, efficient or clean way to retrieve this value within Python? Edit: This is the current way I do it def hexAtOffset(path): with open(path, "rb") as file: content = file.read() pointer = 0x30 hexString = "" for i in range (5): hexString += str(hex(content[pointer] ) )[2:] pointer+=1 return hexString[::-1] print (hexAtOffset() ) One problem I face here is that two zeros in 0x00 get shortened to 0x0
has comment: http://stackoverflow.com/comment/85186645
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85186524
has title: Retrieve hex value from a file that is multiple bytes long (and reverse the hex digits)?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85185617
has comment: http://stackoverflow.com/comment/85186160
accepted answer: http://stackoverflow.com/a/49090211

http://stackoverflow.com/q/49000872
answer count: 1
tagged with: flask
favorite count: 0
has body: I know that is a display element. Therefore, I am displaying data inside the paragraph as a python variable in the {{ filename }} But In the I have a download button that downloads whatever in the as a text file. To do that I stored another version of the data in a hidden Then I put a download button as follows: Download In Flask I have this: @app.route('/database_download', methods=['GET', 'POST']) def download_file(): if request.method == 'POST': f = request['fileData'] response = make_response(f) response.headers["Content-Disposition"] = "attachment; filename=result.txt" return response return render_template('upload.html') The problem I have is that when I remove return render_template from the end, it gives me a ValueError: View function did not return a response or if I keep it then when I click on download nothing happens, it just re-direct me to the same page. Any suggestions please ?
has answer: http://stackoverflow.com/a/49000924
tagged with: python
type: AnsweredQuestion
has title: Request data from HTML paragraph to download using Python Flask
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49000924
score: -1
upvote count: 0

http://stackoverflow.com/a/49033665
type: Answer
answers question: http://stackoverflow.com/q/49033540
score: 0
has body: If you have a list you can iterate over it with a for-loop. item ['author'] = sel.xpath('.//a[contains(@data-hook, "review-author")]/text()').extract() // Using this for-loop construct instead of indices avoids off-by-one errors // and the code won't run if the list is empty. for element in item['author']: print element // Do whatever you want with the element.

http://stackoverflow.com/q/49012141
accepted answer: http://stackoverflow.com/a/49012373
tagged with: pyqt4
type: AnsweredQuestion
tagged with: python
has title: Python 3 key-sorted dict function not working correctly with PyQt4
tagged with: qtextedit
tagged with: python-3.x
type: Question
score: 0
has body: I have a function which is supposed to sort a dict and print the result in a QTextEdit box - "ADtext" in the gui window. Example dict: lunch = {5: "14:00-16:00",27: "12:00-13:00", 13: "12:00-13:00"} function: def example(self): keys= list(lunch.keys()) keys.sort() for key in keys: self.ADtext.setText("({} =&gt; {})".format(key, lunch[key])) However in the gui QTextEdit -"ADtext" box only one of the pairs is shown (always the same). The function works without problems if I print the result in cmd (not in the QTextEdit box): print ("({} =&gt; {})".format(key, lunch[key]))
has answer: http://stackoverflow.com/a/49012373
answer count: 1
tagged with: pyqt

http://stackoverflow.com/comment/85124917
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49059715
has text: Better yet, clarify and illustrate with data including input data and desired output result.

http://stackoverflow.com/a/49102625
has comment: http://stackoverflow.com/comment/85238925
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85237296
accepted answer of: http://stackoverflow.com/q/49102589
has body: Iterating through rows will work, though it is far faster to use numpy.where() data_all['New Column'] = np.where(data_all['Column A'] &gt; 0, data_all['Column A'], data_all['Column B'])
answers question: http://stackoverflow.com/q/49102589
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85171426
type: Comment
comment on: http://stackoverflow.com/q/49082914
score: 0
type: QuestionComment
has text: Possible duplicate of [Python: Lifetime of module-global variables](https://stackoverflow.com/questions/17301091/python-lifetime-of-module-global-variables)

http://stackoverflow.com/a/49048589
score: 1
has body: this is what i meant in my comment - instead of re-opening and overwriting your output-file open it once only. also note that there is no need for .readlines(); that will read your whole file in memory which may not be what you want if your file is really big. from io import StringIO text = '''Oh, speak again, bright angel, for thou art As glorious to this night, being o'er my head As is a winged messenger of heaven Unto the white-upturned wondering eyes Of mortals that fall back to gaze on him When he bestrides the lazy-puffing clouds And sales upon the bosom in the air ''' with StringIO(text) as infile, open('out.txt', 'w') as outfile: for line in infile: if not line.startswith("As"): outfile.write(line) ...of course you need to replace StringIO(text) with open('file1.txt', 'r'). this was just to make my example self-containing.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49048508
downvote count: 0
has comment: http://stackoverflow.com/comment/85101356
has comment: http://stackoverflow.com/comment/85101332

http://stackoverflow.com/a/49008896
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49003440
has body: For serialising a pandas.DataFrame into JSON you can use its to_json() method. There are different formatting options: &gt;&gt;&gt; df 0 1 0 a b 1 c d &gt;&gt;&gt; df.to_json() '{"0":{"0":"a","1":"c"},"1":{"0":"b","1":"d"}}' &gt;&gt;&gt; df.to_json(orient='values') '[["a","b"],["c","d"]]'
answers question: http://stackoverflow.com/q/49003440
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85030480
score: 3
has text: A csv file has no way to represent merged cells. The best you could achieve would be blank fields in place of repeated values. You might consider sending your data directly to Excel and merging the cells there.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49012156

http://stackoverflow.com/a/48990656
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48989751
has body: I think this is the plot you are after. Pandas is not used at all. You should be able to modify this to get the desired output. If instead you wanted to use the dictionary keys directly you could look into using the 'categories' functionality of matplotlib: https://matplotlib.org/gallery/lines_bars_and_markers/categorical_variables.html import matplotlib.pyplot as plt # use these to generate positions and add legend labels labels = {0:'A', 1:'B'} # this sets the position of each set of bars offsets = {0:-0.15, 1:+0.15} # define the main positions main_positions = [i for i in range(len(collect[0]))] ## loop each set of data in the dict using the defined labels for label in labels: # generate list of values to plot vals = [collect[label][i] for i in sorted(collect[label])] # plot the data and set the tick labels plt.bar([main_positions[i] + offsets[label]+1 for i in main_positions],vals,width=0.3,label=labels[label]) ## tidy the xticks and add legend plt.xticks([i+1 for i in main_positions]) plt.legend() plt.show()
upvote count: 2
answers question: http://stackoverflow.com/q/48989751
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/85000525
has text: yep that did the trick--was my suspicion--regex is basically my kryptonite. appreciate the help Daniel
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48997495
type: AnswerComment

http://stackoverflow.com/comment/85256370
score: 0
type: AnswerComment
type: Comment
has text: ofcourse, it takes longer for the weights to get tuned, but you will get good accuracy in one instance. if you are tired of continuous training, train it by checkpoints of your previous training, then it might be easy. Thanks for accepting the answer.
comment on: http://stackoverflow.com/a/49105854

http://stackoverflow.com/a/49117146
accepted answer of: http://stackoverflow.com/q/49116988
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49116988
has comment: http://stackoverflow.com/comment/85327528
has comment: http://stackoverflow.com/comment/85327755
type: Answer
has comment: http://stackoverflow.com/comment/85327693
downvote count: 0
score: 3
has body: With mask pdf.mask(pdf.loc[:,arb_cols]==2,99).assign(c=pdf.c) Out[1190]: a b c 0 1 99 5 1 99 3 6 2 3 4 7 Or with assign pdf.assign(**pdf.loc[:,arb_cols].mask(pdf.loc[:,arb_cols]==2,99)) Out[1193]: a b c 0 1 99 5 1 99 3 6 2 3 4 7
upvote count: 3

http://stackoverflow.com/a/49087165
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: Solution 1 I'm pretty sure this does what you want. It fits a second degree (quadratic) polynomial to your data, then plots that function on an evenly spaced array of x values ranging from the minimum to the maximum of your original x data. new_x = np.linspace(min(x), max(x), num=np.size(x)) coefs = np.polyfit(x,y,2) new_line = np.polyval(coefs, new_x) Plotting it returns: plt.scatter(x,y) plt.scatter(new_x,new_line,c='g', marker='^', s=5) plt.xlim(min(x)-0.00001,max(x)+0.00001) plt.xticks(rotation=90) plt.tight_layout() plt.show() if that wasn't what you meant... However, from your question, it seems like you might be trying to force all your original y-values onto evenly spaced x-values (if that's not your intention, let me know, and I'll just delete this part). This is also possible, there are lots of ways to do this, but I've done it here in pandas: import pandas as pd xy_df=pd.DataFrame({'x_orig': x, 'y_orig': y}) sorted_x_y=xy_df.sort_values('x_orig') sorted_x_y['new_x'] = np.linspace(min(x), max(x), np.size(x)) plt.figure(figsize=[5,5]) plt.scatter(sorted_x_y['new_x'], sorted_x_y['y_orig']) plt.xlim(min(x)-0.00001,max(x)+0.00001) plt.xticks(rotation=90) plt.tight_layout() Which looks pretty different from your original data... which is why I think it might not be exactly what you're looking for.
accepted answer of: http://stackoverflow.com/q/49086896
answers question: http://stackoverflow.com/q/49086896
type: AcceptedAnswer

http://stackoverflow.com/comment/85237369
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49115909
score: 1
has text: Not related to your problem, but you're doing much more work than you need. `authenticate` already checks that the user exists as well as verifying the password, so there's no point in the separate User query; also you really don't need to call authenticate both in the form and the view.

http://stackoverflow.com/a/49027416
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49027000
has body: You need to process each row in the loop and get information you want from it: data = [] for data_row in gain.xpath('//table[@class="TableBorderBottom"]/tr[position() &gt; 1]'): stock = data_row.xpath('./td[3]/text()')[0] last_done = data_row.xpath('./td[5]/text()')[0] change = data_row.xpath('./td[6]/span/text()')[0] data.append({ "Stock": stock, "Last Done": last_done, "Change": change })
answers question: http://stackoverflow.com/q/49027000

http://stackoverflow.com/a/49076077
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49073887
downvote count: 0
has body: Since your edit history indicates multiple updates, below is a list addressing your overall SQL syntax issues. In SQL Server, INNER JOIN must be paired with an ON clause. Your very first version did not do so. CROSS JOIN are the only joins that do not need ON clauses and SQL Server's specific CROSS APPLY or OUTER APPLY. Table aliases used in FROM or JOIN clauses must be maintained in all other clauses: SELECT, WHERE, or GROUP BY. Either stick to ST and UT or SE and SP namings but maintain their usage. Do not prefix column identifiers if they are not defined elsewhere. Column identifiers with names and special characters as well as reserved words should be escaped. In SQL Server, you can escape with square brackets. Hence, First Name column with its space requires escaping and should read: WHERE userKey LIKE ? AND [First Name] LIKE ? Because SQL requires proper punctuation and spaces in its grammar, consider using Python's triple-quote multi-line block for long strings like SQL statements: SQLCommand = """SELECT UT.userID, ST.Status, UT.userName FROM dbo.StatusTable as ST (nolock) INNER JOIN dbo.UserTable as UT (nolock) ON ST.userID = UT.userID WHERE UT.userKey LIKE ? AND UT.[First Name] LIKE ?""" As a final note, none of your issues here is due to Python or pypyodbc which interface to your SQL Server database. All such errors are being raised by the MSSQL engine due to syntax issues. These same items would fail in other ODBC (i.e., VBA's ADO or R's RODBC) or non-ODBC (i.e., Java's JDBC or Python's pymssql) connections. The bottom SQL query that works is substantively different than the one being attempted inside Python such as no spaces between clauses UT.userID(nolock)WHERE, no use of First Name, and no misuse of table aliases.

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/49112581
tag name: countvectorizer

http://stackoverflow.com/comment/85068031
has text: `file.read(1023)`?
score: 1
comment on: http://stackoverflow.com/q/49031690
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85170957
type: AnswerComment
has text: I do see frames consist of all individual ratings of users x variables, that means, rating given by teen, M, single, clerk, individually, but cant I group by with all four ? age, gender, mar_sta and occ ?
type: Comment
comment on: http://stackoverflow.com/a/49024574
score: 0

http://stackoverflow.com/comment/85000610
has text: the problem is that i have a list of 'dependent' parameters that i want to retrieve. All these parameters are written to different lines (e.g. `ncomp` * 2 + 1, or `ncomp`*3 +1 and 'ncomp` * 2+ 'ncomp2' + 1 (i.e. dependent on two parameters). There is quiet a number of these variables with different dependencies. I thought it would be nice to capture all these different dependencies in a dictionary (the parameter dictionary in my post). How can I accommodate for this in a clean and elegant way?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48995509

http://stackoverflow.com/a/49092284
score: 4
accepted answer of: http://stackoverflow.com/q/49092248
type: Answer
upvote count: 4
has body: You have to reset F_Count = 0 after while N_Count &lt; len(N):, otherwise list F is only looped once. So it would be: ... while N_Count &lt; len(N): F_Count = 0 while F_Count &lt; len(F): ... But unless you're learning about loops, this would not be the best way to do what you want. Something using count would be better, like: counts = [N.count(f) for f in F] or similar
downvote count: 0
answers question: http://stackoverflow.com/q/49092248
has comment: http://stackoverflow.com/comment/85189920
type: AcceptedAnswer

http://stackoverflow.com/a/49025420
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49025275
has body: I put the below code as an example. Here I look for all the keys that have 'Blue' in their values. Anyway, as said by COLDSPEED, this use of a dictionary is very unoptimized. dic = {"a" : "Blue Jacket with buttons", "b" : "Green Jacket with a buttons", "c" : "Blue jacket"} keywords = "Blue, Jacket, Buttons" keywords = keywords.split(",") for key, value in dic.iteritems(): if keywords[0] in value: print key

http://stackoverflow.com/q/48998839
has comment: http://stackoverflow.com/comment/85155918
favorite count: 0
has answer: http://stackoverflow.com/a/48999217
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I have a .html saved on my disk and I open with a text editor. Then I try to find all the http ....etc where are on the html file. I open, read the file but how can I mention with for loop that "Hey give me all the hyperlinks after the href= ?" Any suggestion? I try to solve it without Beautiful soup.
type: UnansweredQuestion
upvote count: 1
has title: Parse a html file without Beautiful soup
score: 1
has comment: http://stackoverflow.com/comment/85003881
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85003043

http://stackoverflow.com/q/49022656
tagged with: static
tagged with: abstract-class
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85050364
tagged with: python
tagged with: properties
answer count: 4
tagged with: attributes
linked to: http://stackoverflow.com/q/2736255
has body: What I'd really like to do is something like this: class X(metaclass=abc.ABCMeta): @abc.abstractAttribute # this doesn't exist var = [1,2] class Y(X): var = X.var + [3,4] This would force any subclasses of X to implement a static var attribute. But there's no way to define a static attribute as abstract. Attempting to use @abc.abstractmethod, combined with property, I can get close: class X(metaclass=abc.ABCMeta): @property @abc.abstractmethod def var(self): return [1,2] class Y(X): @property def var(self): return super().var + [3,4] y=Y(); y.var gives [1,2,3,4] as desired. But the goal is to create a static attribute/property, not an instance attribute/property. When creating as a @staticmethod: class X(metaclass=abc.ABCMeta): @property @staticmethod @abc.abstractmethod def var(): return [1,2] class Y(X): @property @staticmethod def var(): return X.var + [3,4] ... then y=Y(); y.var gives TypeError 'staticmethod' object is not callable If I switch the decorator order, this will resolve the staticmethod callable error: class X(metaclass=abc.ABCMeta): @staticmethod @property @abc.abstractmethod def var(): return [1,2] class Y(X): @staticmethod @property def var(): return X.var + [3,4] The static method will work, but the property will not function as intended: y=Y(); y.var returns the property itself, &lt;property at 0x2c16aa1b3b8&gt;. This answer is close to what's desired, but it doesn't work in this case since the base class, X, will already have a var attribute (so subclass can access via super). How do you define a python class to have an abstract, static attribute/property?
has answer: http://stackoverflow.com/a/58206480
type: Question
has answer: http://stackoverflow.com/a/64397790
has comment: http://stackoverflow.com/comment/85050472
upvote count: 20
score: 20
has title: Python: Create Abstract Static Property within Class
has answer: http://stackoverflow.com/a/63346084
has answer: http://stackoverflow.com/a/49024227
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/49046347
score: 2
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/49046241
has body: Strings in python are inmutable, so you cannot change its content. One solution would be to split the string, change the letter and stick it back together: splitted = list(hidden_name) splitted[i] = c hidden_name = ''.join(splitted)
has comment: http://stackoverflow.com/comment/85097331

http://stackoverflow.com/comment/85180856
has text: This is kind of technical, and you can think of it as a tuple, but it does not have an internal tuple. It's really a memory view at the C code level
type: Comment
comment on: http://stackoverflow.com/a/49087609
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84936417
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48965249
has text: How fast are you hitting the server - what is the server? Is it something local that can only handle one things at a time for instance and maybe it hasn't cleared up your old request to handle the new one... Is it just a glitchy unreliable server... etc...? How many URLs do you have - how long do you want to keep trying before giving up - what do you want to do with errors... etc...? It's hard to suggest alternatives when we don't know what you'd like to achieve :)
type: Comment

http://stackoverflow.com/comment/85045589
type: QuestionComment
comment on: http://stackoverflow.com/q/49019371
has text: The solution is staring you in the face. Add the required dimensions. Or be lazy and use a function that adds them for you.
score: 0
type: Comment

http://stackoverflow.com/q/49093469
has answer: http://stackoverflow.com/a/49094232
score: 0
has body: i run following codes in python3: import sqlite3 conn = sqlite3.connect("data.db") conn.execute("create table if not exists data(\ id int prinmary key,view int)") conn.execute("insert into data (id,view) values (0,0)") conn.execute("insert into data (id,view) values (1,'--')") print(conn.execute("select * from data order by id").fetchall()) conn.commit() conn.close() and no error occured, "[(0, 0), (1, '--')]" was printed, why?
answer count: 2
tagged with: sqlite
accepted answer: http://stackoverflow.com/a/49094232
possible better answer: http://stackoverflow.com/a/49093602
has title: why can i insert string value into int column in python sqlite database
has answer: http://stackoverflow.com/a/49093602
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85193316
type: Question
tagged with: database

http://stackoverflow.com/comment/85235832
has text: i have replaced "display_board().board.replace("O", marker)" with "display_board()[col_guess-1][row_guess-1] == marker print(display_board())" but it's not changing the item, why?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49097918

http://stackoverflow.com/q/49075062
score: -2
has title: Scikit-Image: Why won't 'data', 'io', 'viewer' modules import?
downvote count: 2
tagged with: scikit-image
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85170717
has body: I get this error: ImportError: DLL load failed: The specified module could not be found. when I try to import certain Scikit-image modules, 'data', 'io', 'viewer'. The others seem to work fine. I am using the latest version of Anaconda and Scikit-image (0.13.1). I have v3.6.4 python. System is 32bit windows 10. [Edit: code used is: from skimage import data and the error produced is: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-33-cde2e39a26a4&gt; in &lt;module&gt;() ----&gt; 1 from skimage import data ~\Anaconda3\lib\site-packages\skimage\data\__init__.py in &lt;module&gt;() 14 15 from .. import data_dir ---&gt; 16 from ..io import imread, use_plugin 17 from .._shared._warnings import expected_warnings 18 from ._binary_blobs import binary_blobs ~\Anaconda3\lib\site-packages\skimage\io\__init__.py in &lt;module&gt;() 5 """ 6 ----&gt; 7 from .manage_plugins import * 8 from .sift import * 9 from .collection import * ~\Anaconda3\lib\site-packages\skimage\io\manage_plugins.py in &lt;module&gt;() 26 from glob import glob 27 ---&gt; 28 from .collection import imread_collection_wrapper 29 30 ~\Anaconda3\lib\site-packages\skimage\io\collection.py in &lt;module&gt;() 10 import numpy as np 11 import six ---&gt; 12 from PIL import Image 13 14 from ..external.tifffile import TiffFile ~\Anaconda3\lib\site-packages\PIL\Image.py in &lt;module&gt;() 56 # Also note that Image.core is not a publicly documented interface, 57 # and should be considered private and subject to change. ---&gt; 58 from . import _imaging as core 59 if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None): 60 raise ImportError("The _imaging extension was built for another " ImportError: DLL load failed: The specified module could not be found. Thanks in advance...
has answer: http://stackoverflow.com/a/49082766
answer count: 1
has comment: http://stackoverflow.com/comment/85169922
favorite count: 0
has comment: http://stackoverflow.com/comment/85160063
has comment: http://stackoverflow.com/comment/85170239
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85070698
has text: Why is not `M[iM[:, 0]]` for `n == 1`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49032941
score: 0

http://stackoverflow.com/comment/107580987
type: Comment
type: QuestionComment
has text: Does this answer your question? [Beautiful Soup: 'ResultSet' object has no attribute 'find\_all'?](https://stackoverflow.com/questions/24108507/beautiful-soup-resultset-object-has-no-attribute-find-all)
comment on: http://stackoverflow.com/q/49002709
score: 0

http://stackoverflow.com/a/57693590
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49092807
has body: This solved my problem. For Windows: Try deleting the pip folders in AppData/Temp. Python is unable to delete these folders and create new pip folders for unpacking the new installations.
downvote count: 0
type: Answer

http://stackoverflow.com/a/49002930
downvote count: 0
score: 1
has body: I think this should the trick:- list_args = ['201708', '201709', '201710', '201711', '201712', '201801'] str("""select * from dbo.month_step where month_id IN (%s) and tier = 'Sil';""") % (','.join(list_args)) It is simpler and works.
upvote count: 1
answers question: http://stackoverflow.com/q/49002726
type: Answer

http://stackoverflow.com/q/49031748
has title: Pyspark multiprocessing using pool.map()
linked to: http://stackoverflow.com/q/20360686
has comment: http://stackoverflow.com/comment/85068291
tagged with: python-2.7
type: UnansweredQuestion
has body: I am calling full_item() for each element of a list size_DF and passing some parameters to the function. map(lambda x : object.full_item(sc, Database, len(x), end_date),size_DF) map function is working but it is taking more time as list contains more elements. I tried the multiprocessing but getting the error as below: from multiprocessing import Pool pool = Pool() pool.map(lambda x : object.full_item(sc, Database, len(x), end_date),size_DF) cPickle.PicklingError: Can't pickle : attribute lookup builtin.function failed Please help and let me know how can i proceed.
tagged with: python
has comment: http://stackoverflow.com/comment/85068312
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/85069637
has comment: http://stackoverflow.com/comment/85068801
type: Question
tagged with: python-multiprocessing
tagged with: pyspark

http://stackoverflow.com/q/49011058
type: Question
tagged with: python
has body: Hi Im really struggling trying to move some files around. What I want to do is look through a directory find all files that are .jpg and do not start with '.'. I want to modify the filenames of all the jpg's and move them into another directory while keeping them in their sub directories. Some jpg's are in the the root directory and not in a sub. All the files need to be removed from the original place after moving except hidden .files So far I have tried lots of things, one was to: xmpDir = '/Users/richard/Desktop/_xmpDir' xmpAdded = '/Users/richard/Desktop/_xmpAdded' os.chdir(xmpDir) cwd = os.getcwd() for dirName, subdirList, fileList in os.walk(cwd): print('Found directory: %s' % dirName) for sub in subdirList: print(sub) for fname in fileList: if not fname.startswith('.'): print(fname) if not os.path.exists(xmpAdded + '/' + sub ): os.makedirs(xmpAdded + '/' + sub ) shutil.move(dirName + '/' + fname, xmpAdded + '/' + sub + '/' + fname) All this does is move all the files into the first sub directory it comes across. I can use os.walk to go through all the directories and make changes to my files but when I go to move them it puts them all in one folder: os.chdir(xmpDir) cwd = os.getcwd() for dirName, subdirList, fileList in os.walk(cwd): for fname in fileList: if not fname.startswith('.'): newFname = removeID(fname) print(newFname) print(fname) shutil.move(dirName + '/' + fname, newPath1 + '/' + dirName + newFname) I would really appreciate any help I can get. Thanks
has title: Recursively look through a whole directory tree, modify filenames of all files and move the tree excluding hidden . files
has comment: http://stackoverflow.com/comment/85027088
score: 0
has comment: http://stackoverflow.com/comment/85026802
answer count: 0
type: UnansweredQuestion
tagged with: python-2.7
tagged with: shutil

http://stackoverflow.com/q/49002383
score: 0
answer count: 1
tagged with: ocr
type: UnansweredQuestion
tagged with: python
has body: I want to write a python code for Persian letter recognition. I have a dataset of Farsi alphabet that has 15 instances from each class. There are 19 classes. Actually I don't have much experience in python. I almost know what are the steps theoretically but I dont know the coding. Fisrt I want to convert images to feature vectors, but I don't know how to do this:/ I've searched a lot but I couldn't find anything useful. Any help would be highly appreciated.
has comment: http://stackoverflow.com/comment/85013206
type: Question
has comment: http://stackoverflow.com/comment/85068493
tagged with: feature-extraction
has answer: http://stackoverflow.com/a/49048096
has title: Converting images of alphabet to feature vector

http://stackoverflow.com/comment/85207375
type: Comment
comment on: http://stackoverflow.com/a/49101029
has text: I'm not against it at all, it's just somewhat funny.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49004246
score: 0
possible better answer: http://stackoverflow.com/a/49004407
has answer: http://stackoverflow.com/a/49004537
has title: list of jpeg files in nested subdirectories
has answer: http://stackoverflow.com/a/49004407
has answer: http://stackoverflow.com/a/49004424
answer count: 4
accepted answer: http://stackoverflow.com/a/49004537
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49004432
type: Question
tagged with: python
has body: I use the following python code to get list of jpg files in nested subdirectories which are in parent directory. import glob2,os all_header_files = glob2.glob(os.path.join('Path/to/parent/directory','/**/*.jpg')) However, I get nothing but when I cd into the parent directory and I use the following python code then I get the list of jpeg files. import glob2 all_header_files = glob2.glob('./**/*.jpg') How can I get the result with the absolute path?(first version)

http://stackoverflow.com/q/48994414
downvote count: 0
has answer: http://stackoverflow.com/a/48994725
has answer: http://stackoverflow.com/a/70922457
favorite count: 0
tagged with: beautifulsoup
answer count: 5
has answer: http://stackoverflow.com/a/49001887
tagged with: http://stackoverflow.com/tag/html
tagged with: python
possible better answer: http://stackoverflow.com/a/48994612
type: AnsweredQuestion
score: 1
has body: I am currently trying to web scrape a product name out of a website, however, the text is contained within a tag I have never seen before, and hence do not know how to get the text out. Gradient Puffy Jacket I am trying to get the name "Gradient Puffy Jacket" to be accessible from my program with beautiful soup 4 using python 2.7. I would appreciate any insight as this has stumped me for several days.
has title: Web scraping with Beautiful Soup Python
type: Question
has answer: http://stackoverflow.com/a/48994515
accepted answer: http://stackoverflow.com/a/48994515
has answer: http://stackoverflow.com/a/48994612
upvote count: 1

http://stackoverflow.com/q/49062392
has body: I have the same question solved here, but am looking for a solution using Flask-SQLAlchemy or SQLAlchemy: Select row with most recent date per user I need to print one row for each different user that has the highest id, so this example table would produce the following output: id user time io 1 9 1370931202 out 2 9 1370931664 out 3 6 1370932128 out 4 12 1370932128 out 5 12 1370933037 in output: id user time io 2 9 1370931664 out 3 6 1370932128 out 5 12 1370933037 in models.py class Example(db.Model): id = db.Column(db.Integer, primary_key=True) user = db.Column(db.String, default=None, nullable=True) time = db.Column(db.DateTime, default=datetime.utcnow, nullable=True) io = db.Column(db.String, default=None, nullable=True) my query does not find the correct row for each user: result = Example.query.sort_by(Example.id.desc()).group_by(Example.user) Is there any way to fix my query or translate the SQL solution to Flask-SQLAlchemy, Thanks.
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/85150671
linked to: http://stackoverflow.com/q/17038193
has comment: http://stackoverflow.com/comment/85134640
score: 0
tagged with: flask-sqlalchemy
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Select row with most recent date per user using Flask-SQLALchemy

http://stackoverflow.com/a/49018622
score: 1
accepted answer of: http://stackoverflow.com/q/49018512
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49018512
has comment: http://stackoverflow.com/comment/85081176
type: Answer
upvote count: 1
has body: An input field's value is stored as plain text, therefore you cannot include HTML (i.e. a link) and expect the HTML to be parsed and functioning. You could simulate this behavior with JavaScript, however I would recommend against it. (You would add a click listener, your function would pull the value of the field, see if it is a valid URL, and then open up the location.) I'm not going to write the code for this because it would be a terrible user experience. The standard behavior for an input field is that you click on it to edit the text. This is an assumption your users have, and they would therefore (a) not think to click on it because they don't expect it to be a link, and (b) click in it if they wanted to edit the text, only to be redirected and unable to edit the text. Alternatively, you could add a small button next to the input, i.e. 'Open' or 'Test' or an external link icon.

http://stackoverflow.com/comment/85209869
type: QuestionComment
has text: (Aside: the community has discussed [home-made tags in titles](https://meta.stackoverflow.com/questions/253028/why-is-removing-tags-from-the-title-suggested-so-often), and has decided that titles are better as natural English. Use the tag system for tags. Thank you).
comment on: http://stackoverflow.com/q/49102304
score: 0
type: Comment

http://stackoverflow.com/a/52976331
answers question: http://stackoverflow.com/q/49018227
has body: Install the first two packages sudo apt-get install libcurl4-openssl-dev python -m pip install pybind11 These are optional sudo apt install libgmp-dev libmpfr-dev libmpc-dev sudo apt install libssl-dev sudo apt-get install unixodbc unixodbc-dev
score: 0
type: Answer

http://stackoverflow.com/a/49229174
has comment: http://stackoverflow.com/comment/93512117
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49019189
has body: Another solution is to use tensorflow's matrix multiplication functions. Once GPU-enabled tensorflow is up and running, these work out-of-the-box. After installing CUDA and tensorflow-gpu (a couple of involved but straightforward tutorials are here and here), you can use tensorflow's SparseTensor class and sparse_tensor_dense_matmul function as follows: import numpy as np import tensorflow as tf from tensorflow.python.client import device_lib from time import time Make sure GPU is detected: gpus = [x.name for x in device_lib.list_local_devices() if x.device_type == 'GPU'] print('GPU DEVICES:\n {}'.format(gpus)) Output: GPU DEVICES: ['/device:GPU:0'] Benchmarks: from scipy.sparse import csr_matrix ITERS = 30 N = 20000 P = 0.1 # matrix density Using scipy: np.random.seed(0) a_dense = np.random.rand(N, N) a_dense[a_dense &gt; P] = 0 a_sparse = csr_matrix(a_dense) b = np.random.rand(N) tic = time() for ii in range(ITERS): c = a_sparse.dot(b) toc = time() elapsed = toc - tic print('Scipy spmv product took {} seconds per iteration.'.format(elapsed/ITERS)) Output: Scipy spmv product took 0.06693172454833984 seconds per iteration. Using GPU-enabled tensorflow: with tf.device('/device:GPU:0'): np.random.seed(0) a_dense = np.random.rand(N, N) a_dense[a_dense &gt; P] = 0 indices = np.transpose(a_dense.nonzero()) values = a_dense[indices[:, 0], indices[:, 1]] dense_shape = a_dense.shape a_sparse = tf.SparseTensor(indices, values, dense_shape) b = tf.constant(np.random.rand(N, 1)) tic = time() for ii in range(ITERS): c = tf.sparse_tensor_dense_matmul(a_sparse, b) toc = time() elapsed = toc - tic print('GPU spmv product took {} seconds per iteration.'.format(elapsed/ITERS)) Output: GPU spmv product took 0.0011811971664428711 seconds per iteration. Quite a nice speed-up, it turns out.
downvote count: 0

http://stackoverflow.com/comment/85036704
type: Comment
has text: @Saurabh there are many ways to do it, for instance with [skimage.transform.resize`](http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.resize)
score: 1
comment on: http://stackoverflow.com/q/49015697
type: QuestionComment

http://stackoverflow.com/comment/85099654
type: Comment
comment on: http://stackoverflow.com/a/49046649
type: AnswerComment
score: 0
has text: Using your textblob_de generates: **ValueError: need more than 1 value to unpack** ---> 62 w, tag, phrase, role, lemma = t.split('/')

http://stackoverflow.com/q/48997007
has answer: http://stackoverflow.com/a/48997070
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84999452
type: Question
score: 13
upvote count: 15
has title: Check for string in "response.content" raising "TypeError: a bytes-like object is required, not 'str'"
accepted answer: http://stackoverflow.com/a/48997070
has answer: http://stackoverflow.com/a/48997088
tagged with: string
has answer: http://stackoverflow.com/a/48997087
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48997088
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48997065
has body: I am trying to see if a sentence is present in the response back from a request. import requests r = requests.get('https://www.eventbrite.co.uk/o/piers-test-16613670281') text = 'Sorry, there are no upcoming events' if text in r.content: print('No Upcoming Events') I am getting the following error: TypeError: a bytes-like object is required, not 'str' I am not quite sure why this occurring and what the solution would be.
downvote count: 2

django-generic-views
type: Tag
tags question: http://stackoverflow.com/q/49055570
tag name: django-generic-views

http://stackoverflow.com/a/49043984
upvote count: 2
has body: intModifiedUser is an instance of AppUser. You should not set the foreign key identifier directly. Use to get the object from AppUser Instance intModifiedUser = AppUser.objects.get(id=1) country_details = Country(values, intModifiedUser = intModifiedUser)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49027382
answers question: http://stackoverflow.com/q/49027382
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/85127096
has text: Try `df['day'] = pd.to_numeric(df['day'])`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49059794

http://stackoverflow.com/q/49097030
has comment: http://stackoverflow.com/comment/85199222
tagged with: class
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49097209
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49097209
has body: I am trying to learn more about classes and objects in Python and the following is an example given in a tutorial. In the below code I am using: class Employee(object): 'common base clase for all employee' empCount = 0 def __init__(self, name, surname, pay): self.name = name self.surname = surname self.pay = pay Employee.empCount += 1 def displayCount(self): print('Total employee {}'.format(Employee.empCount)) def displayEmployee(self): print('Name: ', self.name, ', Surname: ', self.surname, ', Pay: ', self.pay) def summPay(self): pass I have passed to that class 2 objects, emp1 and emp2 emp1 = Employee('Federico', 'Olivieri', '5000') emp2 = Employee('Anonymous', 'Friend', '6500') What I want is to create another method summPay under the Employee class to make the sum of all salary. I know I could try to use a local variable and increment the variable as for empCount but I was wondering if there is a more elegant way to do it.
type: Question
has title: How make a summ of 2 attributes in a class
has comment: http://stackoverflow.com/comment/85199287

http://stackoverflow.com/q/49111000
linked to: http://stackoverflow.com/q/9692962
has comment: http://stackoverflow.com/comment/85229083
tagged with: python
accepted answer: http://stackoverflow.com/a/49119195
type: AnsweredQuestion
type: Question
has body: I'm trying to split out my models into a separate file as it's getting too large to manage. I've followed this but I am getting a NameError despite having run db.create_all(): NameError: name 'importsTable' is not defined # stack_app.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from stack_dbmodels import db from stack_dbmodels import importsTable from datetime import datetime app = Flask(__name__) app.secret_key = 'secretsquirrel' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stack_newAppCsv.db' db.init_app(app) @app.route('/', methods=['GET']) def stack(): username = "username" new_user = importsTable(username) db.session.add(new_user) db.session.commit() return "Done!" if __name__ == "__main__": app.run(debug = True, port=8080) My models file: # stack_dbmodels.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class importsTable(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80)) def __init__(self, username): self.username = username def __repr__(self): return '&lt;Import {0}&gt;'.format(self.username)
score: 0
has comment: http://stackoverflow.com/comment/85227527
answer count: 1
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/85229325
has answer: http://stackoverflow.com/a/49119195
has title: Why do I get a NameError when importing external DB models into my Flask App?
has comment: http://stackoverflow.com/comment/85228049

http://stackoverflow.com/comment/85171677
comment on: http://stackoverflow.com/q/49071592
score: 0
type: QuestionComment
type: Comment
has text: Thanks, could you elaborate? Sounds like a useful approach.

xpath
tags question: http://stackoverflow.com/q/49046889
tags question: http://stackoverflow.com/q/48996872
tag name: xpath
tags question: http://stackoverflow.com/q/49061657
tags question: http://stackoverflow.com/q/49105291
tags question: http://stackoverflow.com/q/49059592
tags question: http://stackoverflow.com/q/48982959
tags question: http://stackoverflow.com/q/49082933
tags question: http://stackoverflow.com/q/49033540
tags question: http://stackoverflow.com/q/49031703
tags question: http://stackoverflow.com/q/49056755
tags question: http://stackoverflow.com/q/49027000
type: Tag
tags question: http://stackoverflow.com/q/48989333

http://stackoverflow.com/comment/84935962
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48964998
has text: You should read the error message. It will be clear that the problem happens before you even get to the if statement
type: Comment

http://stackoverflow.com/a/49006462
type: Answer
has comment: http://stackoverflow.com/comment/85017390
downvote count: 3
answers question: http://stackoverflow.com/q/49006319
has body: I think you are looking for How to remove specific element in an array using python. Let me know if this is what you are looking for. Alternatively provide us a sample of input and output so we can play with your code. Update: Adding sample of code. Sample of code: #!/usr/bin/env python mainArray = [1, 2, 3, 4, 5, 6] arrayRemove = [1, 3, 6] mainArray = [e for e in mainArray if e not in arrayRemove] print(mainArray)
upvote count: 0
has comment: http://stackoverflow.com/comment/85017491
has comment: http://stackoverflow.com/comment/85018082
score: -3

http://stackoverflow.com/q/49108738
tagged with: python-3.4
score: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-3.x
has body: i have following XML File: <xml_connection_file xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mcf.xsd"> 1.0.0 <connection_group> 1 <connected_to> A B </connected_to> </connection_group> </xml_connection_file> i wish to add a comment in the main node(xml_connection_file). i have written following code in python3 but the error is appearing saying 'lxml.etree._ElementTree' has no attribute 'insert'. from lxml import etree from ansa import utils my_selected_file = utils.SelectOpenFile(0, 'xml files (*.mcf)') tree = etree.parse(my_selected_file[0]) comment = etree.Comment('my comments') tree.insert(1,comment) tree.write('new_file.mcf') Can anyone can tell me what am i doing wrong? thanks in advane!
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49130932
has title: Adding a comment to existing XML File using Python 3
type: Question
tagged with: xml-parsing
answer count: 1

http://stackoverflow.com/q/49062469
linked to: http://stackoverflow.com/q/46878999
upvote count: 3
has comment: http://stackoverflow.com/comment/85130960
has answer: http://stackoverflow.com/a/49063101
accepted answer: http://stackoverflow.com/a/49063101
downvote count: 1
tagged with: python
has body: I want to scrape a website's amount of likes. Using BeautifulSoup, this is what I got so far: user = 'LazadaMalaysia' url = 'https://www.facebook.com/'+ user response = requests.get(url) soup = BeautifulSoup(response.content,'lxml') f = soup.find('div', attrs={'class': '_4bl9'}) The output I receive for f is as follows: Bahagian-bahagian pada halaman ini Bantuan Kebolehcapaian I used the code from this link: How do I scrape the about section of a Facebook page? Unfortunately, it does not work and I cannot wrap my head around why this is the case. Here is the part I want to scrape:
possible better answer: http://stackoverflow.com/a/54262082
has title: Scrape Facebook likes
has answer: http://stackoverflow.com/a/54262082
tagged with: facebook
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/85132684
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85130764
has comment: http://stackoverflow.com/comment/85130895
has comment: http://stackoverflow.com/comment/85133956
type: Question
has comment: http://stackoverflow.com/comment/96148605
answer count: 2
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/a/49071724
has comment: http://stackoverflow.com/comment/85151260
score: 0
has body: The purpose of datasets API is to avoid feeding the values directly to session (because that causes the data to flow first to the client, then to a device). All examples I've seen that use datasets API also use estimator API, where you can provide different input functions for training and inference. def train_dataset(data_dir): """Returns a tf.data.Dataset yielding (image, label) pairs for training.""" data = input_data.read_data_sets(data_dir, one_hot=True).train return tf.data.Dataset.from_tensor_slices((data.images, data.labels)) def infer_dataset(data_dir): """Returns a tf.data.Dataset yielding images for inference.""" data = input_data.read_data_sets(data_dir, one_hot=True).test return tf.data.Dataset.from_tensors((data.images,)) ... def train_input_fn(): dataset = train_dataset(FLAGS.data_dir) dataset = dataset.shuffle(buffer_size=50000).batch(1024).repeat(10) (images, labels) = dataset.make_one_shot_iterator().get_next() return (images, labels) mnist_classifier.train(input_fn=train_input_fn) ... def infer_input_fn(): return infer_dataset(FLAGS.data_dir).make_one_shot_iterator().get_next() mnist_classifier.predict(input_fn=infer_input_fn)
type: Answer
has comment: http://stackoverflow.com/comment/85151362
answers question: http://stackoverflow.com/q/49071212

http://stackoverflow.com/q/49005228
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/55685210
has comment: http://stackoverflow.com/comment/85015095
score: 0
has answer: http://stackoverflow.com/a/49005386
has comment: http://stackoverflow.com/comment/85015031
upvote count: 1
downvote count: 1
has title: flake8 is too strict and yapf is too low
accepted answer: http://stackoverflow.com/a/49005386
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85015093
has body: I use vscode open my .py file. And then I see too many errors alert by flake8 almost cross the whole file. And most of them is about whitespaces. I use yapf to format the code but the code is really not changed . It seems that flake8 is too strict and yapf is too simple. Config the yapf to solve the whitespaces errors or config flake8 to ignore these errors? Which is the common way? My vscode setting: "python.linting.flake8Enabled": true, "python.formatting.provider": "yapf",
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/55685210

http://stackoverflow.com/a/48971522
has body: If you are using pyspark then I would suggest you to go with sparkContext's wholeTextFiles function to read the file, since your file needs to be read as whole text for parsing appropriately. After reading it using wholeTextFiles, you should parse by replacing end of line characters by , and do some additional formattings so that whole text can be broken down into groups of eight strings. import re rdd = sc.wholeTextFiles("path to your csv file")\ .map(lambda x: re.sub(r'(?!(([^"]*"){2})*[^"]*$),', ' ', x[1].replace("\r\n", ",").replace(",,", ",")).split(","))\ .flatMap(lambda x: [x[k:k+8] for k in range(0, len(x), 8)]) You should get output as [u'playerID', u'yearID', u'gameNum', u'gameName', u'teamName', u'lgID', u'GP', u'startingPos'] [u'gomezle01', u'1933', u'1', u'Cricket', u'Team1', u'NYA', u'AL', u'1'] [u'ferreri01', u'1933', u'2', u'Hockey', u'"This is Team2"', u'BOS', u'AL', u'1'] [u'gehrilo01', u'1933', u'3', u'"Game name is Cricket"', u'Team3', u'NYA', u'AL', u'1'] [u'gehrich01', u'1933', u'4', u'Hockey', u'"Here it is Team4"', u'DET', u'AL', u'1'] [u'dykesji01', u'1933', u'5', u'"Game name is Hockey"', u'"Team name Team5"', u'CHA', u'AL', u'1'] If you would like to convert all the array rdd rows into strings of rows then you can add .map(lambda x: ", ".join(x)) and you should get playerID, yearID, gameNum, gameName, teamName, lgID, GP, startingPos gomezle01, 1933, 1, Cricket, Team1, NYA, AL, 1 ferreri01, 1933, 2, Hockey, "This is Team2", BOS, AL, 1 gehrilo01, 1933, 3, "Game name is Cricket", Team3, NYA, AL, 1 gehrich01, 1933, 4, Hockey, "Here it is Team4", DET, AL, 1 dykesji01, 1933, 5, "Game name is Hockey", "Team name Team5", CHA, AL, 1
upvote count: 3
has comment: http://stackoverflow.com/comment/84968895
has comment: http://stackoverflow.com/comment/85018476
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84968859
accepted answer of: http://stackoverflow.com/q/48970822
has comment: http://stackoverflow.com/comment/84968823
has comment: http://stackoverflow.com/comment/84968952
answers question: http://stackoverflow.com/q/48970822
has comment: http://stackoverflow.com/comment/85018544
has comment: http://stackoverflow.com/comment/133156813
has comment: http://stackoverflow.com/comment/85018352
type: Answer
has comment: http://stackoverflow.com/comment/85018066
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85016996
has comment: http://stackoverflow.com/comment/85018463
has comment: http://stackoverflow.com/comment/85018569

http://stackoverflow.com/comment/84951916
type: AnswerComment
comment on: http://stackoverflow.com/a/48973404
type: Comment
score: 1
has text: Yes, will do it. Basically most of the issues concerning this are happening because of badly assigned paths. But that's just a generalization.

http://stackoverflow.com/q/49120232
has comment: http://stackoverflow.com/comment/85246983
has title: Add a datetime column to multiple dataframes in Pandas
score: 0
has answer: http://stackoverflow.com/a/49121781
type: Question
has body: I'm trying to loop through a list of dataframes and append a datetime column to each. I've tried the following to no avail: dfs = ['nov22_2017', 'nov29_2017', 'dec06_2017','dec13_2017', 'dec20_2017', 'dec27_2017', 'jan03_2018', 'jan10_2018'] sheets = ['11.22.17', '11.29.17', '12.6.17', '12.13', '12.20', '12.27', '1.3.18', '1.10.18'] dates = ['2017-11-22', '2017-11-29', '2017-1-06', '2017-12-13', '2017-12-20', '2017-12-27', '2018-01-03', '2018-01-10'] # create a list of datetimes datetimes = [pd.to_datetime(date) for date in dates] # assign each df to a variable dfs = [nrc_xl.parse(sheet, usecols = 10) for sheet in sheets] # assign datetime columns for index, df in enumerate(dfs): df['date'] = datetimes[index] The for loop doesn't modify the dataframes in the list. How do I accomplish this programmatically without having to create and assign a column for each dataframe? EDIT: I fixed it. sheets = ['11.22.17', '11.29.17', '12.6.17', '12.13', '12.20', '12.27', '1.3.18', '1.10.18'] # assign dfs to variables [nov22_2017, nov29_2017, dec06_2017, dec13_2017, dec20_2017, dec27_2017, jan03_2018, jan10_2018] = [nrc_xl.parse(sheet, usecols = 10) for sheet in sheets] dfs = [nov22_2017, nov29_2017, dec06_2017, dec13_2017, dec20_2017, dec27_2017, jan03_2018, jan10_2018] # create a list of datetimes dates = ['2017-11-22', '2017-11-29', '2017-1-06', '2017-12-13', '2017-12-20', '2017-12-27', '2018-01-03', '2018-01-10'] datetimes = [pd.to_datetime(date) for date in dates] # assign datetime columns for index, df in enumerate(dfs): df['date'] = datetimes[index]
tagged with: dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/85247551
answer count: 1
has comment: http://stackoverflow.com/comment/85246466
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85246766
tagged with: python

http://stackoverflow.com/comment/85235136
has text: @Aran-Fey BINGO! If you put that as the answer I'll mark it solved.
comment on: http://stackoverflow.com/q/49114899
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48984325
score: 3
tagged with: xml-parsing
downvote count: 0
has title: lxml.etree.XMLSyntaxError: internal error: Huge input lookup
linked to: http://stackoverflow.com/q/11850345
favorite count: 0
has comment: http://stackoverflow.com/comment/84973452
tagged with: lxml
has comment: http://stackoverflow.com/comment/84973752
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has body: I'm trying to parse a large xml file (~500 MB) with python lxml library, the iterparse, using: context = etree.iterparse('large-file.xml') for event, element in context: # do some stuff element.clear() but it returns the following error: Traceback (most recent call last): File "test.py", line 176, in &lt;module&gt; test_parser() File "test.py", line 121, in test_parser for event, element in context: File "src/lxml/iterparse.pxi", line 208, in lxml.etree.iterparse.__next__ (src/lxml/etree.c:155963) File "src/lxml/iterparse.pxi", line 193, in lxml.etree.iterparse.__next__ (src/lxml/etree.c:155671) File "src/lxml/iterparse.pxi", line 228, in lxml.etree.iterparse._read_more_events (src/lxml/etree.c:156298) File "src/lxml/parser.pxi", line 1362, in lxml.etree._FeedParser.feed (src/lxml/etree.c:116552) File "src/lxml/parser.pxi", line 589, in lxml.etree._ParserContext._handleParseResult (src/lxml/etree.c:107619) File "src/lxml/parser.pxi", line 598, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/etree.c:107738) File "src/lxml/parser.pxi", line 709, in lxml.etree._handleParseResult (src/lxml/etree.c:109447) File "src/lxml/parser.pxi", line 638, in lxml.etree._raiseParseError (src/lxml/etree.c:108301) File "large-file.xml", line 20593 lxml.etree.XMLSyntaxError: internal error: Huge input lookup, line 20593, column 199
answer count: 0
upvote count: 3
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/85274714
has text: can you please post a gist of your configs @gallocedrone ?
score: 1
comment on: http://stackoverflow.com/a/49069479
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49101151
upvote count: 1
has body: x = [5,5,5,5,6,7,87,8,9,10] for c in x: if c == 5: print('5') else: print('no') while i==5 is always True because the value of i never changes inside the body of the for loop.
answers question: http://stackoverflow.com/q/49101016
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49101016
score: 1

http://stackoverflow.com/a/49109777
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49108378
type: Answer
upvote count: 1
has body: for generating time ranges use pandas : import pandas as pd my_ranges = pd.date_range('2015-07-19', '2015-07-20', freq='5S') This example will output: In []: my_ranges Out[]: DatetimeIndex(['2015-07-19 00:00:00', '2015-07-19 00:00:05', '2015-07-19 00:00:10', '2015-07-19 00:00:15', '2015-07-19 00:00:20', '2015-07-19 00:00:25', '2015-07-19 00:00:30', '2015-07-19 00:00:35', '2015-07-19 00:00:40', '2015-07-19 00:00:45', ... '2015-07-19 23:59:15', '2015-07-19 23:59:20', '2015-07-19 23:59:25', '2015-07-19 23:59:30', '2015-07-19 23:59:35', '2015-07-19 23:59:40', '2015-07-19 23:59:45', '2015-07-19 23:59:50', '2015-07-19 23:59:55', '2015-07-20 00:00:00'], dtype='datetime64[ns]', length=17281, freq='5S') which is accesible by index and sliceable by all of pandas methods in order to extract the parallel ranges in your data set.

http://stackoverflow.com/q/49037919
upvote count: 1
has body: I am trying to compile a Fortran 90 file with f2py, to use in a Python module. The file is composed of two subroutines. I can compile the file, using gfortran ljlib3.f90 in the command window, but I get errors when trying to compile the subroutine with f2py. I am using Python(x,y) on Win 10 (Python 2.7.10) and Mingw-w64 (all properly installed). It's difficult because this is someone else's code from the tutorial, where in my case all works fine until almost the end of the compiling (when comparing with the tutorial). Here are the subroutines in the file ljlib3.f90: subroutine EnergyForces(Pos, L, rc, PEnergy, Forces, Dim, NAtom) implicit none integer, intent(in) :: Dim, NAtom real(8), intent(in), dimension(0:NAtom-1, 0:Dim-1) :: Pos real(8), intent(in) :: L, rc real(8), intent(out) :: PEnergy real(8), intent(inout), dimension(0:NAtom-1, 0:Dim-1) :: Forces !f2py intent(in,out) :: Forces real(8), dimension(Dim) :: rij, Fij, Posi real(8) :: d2, id2, id6, id12 real(8) :: rc2, Shift integer :: i, j PEnergy = 0. Forces = 0. Shift = -4. * (rc**(-12) - rc**(-6)) rc2 = rc * rc do i = 0, NAtom - 1 !store Pos(i,:) in a temporary array for faster access in j loop Posi = Pos(i,:) do j = i + 1, NAtom - 1 rij = Pos(j,:) - Posi rij = rij - L * dnint(rij / L) !compute only the squared distance and compare to squared cut d2 = sum(rij * rij) if (d2 &gt; rc2) then cycle end if id2 = 1. / d2 !inverse squared distance id6 = id2 * id2 * id2 !inverse sixth distance id12 = id6 * id6 !inverse twelvth distance PEnergy = PEnergy + 4. * (id12 - id6) + Shift Fij = rij * ((-48. * id12 + 24. * id6) * id2) Forces(i,:) = Forces(i,:) + Fij Forces(j,:) = Forces(j,:) - Fij enddo enddo end subroutine subroutine VVIntegrate(Pos, Vel, Accel, L, CutSq, dt, KEnergy, PEnergy, Dim, NAtom) implicit none integer, intent(in) :: Dim, NAtom real(8), intent(in) :: L, CutSq, dt real(8), intent(inout), dimension(0:NAtom-1, 0:Dim-1) :: Pos, Vel, Accel !f2py intent(in,out) :: Pos, Vel, Accel real(8), intent(out) :: KE…
has comment: http://stackoverflow.com/comment/85102048
score: 1
has comment: http://stackoverflow.com/comment/85106635
tagged with: f2py
has comment: http://stackoverflow.com/comment/85100719
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85105942
tagged with: mingw-w64
has comment: http://stackoverflow.com/comment/85105147
has answer: http://stackoverflow.com/a/58409516
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85081178
tagged with: python
has comment: http://stackoverflow.com/comment/85104993
linked to: http://stackoverflow.com/q/32555087
has title: undefined reference to `__imp_PyFloat_Type' using f2py on Windows 10
tagged with: fortran
type: UnansweredQuestion

http://stackoverflow.com/comment/85045471
has text: another crazy idea that `y` could be a matrix "`zip(y,g)`" so you will need estimator wrapper that cut first column, but scorer could both. [source](https://github.com/scikit-learn/scikit-learn/blob/d9c212297ec594a81ae768bec206565055878d99/sklearn/model_selection/_search.py#L569)
comment on: http://stackoverflow.com/q/49017257
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85246172
has text: Mm, i was able to put together something, i put what i did in my question. Thanks. Note, its still not perfect, close enough.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49117818

http://stackoverflow.com/a/49090700
has body: You can use np.fromfunction for this: modified_noise = np.fromfunction(lambda i, j: function(i, j), (size, size), dtype=float) This constructs an array by executing a function over each coordinate. Related: How can I use a range inside numpy.fromfunction?
upvote count: 2
answers question: http://stackoverflow.com/q/49090643
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85188507
score: 2

http://stackoverflow.com/comment/85235828
type: QuestionComment
has text: You provided a JSON example without any `'rain'` in it. That's not a very good example, because it is unclear what you are searching for. You could be looking for keys (`{"rain": ...}`, for substrings of keys (`{"rainfall": ...}`), for strings in values: (`{"precipitation": "rain"}`), substrings in values `{"precipitation": "Heavy rain"}`), or for all of the above. If looking for substrings, what should happen when it is part of a word, like `restraint`?
type: Comment
comment on: http://stackoverflow.com/q/49114995
score: 0

http://stackoverflow.com/a/49027380
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/49027271
has comment: http://stackoverflow.com/comment/85059344
has body: You can use &gt;&gt;&gt; ":".join(map(str, range(20,1,-3))) &gt;&gt;&gt; '20:17:14:11:8:5:2'
upvote count: 8
has comment: http://stackoverflow.com/comment/85059692
has comment: http://stackoverflow.com/comment/85059640
type: Answer

http://stackoverflow.com/q/49047902
type: Question
has title: Search for terms in file
has answer: http://stackoverflow.com/a/49048453
tagged with: search
score: 0
accepted answer: http://stackoverflow.com/a/49048453
answer count: 1
linked to: http://stackoverflow.com/q/4940032
has comment: http://stackoverflow.com/comment/85100255
has body: I am having problems with my script. I want to find some terms in different files, defined in a searchlist. However - it won't find those terms, even if they are definitely included in those files. I checked it. Am I missing something? path = '/mypath' for filename in glob.glob(os.path.join(path, '*.txt')): with open(filename) as infp: mylist = infp.read().splitlines() for word in mylist: searchlist = ["term1", "term2", "term3"] for i in searchlist: if i in word: print ('found') else: print ('not found')
has comment: http://stackoverflow.com/comment/85100161
tagged with: python
type: AnsweredQuestion
tagged with: file

http://stackoverflow.com/comment/85205420
has text: Sorry, will paste my code next time.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49096649
type: QuestionComment

http://stackoverflow.com/q/49084728
type: Question
score: 0
has answer: http://stackoverflow.com/a/49084729
has body: Using current User model in your serializers is easy: user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) but what if I have my own UserProfile model and I want to use current UserProfile in a serializer. Just doing CurrentUserDefault().profile does not work, of course because at this point this is an empty object.
answer count: 1
tagged with: django-rest-framework
has title: DRF: a way to use default UserProfile field in serializer?
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/49110120
has answer: http://stackoverflow.com/a/49110221
accepted answer: http://stackoverflow.com/a/49110221
type: Question
upvote count: 5
tagged with: sorting
score: 5
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/1517793
has title: Sorting twice in pandas
type: AnsweredQuestion
has body: I have a dataframe A that has three columns: 'id', 'value' and 'date'. I was doing a groupby by id, and noticed something strange: if I do two successive sorts for rows with a given id, first by value and then date, the order of operations affects the order of rows. Notice the order of rows with index 42915 and 42916: A.sort_values('value').sort_values('date')[A.sort_values('value').sort_values('date')['id'] == '0001249666'] id value date 42913 0001249666 113845.0 20130408 42914 0001249666 114597.0 20130430 42916 0001249666 125972.0 20140414 42915 0001249666 125971.0 20140414 42917 0001249666 136154.0 20150410 42918 0001249666 145551.0 20160407 42919 0001249666 152911.0 20170413 A[A['id'] == '0001249666'].sort_values('value').sort_values('date') id value date 42913 0001249666 113845.0 20130408 42914 0001249666 114597.0 20130430 42915 0001249666 125971.0 20140414 42916 0001249666 125972.0 20140414 42917 0001249666 136154.0 20150410 42918 0001249666 145551.0 20160407 42919 0001249666 152911.0 20170413 If I however use .sort_values with two arguments, the order doesn't matter. A.sort_values(['date','value'])[A.sort_values(['date','value'])['id'] == '0001249666'] id value date 42913 0001249666 113845.0 20130408 42914 0001249666 114597.0 20130430 42915 0001249666 125971.0 20140414 42916 0001249666 125972.0 20140414 42917 0001249666 136154.0 20150410 42918 0001249666 145551.0 20160407 42919 0001249666 152911.0 20170413 a[a['id'] == '0001249666'].sort_values(['date','value']) id value date 42913 0001249666 113845.0 20130408 42914 0001249666 114597.0 20130430 42915 0001249666 125971.0 20140414 42916 0001249666 125972.0 20140414 42917 0001249666 136154.0 20150410 42918 0001249666 145551.0 20160407 42919 0001249666 152911.0 20170413 Now I know that what I'm doing isn't the smartest way of doing what I want, but I am really interested in understanding what could explain this behaviour? What am I implicitly assuming when I don't understand this behaviour.

http://stackoverflow.com/a/48995877
type: Answer
answers question: http://stackoverflow.com/q/48995735
score: 0
has body: This occurs because you declared a constraint: unique_together = ('name', 'user') Just remove this constraint.

http://stackoverflow.com/q/49017178
upvote count: 24
type: AnsweredQuestion
tagged with: dataframe
score: 24
accepted answer: http://stackoverflow.com/a/49017309
has answer: http://stackoverflow.com/a/49017382
type: Question
has answer: http://stackoverflow.com/a/49017556
downvote count: 0
possible better answer: http://stackoverflow.com/a/49017382
answer count: 3
tagged with: pandas
has body: type(Table) pandas.core.frame.DataFrame Table ======= ======= ======= Column1 Column2 Column3 0 23 1 1 5 2 1 2 3 1 19 5 2 56 1 2 22 2 3 2 4 3 14 5 4 59 1 5 44 1 5 1 2 5 87 3 For anyone familliar with pandas how would I build a multivalue dictionary with the .groupby() method? I would like an output to resemble this format: { 0: [(23,1)] 1: [(5, 2), (2, 3), (19, 5)] # etc... } where Col1 values are represented as keys and the corresponding Col2 and Col3 are tuples packed into an array for each Col1 key. My syntax works for pooling only one column into the .groupby(): Table.groupby('Column1')['Column2'].apply(list).to_dict() # Result as expected { 0: [23], 1: [5, 2, 19], 2: [56, 22], 3: [2, 14], 4: [59], 5: [44, 1, 87] } However specifying multiple values for the indices results in returning column names for the value : Table.groupby('Column1')[('Column2', 'Column3')].apply(list).to_dict() # Result has column namespace as array value { 0: ['Column2', 'Column3'], 1: ['Column2', 'Column3'], 2: ['Column2', 'Column3'], 3: ['Column2', 'Column3'], 4: ['Column2', 'Column3'], 5: ['Column2', 'Column3'] } How would I return a list of tuples in the value array?
tagged with: python
tagged with: dictionary
tagged with: jupyter
favorite count: 0
has answer: http://stackoverflow.com/a/49017309
has title: Pandas DataFrame.groupby() to dictionary with multiple columns for value

http://stackoverflow.com/comment/84945411
has text: Error comes from the first line.
comment on: http://stackoverflow.com/q/48969969
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48992547
score: 1
has comment: http://stackoverflow.com/comment/84990664
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/84990103
upvote count: 1
has body: I expected isinstance function to return True only for types that exist in object's type mro tuple. But: &gt;&gt;&gt; isinstance(int(), numbers.Integral) True &gt;&gt;&gt; int.__mro__ (&lt;type 'int'&gt;, &lt;type 'object'&gt;) Why int.mro does not contain numbers.Integral?
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/8203336
has comment: http://stackoverflow.com/comment/84990223
has title: Why int.__mro__ doesn't contain numbers.Integral?
linked to: http://stackoverflow.com/q/8203336

http://stackoverflow.com/a/51493661
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49002399
score: 2
has body: First thing first: what you get is the expected behaviour. "shallow" copy means that you create a new copy of the object, so adding to list b will obviously NOT impact list a. I just want to understand difference between deepcopy and shallow copy. Because shallowcopy and deepcopy is behaving in same manner In your example, you are doing a shallow copy of mutable container (a list) containing immutable objects (integers), so the result is indeed the same. To find out the difference between shallow and deep copies you have to use a list containing mutable objects - dicts for example: &gt;&gt;&gt; import copy &gt;&gt;&gt; a = [{"name":"a"}, {"name":"b"}] &gt;&gt;&gt; b = copy.copy(a) &gt;&gt;&gt; a[0]["age"] = 42 &gt;&gt;&gt; a [{'age': 42, 'name': 'a'}, {'name': 'b'}] &gt;&gt;&gt; b [{'age': 42, 'name': 'a'}, {'name': 'b'}] &gt;&gt;&gt; a.append({"bar":"baaz"}) &gt;&gt;&gt; a [{'age': 42, 'name': 'a'}, {'name': 'b'}, {'bar': 'baaz'}] &gt;&gt;&gt; b [{'age': 42, 'name': 'a'}, {'name': 'b'}] &gt;&gt;&gt; id(a) 139833628392264 &gt;&gt;&gt; id(b) 139833599561240 &gt;&gt;&gt; [id(x) for x in a] [139833628091568, 139833599520392, 139833599544128] &gt;&gt;&gt; [id(x) for x in b] [139833628091568, 139833599520392] As you can see, a and b are distinct objects - they have different ids, and adding to one doesn't add to the other - but they (initially at least) share the same objects (just after the copy a[0] and a[1] are pointing to the same objects as b[0] and b[1]). Now if you do a deep copy: &gt;&gt;&gt; c = copy.deepcopy(a) &gt;&gt;&gt; c [{'age': 42, 'name': 'a'}, {'name': 'b'}, {'bar': 'baaz'}] &gt;&gt;&gt; [id(x) for x in c] [139833599544408, 139833599594576, 139833599596256] &gt;&gt;&gt; c[0]["age"] = 84 &gt;&gt;&gt; c [{'age': 84, 'name': 'a'}, {'name': 'b'}, {'bar': 'baaz'}] &gt;&gt;&gt; a [{'age': 42, 'name': 'a'}, {'name': 'b'}, {'bar': 'baaz'}] &gt;&gt;&gt; b [{'age': 42, 'name': 'a'}, {'name': 'b'}] &gt;&gt;&gt; you can see that c elements are themselves copies (d…
upvote count: 2

http://stackoverflow.com/comment/84939809
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48966810
type: AnswerComment
has text: i tried what your code but it give me this error i+=1 ^ IndentationError: unindent does not match any outer indentation level

http://stackoverflow.com/q/49109150
answer count: 3
has answer: http://stackoverflow.com/a/49109444
has comment: http://stackoverflow.com/comment/85223300
favorite count: 0
has comment: http://stackoverflow.com/comment/85224099
has title: How to split a string into list and combine two known token into one in python?
has comment: http://stackoverflow.com/comment/85223717
tagged with: python
has body: For a given string like: "Today is a bright sunny day in New York" I want to make my list to be: ['Today','is','a','bright','sunny','day','in','New York'] Another example: "This is a hello world program" The list be: ['This', 'is', 'a', 'hello world', 'program'] For every given string S, we have the entities E which needs to be kept together. The first example had entity E to be "New", "York" and the second example had entity to be "hello","world". I have tried to get it done via regex but I am unsuccessful in splitting by spaces and merging two entities. Example: regex = "(navy blue)|[a-zA-Z0-9]*" match = re.findall(regex, "the sky looks navy blue.",re.IGNORECASE) print match Output: ['', '', '', '', '', '', 'navy blue', '', '']
possible better answer: http://stackoverflow.com/a/49109217
tagged with: regex
has comment: http://stackoverflow.com/comment/85224063
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85223219
tagged with: tokenize
downvote count: 1
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/49109358
has comment: http://stackoverflow.com/comment/85224330
accepted answer: http://stackoverflow.com/a/49109358
has answer: http://stackoverflow.com/a/49109217
upvote count: 3

http://stackoverflow.com/a/48967597
has comment: http://stackoverflow.com/comment/84941055
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48967540
answers question: http://stackoverflow.com/q/48967540
has body: You can use the following function def get_pwm(angle): return (angle/18.0) + 2.5 This function will give you the required PWM given an angle. Your question tells that for 0 degrees -&gt; PWM is 2.5, 90 degrees -&gt; PWM is 7.5 and 180 degrees -&gt; PWM is 12.5. This shows that the PWM and angle have a linear relation. However, the starting value of PWM is 2.5 when angle is 0 degrees.
upvote count: 1
type: AcceptedAnswer

http
tags question: http://stackoverflow.com/q/49013757
tags question: http://stackoverflow.com/q/49077826
tags question: http://stackoverflow.com/q/49003394
tag name: http
tags question: http://stackoverflow.com/q/49019415
tags question: http://stackoverflow.com/q/49058831
tags question: http://stackoverflow.com/q/49112365
tags question: http://stackoverflow.com/q/49025279
type: Tag
tags question: http://stackoverflow.com/q/49017670
tags question: http://stackoverflow.com/q/49039241
tags question: http://stackoverflow.com/q/48981048
tags question: http://stackoverflow.com/q/49071377
tags question: http://stackoverflow.com/q/49118449

http://stackoverflow.com/comment/85039795
type: Comment
type: QuestionComment
has text: @PatrickArtner A typo, was meant to be data
comment on: http://stackoverflow.com/q/49017230
score: 0

http://stackoverflow.com/comment/85036349
comment on: http://stackoverflow.com/q/49015697
has text: I am trying to implement a perceptron model for image classification,in which each image is of different size,for eg:1.)(3,1200,1600) 2.)(3,400,400)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48991137
answers question: http://stackoverflow.com/q/48979219
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/108747689
downvote count: 0
type: Answer
upvote count: 6
has body: To combine the two images you can make use of numpy slicing to select the portion of the background image where you want to blend the foreground, then insert the newly blended portion in your background again. import cv def combine_two_color_images(image1, image2): foreground, background = image1.copy(), image2.copy() foreground_height = foreground.shape[0] foreground_width = foreground.shape[1] alpha =0.5 # do composite on the upper-left corner of the background image. blended_portion = cv.addWeighted(foreground, alpha, background[:foreground_height,:foreground_width,:], 1 - alpha, 0, background) background[:foreground_height,:foreground_width,:] = blended_portion cv.imshow('composited image', background) cv.waitKey(10000) edit: To place the foreground at a specified location you use numpy indexing as before. Numpy indexing is very powerful and you will find it useful on many occasions. I linked the documentation above. Is really worth to take a look at. def combine_two_color_images_with_anchor(image1, image2, anchor_y, anchor_x): foreground, background = image1.copy(), image2.copy() # Check if the foreground is inbound with the new coordinates and raise an error if out of bounds background_height = background.shape[0] background_width = background.shape[1] foreground_height = foreground.shape[0] foreground_width = foreground.shape[1] if foreground_height+anchor_y > background_height or foreground_width+anchor_x > background_width: raise ValueError("The foreground image exceeds the background boundaries at this location") alpha =0.5 # do composite at specified location start_y = anchor_y start_x = anchor_x end_y = anchor_y+foreground_height end_x = anchor_x+foreground_width blended_portion = cv.addWeighted(foreground, alpha, background[start_y:end_y, start_x:end_x,:], 1 - alpha, 0, background) background[start_y:end_y, start_x:end_x,:] = blended_portion cv.imshow('composited image', background) cv.waitKey(10000)
score: 6
accepted answer of: http://stackoverflow.com/q/48979219

http://stackoverflow.com/comment/85159132
score: 0
has text: Don't do the chdir: you should make sure that the Instant Client is in your PATH environment variable before you run python. Also make sure you have the correct VS Redistributable - the Instant Client download page has the details. Here are the installation instructions http://cx-oracle.readthedocs.io/en/latest/installation.html#installing-cx-oracle-on-windows
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49060336

http://stackoverflow.com/q/49058919
linked to: http://stackoverflow.com/q/23294658
accepted answer: http://stackoverflow.com/a/49059006
has comment: http://stackoverflow.com/comment/85123791
tagged with: python
has comment: http://stackoverflow.com/comment/85122911
type: AnsweredQuestion
tagged with: conditional-statements
score: 1
has comment: http://stackoverflow.com/comment/85139131
downvote count: 3
has answer: http://stackoverflow.com/a/49059006
has comment: http://stackoverflow.com/comment/85123242
has comment: http://stackoverflow.com/comment/85122917
type: Question
upvote count: 4
tagged with: while-loop
answer count: 1
has title: Python While Loop Not Returning Desired Value
has comment: http://stackoverflow.com/comment/85122896
favorite count: 0
tagged with: python-3.x
has body: Just recently started learning python and ran into a bit of an odd problem. I've created this function to ensure that the number entered by a user is larger than zero: def numcheck(value,variable): while value &lt;= 0: print('The' +str(variable) + 'must be greater than zero! ') value = float(input('Please enter a positive number for' +str(variable)+ \ 'and press enter. ')) return value The function is used within a main function as follows: def main(): length = float(input('What is the length of the block of cheese? ')) numcheck(length,' length of the block ' ) My problem is that the function successfully recognizes non-positive values, but when a new value is entered, the original number is still passed to the rest of the function. For example, if -10 is entered into length, I will be prompted to enter another value. If 15 is entered, the while loop will close but -10 will still pass from the function completely ruining the arithmetic that follows. I have spent several hours trying to remedy this with no success. I would appreciate any advice y'all have to offer. Thanks so much!
tagged with: return

http://stackoverflow.com/q/49043373
tagged with: sql
answer count: 1
has body: I am trying to insert data into a table that has already been created. The code does not throw any error but simply does not writes into the DB. I think there is problem with the timestamp, may be. If any of you could please have a look at the code and provide some pointers, that would be great. TIA!! Cheers import pyodbc import datetime import time def connect_db(): db = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=xxxxx\SQLEXPRESS;" "Database=test;" "Trusted_Connection=yes;" "uid=xxx;" "password=xyz") cursor = db.cursor() ts = time.time() timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') sql = "INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', %)" % (timestamp) cursor.execute(sql) db.commit() cursor.close() db.close()
favorite count: 0
score: -3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85091809
downvote count: 3
has comment: http://stackoverflow.com/comment/85091729
has answer: http://stackoverflow.com/a/49043479
has title: SQL insert into MS Server DB using Python not working
type: Question
accepted answer: http://stackoverflow.com/a/49043479
upvote count: 0
tagged with: sql-server
has comment: http://stackoverflow.com/comment/85091866

http://stackoverflow.com/comment/85059824
score: 0
type: Comment
type: AnswerComment
has text: I'm not sure which of the cases would be the desireable one for you. But if you want to specify what the desired output should be, there is for sure a solution, which I could add to the answer.
comment on: http://stackoverflow.com/a/49027753

http://stackoverflow.com/a/49075059
score: 14
downvote count: 0
has body: You can find the source code of that threading.Thread() constructor here (of cpython, the most common python implementation): def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() If you pass daemon=True into it, that will be put in kwargs, but as you can see in the code, nothing happens with it. So yes, you're correct, you'll have to set the daemon attribute after creating it (and before calling start(). There seems to be no option to set it directly when constructing the Timer.
type: Answer
answers question: http://stackoverflow.com/q/49074715
upvote count: 14
has comment: http://stackoverflow.com/comment/130744923
accepted answer of: http://stackoverflow.com/q/49074715
type: AcceptedAnswer

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/49055933
type: Tag

http://stackoverflow.com/q/49041689
has title: Tracing Canadian borders with a function. (longitude and latitude boundaries of Canada)
tagged with: python
type: AnsweredQuestion
tagged with: math
tagged with: geolocation
type: Question
has answer: http://stackoverflow.com/a/49042515
score: 0
accepted answer: http://stackoverflow.com/a/49042515
answer count: 1
tagged with: latitude-longitude
has body: I'm writing a python script that generates random addresses in Canada. To do this, I have to generate random tuples (longitude,latitude) that are within Canadian borders (not in the ocean). I figured that I can approximate the borders with small rectangles (just like in calculus). Which does the job, but it is not optimal/accurate. I couldn't find any academic paper/discussion on the web, maybe my searches did not contain the right keywords. Can you help me find the right resources or even answer this question? The programming part is fine, I just need the math! Thank you
tagged with: integral

http://stackoverflow.com/q/48988038
has comment: http://stackoverflow.com/comment/84981679
has body: I have array: arr = np.array([1,2,3,2,3,4,3,2,1,2,3,1,2,3,2,2,3,4,2,1]) print (arr) [1 2 3 2 3 4 3 2 1 2 3 1 2 3 2 2 3 4 2 1] I would like find this pattern and return booelan mask: pat = [1,2,3] N = len(pat) I use strides: #https://stackoverflow.com/q/7100242/2901002 def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) c = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) return c print (rolling_window(arr, N)) [[1 2 3] [2 3 2] [3 2 3] [2 3 4] [3 4 3] [4 3 2] [3 2 1] [2 1 2] [1 2 3] [2 3 1] [3 1 2] [1 2 3] [2 3 2] [3 2 2] [2 2 3] [2 3 4] [3 4 2] [4 2 1]] I find positions of first values only: b = np.all(rolling_window(arr, N) == pat, axis=1) c = np.mgrid[0:len(b)][b] print (c) [ 0 8 11] And positions another vals: d = [i for x in c for i in range(x, x+N)] print (d) [0, 1, 2, 8, 9, 10, 11, 12, 13] Last return mask by in1d: e = np.in1d(np.arange(len(arr)), d) print (e) [ True True True False False False False False True True True True True True False False False False False False] Verify mask: print (np.vstack((arr, e))) [[1 2 3 2 3 4 3 2 1 2 3 1 2 3 2 2 3 4 2 1] [1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0]] 1 2 3 1 2 3 1 2 3 I think my solution is a bit over-complicated. Is there some better, more pythonic solution?
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/48988860
has title: Find boolean mask by pattern
linked to: http://stackoverflow.com/q/16970982
downvote count: 1
tagged with: stride
has comment: http://stackoverflow.com/comment/84981039
type: Question
has comment: http://stackoverflow.com/comment/84980883
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84980999
linked to: http://stackoverflow.com/q/7100242
has comment: http://stackoverflow.com/comment/84981418
has comment: http://stackoverflow.com/comment/84981715
has comment: http://stackoverflow.com/comment/84980941
has answer: http://stackoverflow.com/a/48988860
tagged with: numpy
tagged with: boolean
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/84981471
linked to: http://stackoverflow.com/q/48710783
tagged with: arrays
possible better answer: http://stackoverflow.com/a/49002944
favorite count: 0
has answer: http://stackoverflow.com/a/49002944

http://stackoverflow.com/comment/84998501
has text: I have already converted both the table in `htmltable` format, can you help me with that how to paste it in mail body with one space distance.
type: AnswerComment
comment on: http://stackoverflow.com/a/48996369
score: 0
type: Comment

http://stackoverflow.com/q/49030448
favorite count: 0
accepted answer: http://stackoverflow.com/a/49031638
score: -3
tagged with: python
has title: Design choices for numpy, python
has answer: http://stackoverflow.com/a/49031638
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85088236
has body: Why does implementors of numpy in python decided to have shape for np.random.randn as comma separated ints but for np.zeros as tuple of shape? Please explain this design choice. Thanks
has comment: http://stackoverflow.com/comment/85067450
upvote count: 3
has comment: http://stackoverflow.com/comment/85071789
has comment: http://stackoverflow.com/comment/85065194
type: Question
tagged with: numpy
answer count: 1

http://stackoverflow.com/a/49076182
score: 0
type: Answer
has body: Yes, this can be done without using a function definition. Try this: wMean = 0 for i in range(N): ## Loop through all the weights wMean += (A[i] * B[i]) ## Multiply the weights by the result wMean /= sum(A) ## Divide the sum to get the Weighted Mean Of course, you could also define a function which multiplies two given numbers, and map() the lists using this function, but you've stated that you don't wish to use any functions.
answers question: http://stackoverflow.com/q/49076131

http://stackoverflow.com/a/48990045
has body: you are getting that weird print because you are not checking data from client. As a workaround you can check whether the data sent from client is empty or have value. If it have value print it and otherwise don't do anything. Please let me know if you need any code reference or something extra. if sentense: print sentense
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84984592
answers question: http://stackoverflow.com/q/48988855

http://stackoverflow.com/q/49061906
has answer: http://stackoverflow.com/a/49062098
tagged with: python
linked to: http://stackoverflow.com/q/46597013
score: 0
has body: I am working with some 3D (volumetric) data using Python, and for every tetrahedron, I have not only the vertices's coordinates but also a fourth dimension which is the value of some parameter for that tetrahedron volume. For example: # nodes coordinates that defines a tetrahedron volume: x = [0.0, 1.0, 0.0, 0.0] y = [0.0, 0.0, 1.0, 0.0] z = [0.0, 0.0, 0.0, 1.0] # Scaler value of the potential for the given volume: c = 100.0 I would like to plot a 3D volume (given by the nodes coordinates) filled with some solid color, which would represent the given value C. How could I do that in Python 3.6 using its plotting libraries?
tagged with: scipy
answer count: 1
accepted answer: http://stackoverflow.com/a/49062098
tagged with: matplotlib
has title: Plot and fill 3D volumes in Python
tagged with: numpy
type: AnsweredQuestion
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/85008588
comment on: http://stackoverflow.com/q/49001385
has text: I don't think this is caused by django version, this is the django-rest-framework.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49057646
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/49057790
has title: Python shows wrong gcc version
favorite count: 0
has answer: http://stackoverflow.com/a/49057790
tagged with: python
has comment: http://stackoverflow.com/comment/85120320
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49057795
tagged with: interpreter
has body: I updated gcc to v6 few weeks ago. Today i noticed that python2 and python3 both the interpreters were using gcc v5. Why does python interpreter show gcc v5 but I have gcc v6 installed? I am using xubuntu 16. Here is my terminal:
accepted answer: http://stackoverflow.com/a/49057795
has comment: http://stackoverflow.com/comment/85120193
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85119956
has comment: http://stackoverflow.com/comment/85120007
tagged with: gcc
score: 0

http://stackoverflow.com/comment/85196842
has text: I don't know why you close questions assuming I have not already checked other threads. I have. They didn't get me anywhere with what I'm doing wrong here in this line. Thanks for your patience and arrogance! I really appreciate it.
comment on: http://stackoverflow.com/q/49095596
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49036122
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: pyside2
upvote count: 1
has answer: http://stackoverflow.com/a/49036322
type: Question
tagged with: qcolordialog
has body: I'm having a problem with pyside2. I need to implement a color picker that, when I choose a color, visualize that color in a little square. I've done the color picker like this: color = QtWidgets.QColorDialog.getColor() but I don't know how to make a square (it should be a label?) and to colour it with the selected color.
has title: Color Picker and Visualizer with Pyside2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49036322
favorite count: 0

http://stackoverflow.com/comment/85212380
score: 1
has text: Perhaps [this](https://stackoverflow.com/questions/21129020/how-to-fix-unicodedecodeerror-ascii-codec-cant-decode-byte) solves your problem?
comment on: http://stackoverflow.com/q/49103602
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85042711
score: 0
has text: Hang on, got the whole file here, I put it into word pad instead
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49018087

http://stackoverflow.com/q/48993168
answer count: 1
upvote count: 0
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/48993366
has comment: http://stackoverflow.com/comment/84991518
favorite count: 0
has comment: http://stackoverflow.com/comment/84995245
has comment: http://stackoverflow.com/comment/84991522
type: Question
has title: Trying to use json load with txt file
tagged with: python
tagged with: text
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84991756
downvote count: 3
has body: import json f=open("99_jiayi.txt",'r',encoding = 'utf-8-sig') a=json.load(f) f.close() https://i.sstatic.net/vD3M5.png https://i.sstatic.net/QP0oW.png I tried to turn the text file into a list in order to analyze the data I used the "json load" and it worked on another file which is written in the same mode But when i want to use it on another file it comes out the error i searched google for a lot of time but still cant get the ans Hope someone can help me with this question i have some problem to express my thought with eng so if anyone cant understand what i am typing plz let me know tks!!

http://stackoverflow.com/comment/85169263
comment on: http://stackoverflow.com/a/49081326
has text: To add to this the [docs](https://docs.python.org/3/reference/datamodel.html#object.__iadd__) do say these methods attempt to do the operation in place and return the result.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49108742
has title: ModuleNotFoundError - Python 3.6
has comment: http://stackoverflow.com/comment/85222585
has comment: http://stackoverflow.com/comment/85223430
tagged with: python
has comment: http://stackoverflow.com/comment/85223176
tagged with: module
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/85223073
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/85223586
has comment: http://stackoverflow.com/comment/85223130
has comment: http://stackoverflow.com/comment/85223199
downvote count: 0
has body: I have read the documentation on what to do if you want the directories to be treated as packages: https://docs.python.org/3/tutorial/modules.html. i.e. one needs __init__.py files in such directories. I followed the instructions and created a folder structure that contains these files: Screenshot you are looking at has the structure on the left that reflects that of the documentation. On the right is the code (routes.py; you can see it as the last file in the folder structure on the left) that gives me the error: Traceback (most recent call last): File "routes.py", line 2, in &lt;module&gt; from app.static.python.sections_elements import * ModuleNotFoundError: No module named 'app' all of the __init__.py files are empty, except for the __init__.py in python folder. Which contains two lines of code: __all__ = ['sections_elements.py'] i.e. __all__ declaration and an empty line. Can you let me know what am I missing here? Why am I getting this error? ( I am running python routes.py)
favorite count: 0
has comment: http://stackoverflow.com/comment/85222450
has comment: http://stackoverflow.com/comment/85223211

http://stackoverflow.com/a/49059644
answers question: http://stackoverflow.com/q/49059594
downvote count: 0
has comment: http://stackoverflow.com/comment/85124378
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85124483
has body: IIUC..cumsum? df.x.cumsum() Out[864]: date 2017-07-30 1 2017-07-31 3 2017-08-01 6 2017-08-02 10 Name: x, dtype: int64 Updated n=2 s=n**(np.arange(len(df)))[::-1] df.x.rolling(window=len(df),min_periods=1).apply(lambda x : sum(x*s[-len(x):])) Out[894]: date 2017-07-30 1.0 2017-07-31 4.0 2017-08-01 11.0 2017-08-02 26.0 Name: x, dtype: float64

http://stackoverflow.com/q/49099313
favorite count: 0
linked to: http://stackoverflow.com/q/33239308
type: UnansweredQuestion
has body: I have the below flask code : from flask import Flask,request,jsonify import requests from werkzeug.exceptions import InternalServerError, NotFound import sys import json app = Flask(__name__) app.config['SECRET_KEY'] = "Secret!" class InvalidUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message rv['status_code'] = self.status_code return rv @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response @app.route('/test',methods=["GET","POST"]) def test(): url = "https://httpbin.org/status/404" try: response = requests.get(url) if response.status_code != 200: try: response.raise_for_status() except requests.exceptions.HTTPError: status = response.status_code print status raise InvalidUsage("An HTTP exception has been raised",status_code=status) except requests.exceptions.RequestException as e: print e if __name__ == "__main__": app.run(debug=True) My question is how do i get the exception string(message) and other relevant params from the requests.exceptions.RequestException object e ? Also what is the best way to log such exceptions . In case of an HTTPError exceptions i have the status code to refer to. But requests.exceptions.RequestException catches all request exceptions . So how do i differentiate between them and also what is the best way to log them apart from using print statements. Thanks a lot in advance for any answers.
has answer: http://stackoverflow.com/a/69960949
tagged with: python
has title: How to get the exception string from requests.exceptions.RequestException
tagged with: python-requests
linked to: http://stackoverflow.com/q/37684153
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/49100360
score: 4
has comment: http://stackoverflow.com/comment/100082958
tagged with: flask
linked to: http://stackoverflow.com/q/16511337
downvote count: 0

http://stackoverflow.com/comment/85174704
comment on: http://stackoverflow.com/q/49083826
type: QuestionComment
score: 0
has text: Actually, I find all of the lines that will cause error, except for '.'*n , others are `['in', 'emailing', 'Email', 'email', 'At', 'at', 'by', 'to', 'in', 'or', '•', 'Contact','contact', 'is', 'on']`
type: Comment

http://stackoverflow.com/q/49012114
has comment: http://stackoverflow.com/comment/85028805
has body: I have a file like this: https://gist.github.com/manbharae/70735d5a7b2bbbb5fdd99af477e224be What I want to do is generate 1 label for 1 second. Since this above file is 160 seconds long, there should be 160 labels. in other words I want to generate string of length 160. However I'm ending up having an str of len 166 instead of 160. My code : filename = './test_file.txt' ann = [] with open(filename, 'r') as f: for line in f: _, end, label = line.strip().split('\t') ann.append((int(float(end)), 'MIT' if label == 'MILAN' else 'not-MIT')) str = '' prev_value = 0 for s in ann: value = s[0] letter = 'M' if s[1] == 'MIT' else 'x' str += letter * (value - prev_value) print str prev_value = value name_of_file, file_ext = os.path.splitext(os.path.basename(filename)) print "\n\nfile_name processed:", name_of_file print str print "length of string", len(str),"\n\n" My final output: xxxxxxxMxMMMMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxMMMMMMMMMMMMMMMMMMMMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 166. Which is wrong. Str should be 160characters with each character per second, because file is 160 seconds long. There is some small bug somewhere, unable to find it. Please advise what's going wrong here? Thanks. Few things that I tried were , trying to include an if condition to break out of the loop once length of 160 is reached like this: if ann[len(ann)-1][0] == len(str): break; AFAIK, something is going wrong in the last iteration, because until then everything is fine. however it didn't help. I looked at : https://stackoverflow.com/a/14927311/4932791 https://stackoverflow.com/a/1424016/4932791
linked to: http://stackoverflow.com/q/14927114
tagged with: python
has answer: http://stackoverflow.com/a/49012639
downvote count: 0
score: 1
has title: generate string with length equal to length of time in file, with 1 label per second , python
type: Question
linked to: http://stackoverflow.com/q/1424005
upvote count: 1
answer count: 1
tagged with: string
tagged with: sequence
favorite count: 0
has comment: http://stackoverflow.com/comment/85028937
type: UnansweredQuestion

http://stackoverflow.com/q/49079685
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: opencv
has body: ret&amp;corners are always False&amp;None.I wrote img.py import numpy as np import cv2 import glob from PIL import Image # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((6*7,3), np.float32) objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. images = Image.open('cosme.jpg') gray = cv2.cvtColor(np.array(images),cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (7,6),None) print(ret) print(corners) # If found, add object points, image points (after refining them) if ret == True: objpoints.append(objp) corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) imgpoints.append(corners2) # Draw and display the corners img = cv2.drawChessboardCorners(img, (7,6), corners2,ret) cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows() Always ret is False,so image is not shown.print(ret) shows False and print(corners) shows None ,so always program does not go into if statement. I really cannot understand why ret are always False because gray has normal value.I think (7,6) causes this error but I cannot know what causes this error.What is wrong in my codes?How should I fix this?
score: -1
has title: ret&corners are always False&None
type: Question
tagged with: numpy
upvote count: 0
has answer: http://stackoverflow.com/a/49116168
answer count: 1

http://stackoverflow.com/a/49002512
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/49002272
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85009615
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49002272
has body: nan has the peculiar property of comparing not equal to anything, including nan itself: &gt;&gt;&gt; y = np.random.random(size=(2,2,3)) &gt;&gt;&gt; y[0,0,2] = np.nan &gt;&gt;&gt; y[0,1,0] = np.nan &gt;&gt;&gt; y[0,0,1] = np.nan &gt;&gt;&gt; y[0,1,2] = np.nan &gt;&gt;&gt; &gt;&gt;&gt; y array([[[0.03161193, nan, nan], [ nan, 0.55789282, nan]], [[0.78047397, 0.06949872, 0.65225197], [0.84801579, 0.11298244, 0.07627531]]]) &gt;&gt;&gt; &gt;&gt;&gt; y == np.nan array([[[False, False, False], [False, False, False]], [[False, False, False], [False, False, False]]]) To check for nan you have to use np.isnan &gt;&gt;&gt; np.isnan(y) array([[[False, True, True], [ True, False, True]], [[False, False, False], [False, False, False]]]) With this little modification your code will actually work: &gt;&gt;&gt; mask1 = (y==0).any(axis=2) &gt;&gt;&gt; mask2 = np.isnan(y).any(axis=2) &gt;&gt;&gt; y[np.logical_or(mask1, mask2)] = np.nan &gt;&gt;&gt; &gt;&gt;&gt; y array([[[ nan, nan, nan], [ nan, nan, nan]], [[0.78047397, 0.06949872, 0.65225197], [0.84801579, 0.11298244, 0.07627531]]])
type: Answer

http://stackoverflow.com/q/49013020
tagged with: wav
has comment: http://stackoverflow.com/comment/85033437
has title: scipy.io.wavfile.read() the stdout from FFmpeg
has comment: http://stackoverflow.com/comment/85034034
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85043339
tagged with: ffmpeg
accepted answer: http://stackoverflow.com/a/49019356
tagged with: python
type: AnsweredQuestion
tagged with: subprocess
score: 1
has answer: http://stackoverflow.com/a/49019356
has body: After searching for a long time, I still cannot find the solution to use scipy.io.wavfile.read() to read the bytes from the stdout of FFmpeg 3.3.6. Here is the example code working perfectly. However, it needs to save a converted file to disk. import subprocess import scipy.io.wavfile as wavfile command = 'ffmpeg -i in.mp3 out.wav' subprocess.run(command) with open('out.wav', 'rb') as wf: rate, signal = wavfile.read(wf) print(rate, signal) And here is the code I try to get the FFmpeg output from stdout and load it into scipy wavfile. import io import subprocess import scipy.io.wavfile as wavfile command = 'ffmpeg -i in.mp3 -f wav -' proc = subprocess.run(command, stdout=subprocess.PIPE) rate, signal = wavfile.read(io.BytesIO(proc.stdout)) print(rate, signal) Sadly, it raises a ValueError. Traceback (most recent call last): File ".\err.py", line 8, in &lt;module&gt; rate, signal = wavfile.read(io.BytesIO(proc.stdout)) File "C:\Users\Sean Wu\AppData\Local\Programs\Python\Python36\lib\site- packages\scipy\io\wavfile.py", line 246, in read raise ValueError("Unexpected end of file.") ValueError: Unexpected end of file. Are there any methods to solve this problem?
upvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/85034353
type: Question
has comment: http://stackoverflow.com/comment/85033740
has comment: http://stackoverflow.com/comment/85032951

http://stackoverflow.com/q/49002691
has title: Printing a list of prime factors in python
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85010055
type: Question
score: 0
has body: I'm trying to print a table that shows the prime factor counts of a certain number. I have a function to determine if a number is prime: def isPrime(n): p1 = factors(n) if len(p1) == 1: return True return False And a function to count the factors of a number into a dict object: from collections import Counter def factorCounts(n): a = factors(n) Counter(a) return dict(Counter(a)) Here's what I came up with for the table, but I cannot figure out how to use the if else statement to skip over a certain "i" if it is not prime: def printTable(n): for i in range(1,n): if isPrime(i) == True: return factorCounts(n) del(i) print(str(n).rjust(5), '*' * 7) This is the output for the above code. Obviously, it's not deleting an i if it is not prime, and it's not formatting the output into a table. printTable(10) {2: 1, 5: 1, 10: 1} Output should look like this: (where the stars represent how many times the prime is a factor of the number "n" and the dashes represent not a factor of "n") 2 ** 3 * 5 - 7 - 11 -
upvote count: 1
has comment: http://stackoverflow.com/comment/85042470
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85009971

http://stackoverflow.com/comment/85160901
type: Comment
has text: Oh sorry, the integers wouldn't always be in multiples of 3. Actually I just have a list of 6 locations that need to be divided by static integers. Is there a way I could just manually populate a list?
comment on: http://stackoverflow.com/a/49077455
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85151029
comment on: http://stackoverflow.com/a/49072512
type: Comment
score: 0
type: AnswerComment
has text: I tried that first, before posting. I get a traceback: ` bins[dig]` ` TypeErrorTraceback (most recent call last)` ` <ipython-input-1037-fa1ce02e82f4> in <module>()` ` ----> 1 bins[dig]` ` TypeError: only integer scalar arrays can be converted to a scalar index`

http://stackoverflow.com/q/49044133
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: git-submodules
has answer: http://stackoverflow.com/a/49044440
score: 3
upvote count: 3
type: Question
has title: No module named copy_reg in python3
has body: I have a git submodule that has this line import copy_reg It works for Python 2. However, there is no module named copy_reg in Python3. The Python3 module name is copyreg. I cannot change code in the git submodule since it will break in future updates. How to make the code work for both Python2 and Python3 without modifying module's code.
answer count: 1
downvote count: 0
tagged with: python-2.x

http://stackoverflow.com/a/49001227
answers question: http://stackoverflow.com/q/49001176
upvote count: 1
has body: I don't know if it's more verbose or not, but here's an alternative without calling split twice: patternMap = {x1:x2 for x1, x2 in map(lambda f: f.split('='), foo)}
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/49102975
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85211117
upvote count: 2
tagged with: python
has body: I am trying to remove an element from a JSON file using python. I have converted the dictionary to a python dictionary and so far I have been failing. JSON file I am working with is uploaded here I need to delete all the associated keys and value from the JSON if the key is 'access_ip_v4'. I cannot use sed/grep or any other regex techniques or string replace techniques. I am kind of stuck with python dictionaries on this. Here is my work so far. def dict_sweep(input_dic, k): for key in input_dic.keys(): if key == k: print("DIRECT DELETE") del input_dic[key] elif type(input_dic[key]) is dict: print('DICT FOUND') input_dic[key] = dict_sweep(input_dic[key], k) elif isinstance(type(input_dic[key]), type([])): print("LIST FOUND") for i, v in enumerate(input_dic[key]): if isinstance(input_dic[key][i], dict): input_dic[key][i] = dict_sweep(v, k) return input_dic I think my code fails when it encounters a list. Failing in the sense, clean_data = dict_sweep(data, 'access_ip_v4') print(clean_data) will again print the data rather than printing the cleaned version of data. I am not so sure about it. I have read some other questions like this but It is not helpful. Can someone give me a pointer here?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41267926
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/85212475
has comment: http://stackoverflow.com/comment/85211080
has answer: http://stackoverflow.com/a/49103013
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49103013
favorite count: 0
has title: Deleting a key from a nested dictionary / json

http://stackoverflow.com/comment/85221202
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49107685
has text: @ArpitSolanki Yes, quite literally. Maybe even more. Doing neural net stuff and working with extremely large data
type: AnswerComment

http://stackoverflow.com/a/49058046
has body: the issue is the ambiguity between the two pip that you've mentioned in the Environments. As you mentioned the issue only started occurring when you installed python3 on the same system where python2 was installed and both have pip and hence when you fire up pip in your cmd, Windows System isn't able to pick one out of the two. Why does your C:&gt;python27 -m pip install seaborn work? Well it's quite simple, since you've mentioned the python27 there, windows knows exactly which pip you're talking about. How to fix it? see the edits for this section. (I tried this, it didn't work) Removed it from the final answer to avoid confusion. Alternatively, what you can do is, rename your python.exe for python 3 to python3. Don't forget to put it inside your PATH environment. Just use python for python 2, python3 for python 3. Their pip are separated, pip for python 2. pip3 for python 3. Now, run and see the below commands behave: # will return the default version of pip pip --version # will use the Python 2 version of pip pip2 --version # will use the Python 3 version of pip pip3 --version
has comment: http://stackoverflow.com/comment/85120954
has comment: http://stackoverflow.com/comment/85122563
has comment: http://stackoverflow.com/comment/85120977
has comment: http://stackoverflow.com/comment/85122924
has comment: http://stackoverflow.com/comment/85122489
has comment: http://stackoverflow.com/comment/85121492
has comment: http://stackoverflow.com/comment/85121074
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49057888
has comment: http://stackoverflow.com/comment/85122824
has comment: http://stackoverflow.com/comment/85122351
downvote count: 0

http://stackoverflow.com/comment/85190913
score: 0
comment on: http://stackoverflow.com/q/49087063
type: QuestionComment
type: Comment
has text: Use `name` field in `obj.ville` model or use `_rec_name` to the specify the name (`_rec_name = 'field_name'`) of the record.

http://stackoverflow.com/comment/84968637
score: 0
comment on: http://stackoverflow.com/q/48981746
type: Comment
type: QuestionComment
has text: oh ... just realised ... `$.ajaxSetup` that doesn't make a request - surely you want `$.ajax`

http://stackoverflow.com/a/49048777
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/111266228
has comment: http://stackoverflow.com/comment/107121772
type: Answer
has body: TLDR (a) use neato, not dot to draw (b) pos attrs should be of the form "100,200!" in the dot file. Don't double-quote it, and add an ! mark. Firstly, not all of the graphviz tools support positions. See docs: In neato and fdp, pos can be used to set the initial position of a node Secondly, once you are using a tool that reads the pos attribute, you'll see some errors in the output. To understand problems with an external tool, it makes more sense to test it in isolation, so let's do that to file: nx.drawing.write_dot(graph, "test.dot") And then run neato: &gt; neato -Tpng test.dot &gt;test1.png Error: node 1, position "100,100", expected two doubles Error: node 2, position "100,200", expected two doubles Error: node 3, position "200,100", expected two doubles Error: node 4, position "200,200", expected two doubles You'll now see that the format isn't right. And so neato proceeds to layout the graph as if pos wasn't specified. for n in graph: graph.node[n]['pos'] = "{},{}!".format( graph.node[n]['x'], graph.node[n]['y']) Now try again: nx.drawing.write_dot(graph, "test_fix.dot") # note: the -n flag causes neato to use points rather than inches. # see docs, and/or experiment with -s setting as well &gt; neato -n -Tpng test_fix.dot &gt;test2.png And positions are now respected: Edge labels and image size The dot manual and this site both have info on how to draw edge labels (e.g. How to add edge labels in Graphviz? or Graphviz: Place edge label on the other side (II)), and obviously you need to add some property to your graph (see "associate data to edges using keywords": https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.DiGraph.add_edge.html ) It isn't clear what you mean by "plt.figure command does not really work" but this is quite far from the networkx issues here so I think it would be better to post a new question that isolates the problem and explains it fully.
has comment: http://stackoverflow.com/comment/85141080
answers question: http://stackoverflow.com/q/49040633
has comment: http://stackoverflow.com/comment/85113331
score: 4

http://stackoverflow.com/q/49020535
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/85046475
accepted answer: http://stackoverflow.com/a/49020621
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85046289
answer count: 1
favorite count: 0
has body: I have a csv Neighbours.csv which has disease name and patients who have that disease: Chondromalacia patellae,alex,maggie,bob Hypogonadism,Williams,alex and so on.... Another csv Similarityscores.csv which has Patient name and his score: Williams,0.0 alex,1.0 bob,2.0 maggie,0.5 and so on.... Now my desired output Disease name and sum of scores of the patients who have that disease: Chondromalacia patellae,3.5 Hypogonadism,1.0 I have tried processing Neighbours.csv first, but since the number of patients who have the disease is unknown, I am not able to proceed further.
has title: How to read a csv with unknown no of columns and compare it with another and retrieve values
has comment: http://stackoverflow.com/comment/85046488
downvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49020621
has comment: http://stackoverflow.com/comment/85046340
type: Question

http://stackoverflow.com/comment/85064402
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49028375
has text: Great! Please accept the answer. What happened @Chris couldn't I help you?

http://stackoverflow.com/q/49106456
tagged with: proxy
tagged with: python-asyncio
tagged with: python
has comment: http://stackoverflow.com/comment/85218469
accepted answer: http://stackoverflow.com/a/49107831
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85218289
tagged with: tcp
has comment: http://stackoverflow.com/comment/85220340
type: Question
has body: I am trying to build a man-in-middle proxy server that relays the client request to the various proxy services predefined in my app. So, in order to do this, I need to distinguish the client's request for a service. The code below works as long as I don't uncomment # data = await client_reader.read(2048) from which I can parse the headers. i.e. If I do perform that code, Say if am doing this with that line of code uncommmented: r = requests.get('http://api.ipify.org/', headers = {'Proxy-Type':'custom'}, proxies={'http':'http://127.0.0.1:9911'}) I would get a 408 Request Time-out from ipify in the r.content async def proxy_data(reader, writer, connection_string): try: while True: data = await reader.read(2048) if not data: break writer.write(data) await writer.drain() except Exception as e: raise finally: writer.close() async def accept_client(client_reader, client_writer): try: # Get proxy service - [Proxy-Type] from header via client_reader # Set remote_address and remote_port based on it # data = await client_reader.read(2048) (remote_reader, remote_writer) = await asyncio.wait_for( asyncio.open_connection(host = remote_address, port = remote_port), timeout = 30) except asyncio.TimeoutError: client_writer.close() except Exception as e: client_writer.close() else: # Pipe the streams asyncio.ensure_future(proxy_data(client_reader, remote_writer)) asyncio.ensure_future(proxy_data(remote_reader, client_writer)) def main(): def handle_client(client_reader, client_writer): asyncio.ensure_future( accept_client( client_reader = client_reader, client_writer = client_writer ) ) loop = asyncio.get_event_loop() try: server = loop.run_until_complete( asyncio.start_server( handle_client, host = '127.0.0.1', port = 9911)) except Exception as e: logger.error('Bind error: {}'.format(e)) sys.exit(1) for s in server.sockets: logger.debug('Proxy broker listening on {}'.format(s.getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass if __name__ == '__main__': main() Ca…
has comment: http://stackoverflow.com/comment/85218178
has comment: http://stackoverflow.com/comment/85219239
score: 0
has answer: http://stackoverflow.com/a/49107831
answer count: 1
has title: How to safely read ReaderStream from asyncio without breaking the stream

http://stackoverflow.com/comment/85210402
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49102116
has text: Updated latest code
score: 0

http://stackoverflow.com/a/48999905
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48999648
has body: a='''123456 0.7201741337776184 0.028222769498825073 G3/26 0.7428475022315979 0.14198169112205505 BED: 0.6399385929107666 0.14720818400382996 02/12/1979 0.7476143836975098 0.2584814727306366 DOB: 0.6413170695304871 0.26108822226524353 AGE: 0.6393641233444214 0.3781811594963074 32YSEX: 0.7450932264328003 0.379544198513031 M 0.9087993502616882 0.38598716259002686 6056 0.5140257477760315 0.490386426448822 REL: 0.6386545300483704 0.49573469161987305 HINDU 0.7446932792663574 0.4978155195713043 18/01/18 0.7429159879684448 0.6074452996253967 ADM: 0.6375628709793091 0.6129379272460938 PAY: 0.6137194633483887 0.7307364344596863 AUF 0.8062918186187744 0.7317520380020142 PVT 0.726770281791687 0.732855498790741 80611895 0.7259002923965454 0.8441673517227173 FND: 0.6144964098930359 0.847784698009491 ''' right,rightX,rightY=zip(*[x.split() for x in a.splitlines()]) rightX=list(map(float,rightX)) rightY=list(map(float,rightY)) prev_x=prev_y=None new_right=[] new_left=[] import math for text,x,y in zip(right,rightX,rightY): if prev_x and prev_y and math.fabs(prev_y - y) &lt;= 0.05: lastText = new_right.pop(-1) lastText=lastText.split() if prev_x &gt; x: lastText.insert(-1,text) else: lastText.append(text) new_right.append(' '.join(lastText)) else: new_right.append(text) prev_x = x prev_y = y for text in new_right: print(text)

gmail
type: Tag
tags question: http://stackoverflow.com/q/49017861
tag name: gmail
tags question: http://stackoverflow.com/q/48977538

http://stackoverflow.com/a/49040452
has body: I hope someone can give you a more elegant method. Split each string of words into a list, in a new column, called words. Multiply these lists by the column Amount, then request their counts using Counter. Aggregate these counts across records using an external function, aggregator. Finally construct the new Dataframe using the aggregated data. import pandas as pd from collections import Counter, defaultdict def aggregator(counter): for k in counter.keys(): result[k]+=counter[k] df = pd.read_excel('sampleWordData.xlsx', header=0) df['words'] = df['Word'].str.split() df['counts'] = (df['words']*df['Amount']).apply(Counter) result = defaultdict(int) df.counts.apply(aggregator) new_df = pd.DataFrame({'words': list(result.keys()), 'counts': list(result.values())}) print (new_df) Printed result: counts words 0 20 Google 1 10 is 2 10 awesome 3 5 Hi
answers question: http://stackoverflow.com/q/49035510
score: 0
type: Answer

http://stackoverflow.com/q/49053494
tagged with: dataframe
has answer: http://stackoverflow.com/a/49053866
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49053774
accepted answer: http://stackoverflow.com/a/49053774
tagged with: pandas
favorite count: 0
has title: Sum of grouped by data in Pandas (Python)
tagged with: python
possible better answer: http://stackoverflow.com/a/49053866
has body: For my task, I need to understand some Python Pandas Code in order to make some modification and reimplement it using another programming language(Java). I took some online tutorials, but still have issues with Pandas. For example, this lines: uniq_page_df = df.groupby(["asin", "views_count"]) uniq_page_df = uniq_page_df.sum().reset_index() sum_views_count = int(uniq_page_df["views_count"].sum()) In this part, as I understand, author tries to calculate total views count. So my question is, why do we need to group by and calculate sum for each group(line 2) and then calculate overall sum(line 3)? Why we cannot calculate it without grouping by? Or I didn’t understand this part of code correctly. Another question is, why do we need to reset_index() after calculating sum() on line 2? UPDATE: all columns in data frame are: asin, product_group, category_description, views_count
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/85072923
comment on: http://stackoverflow.com/q/49033663
has text: Ajax will only update my page, but how it will be reflected in every user's page? is my understanding right?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85082908
type: Comment
comment on: http://stackoverflow.com/a/49037201
score: 0
type: AnswerComment
has text: @stevendesu `df2.add(df1).dropna()` Does that work?

http://stackoverflow.com/a/49101288
downvote count: 2
upvote count: 1
score: -1
has body: darts_list = [20,1,18,4,13,6,10,15,2,17,3,19,7,16,8,11,14,9,12,5] d=dict() for c in darts_list: d[c]=0
answers question: http://stackoverflow.com/q/49101245
type: Answer

http://stackoverflow.com/q/49041524
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Error doing update_item in DynamoDB python boto3
tagged with: amazon-dynamodb
accepted answer: http://stackoverflow.com/a/49044502
type: Question
tagged with: boto3
has body: I have a table in DynamoDB that holds a bunch of documents for me. The documents have the following fields: computedID (Primary partition key), publication_timestamp, displayTitle, displayText, displayUrl, producer and tags. I'd like to do update_item on the table, so that a record gets updated only if any of the fields publication_timestamp, displayTitle, displayText, displayUrl, producer and tags has changed. If the record is totally new it will be simply inserted in the table. The problem is that not all the existing documents in the table or the incoming documents have displayTitle, displayText, displayUrl and tags. They may miss any number of these fields. I have tried the following: dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('project_Incoming_Data') print("Sending documents to DynamoDB...") for item in Docs: try: response=table.update_item( Key={"computedID":item["computedID"]}, UpdateExpression="SET publication_timestamp = :time, displayTitle= :title, displayText= :text, producer = :p, tags= :tags, displayUrl= :url, time_to_live= :ttl", ConditionExpression= "publication_timestamp &lt;&gt; :time OR (attribute_exists(displayTitle) AND displayTitle &lt;&gt; :title) OR (attribute_exists(displayText) AND displayText &lt;&gt; :text) OR producer &lt;&gt; :p OR (attribute_exists(tags) AND tags &lt;&gt; :tags) OR (attribute_exists(displayUrl) AND displayUrl &lt;&gt; :url)", ExpressionAttributeValues={ ":time":item["publication_timestamp"], ":ttl":item["time_to_live"], ":title":item["displayTitle"], ":text":item["displayText"], ":p":item["producer"], ":tags":item["tags"], ":url":item["displayUrl"] }, ReturnValues="UPDATED_NEW" ) print("response is: "+str(response)) except Exception as e: print (e) print("Done with sending documents to DynamoDB") I still am unable to get some of my documents into DynamoDB. The error I get is 'displayText'! I am guessing that the mechanism I have in place for making sure that the field exists on the record doesn't work …
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49044502

http://stackoverflow.com/a/49100564
has body: Separate the part that throws the exception you're interested in from the parts that throw unrelated exceptions: try: iterator = iter(y) except TypeError: handle_that() else: do_whatever_with([orig[x].value.flatten() for x in iterator])
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49100416
type: Answer
accepted answer of: http://stackoverflow.com/q/49100416

http://stackoverflow.com/q/49110788
has comment: http://stackoverflow.com/comment/85226655
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49111130
type: Question
has title: issues when executing crontab job
score: 0
tagged with: cron
answer count: 1
tagged with: debian
has body: i have a simple cron job that should sent mail every 15 minutes and update a local sqlite3 db file. the problem is while i do get the mails correctly,the table in the db dose not get updated, import sys import Adafruit_DHT import time import sqlite3 import datetime import smtplib print('Fierd!') print(datetime.datetime.now()) humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 17) conn = sqlite3.connect('history.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS history(id INTEGER PRIMARY KEY AUTOINCREMENT,temp real,humidty integer,time DATE )''') c.execute('''INSERT INTO history(temp,humidty,time) VALUES(?,?,?)''',(temperature,humidity,datetime.datetime.now())) conn.commit() conn.close() server = smtplib.SMTP('*************',587) server.starttls() server.login('******','********') msg =temperature server.sendmail('*******************','******************',repr(msg)) server.quit() as you can see the mail should be sent after the value was inserted to the db. but i am only reciving the mails. if i am running it manually it dose work as expected. EDIT: this is the cron command: */15 * * * * sudo python /home/pi/adafruit_python_DHT/examples/saveHistory.py &amp;> /tmp/mycommand.log # JOB_ID_1 any ideas ?
has comment: http://stackoverflow.com/comment/85226695
has answer: http://stackoverflow.com/a/49111130
tagged with: python

http://stackoverflow.com/a/49113782
downvote count: 0
answers question: http://stackoverflow.com/q/49012987
accepted answer of: http://stackoverflow.com/q/49012987
score: 3
upvote count: 3
type: AcceptedAnswer
has body: Thanks to a helpful user on Reddit who pointed out what I had wasn't considered a CellID but what's referred to as a token, this has been solved. CellID has a from_token function that can be used as such. import s2sphere from s2sphere import CellId, LatLng, Cell def get_corners(s2CellId_str, level): c1 = Cell(CellId.from_token(s2CellId_str)) print(c1) c0 = LatLng.from_point(c1.get_center()) # center lat/lon of s2 cell v0 = LatLng.from_point(c1.get_vertex(0)) # lat/lon of upper/left corner v1 = LatLng.from_point(c1.get_vertex(1)) # lat/lon of lower/left corner v2 = LatLng.from_point(c1.get_vertex(2)) # lat/lon of lower/right corner v3 = LatLng.from_point(c1.get_vertex(3)) # lat/lon of upper/right corner print(' // s2 level ' + str(level) + ' cell id = ' + s2CellId_str) print('Center = ' + str(c0)) print('Vertex0 = ' + str(v0)) print('Vertex1 = ' + str(v1)) print('Vertex2 = ' + str(v2)) print('Vertex3 = ' + str(v3)) get_corners("487a73cc7c", 17) Documentation: http://s2sphere.readthedocs.io/en/latest/api.html#s2sphere.CellId.from_token As a slightly different solution, if you've got the lat/long values, you can do it like this: import s2sphere lat = 52.809766 lng = -2.088996 cell_id = s2sphere.CellId.from_lat_lng(s2sphere.LatLng.from_degrees(lat,lng)).parent(12) print (s2sphere.LatLng.from_point(s2sphere.Cell(cell_id).get_center())) print (s2sphere.LatLng.from_point(s2sphere.Cell(cell_id).get_vertex(0))) print (s2sphere.LatLng.from_point(s2sphere.Cell(cell_id).get_vertex(1))) print (s2sphere.LatLng.from_point(s2sphere.Cell(cell_id).get_vertex(2))) print (s2sphere.LatLng.from_point(s2sphere.Cell(cell_id).get_vertex(3)))
type: Answer

http://stackoverflow.com/comment/85183371
type: QuestionComment
comment on: http://stackoverflow.com/q/49088820
has text: Please, tell us what you've done so far
score: 0
type: Comment

http://stackoverflow.com/a/51580736
type: Answer
answers question: http://stackoverflow.com/q/49121072
downvote count: 1
upvote count: 0
score: -1
has body: I don't know the exact process of finding the path in Google Colab, but I solved the above problem using copy paste in Google Colab: (!wget http://alereimondo.no-ip.org/OpenCV/uploads/34/frontalFace10.zip) !unzip frontalFace10.zip

http://stackoverflow.com/a/49000922
score: 1
answers question: http://stackoverflow.com/q/49000803
type: Answer
has body: a=[3, 5, 2, 7, 5, 3, 6, 8, 4] mean_list = [ mean(x) for x in [ y[1:3] for y in [ sorted(a[z:z+3]) for z in range(len(a)) if z &lt; len(a) -2 ] ] ]
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/49046317
tagged with: merge
upvote count: 4
has answer: http://stackoverflow.com/a/49046361
accepted answer: http://stackoverflow.com/a/49046361
type: AnsweredQuestion
downvote count: 0
tagged with: pivot
has body: I'm looking to combine three columns into a single column within a dataframe, using the column headers as the value for the new column. All three columns have a unique value of '1' where the other two just have NaN. Originally I wanted to use pivot, but I suspect a merge operation would be easier? I'm just not sure how to go about it. i.e. I need to turn index A B C time id 0 1 NaN NaN 4.42 1 1 1 NaN NaN 4.48 3 2 1 NaN NaN 5.45 2 3 NaN 1 NaN 6.64 2 4 NaN 1 NaN 7.49 1 5 NaN 1 NaN 7.72 3 6 NaN NaN 1 8.13 1 7 NaN NaN 1 8.65 2 8 NaN NaN 1 9.07 3 into... index type time id 0 A 4.42 1 1 A 4.48 3 2 A 5.45 2 3 B 6.64 2 4 B 7.49 1 5 B 7.72 3 6 C 8.13 1 7 C 8.65 2 8 C 9.07 3
type: Question
tagged with: dataframe
score: 4
tagged with: pandas
answer count: 1
favorite count: 0
has title: Pandas pivot/merge multiple columns into single, using column headers as values
tagged with: python

http://stackoverflow.com/a/48993450
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48993409
answers question: http://stackoverflow.com/q/48993409
type: Answer
has comment: http://stackoverflow.com/comment/85029367
downvote count: 0
score: 1
has body: This is one way: da0['new'] = da0['B'].map(da1.set_index('E')['F']) Result A B C D new 0 foo two -0.616481 -0.679958 beta 1 bar one 1.721246 -0.985037 alpha 2 foo two 0.782059 -0.694043 beta 3 bar three -1.088806 1.855281 gamma 4 foo three 0.302535 0.042422 gamma 5 bar one 1.893247 -1.218680 alpha 6 foo two -2.337719 -0.077325 beta 7 foo two 0.137897 1.709476 beta Explanation pd.Series.map may take a Series as an input. Using set_index ensures the values from da0['B'] aligns with da1['E'].
has comment: http://stackoverflow.com/comment/85029876

http://stackoverflow.com/a/49067400
has comment: http://stackoverflow.com/comment/85189919
type: Answer
has body: Import caches all imports, so with multiple imports they will just access the cached version after the first time an import is performed. See https://docs.python.org/3/reference/import.html for details of how this works. Generally speaking you should create your import structure around the concept of modules being correct, performance shouldn't be a large factor in this decision, because honestly when you get the import structure right there won't be that much of a performance difference. If you use something from a module in a file you should explicitly import that module. Related to this make sure that every module you use can be imported directly without error, this will help you design your modules better and avoid a class of subtle bugs where changing the order of importing can cause errors due to the caching mechanism in importlib.
accepted answer of: http://stackoverflow.com/q/49067384
has comment: http://stackoverflow.com/comment/85139936
answers question: http://stackoverflow.com/q/49067384
score: 5
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/85140258
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85139844

http://stackoverflow.com/comment/85042845
score: 0
comment on: http://stackoverflow.com/q/49018087
has text: Of course. As you can notice, I wrote `print` as a function, which was not the case in Python 2
type: QuestionComment
type: Comment

seaborn
tags question: http://stackoverflow.com/q/49117963
tags question: http://stackoverflow.com/q/49000141
tags question: http://stackoverflow.com/q/48967026
tags question: http://stackoverflow.com/q/49099765
tags question: http://stackoverflow.com/q/49020709
tag name: seaborn
tags question: http://stackoverflow.com/q/49006287
tags question: http://stackoverflow.com/q/49042433
tags question: http://stackoverflow.com/q/49065885
tags question: http://stackoverflow.com/q/49083571
tags question: http://stackoverflow.com/q/49034829
tags question: http://stackoverflow.com/q/48985874
tags question: http://stackoverflow.com/q/48990594
tags question: http://stackoverflow.com/q/49059956
tags question: http://stackoverflow.com/q/49033814
tags question: http://stackoverflow.com/q/49035671
tags question: http://stackoverflow.com/q/49104975
tags question: http://stackoverflow.com/q/49044131
tags question: http://stackoverflow.com/q/49086528
tags question: http://stackoverflow.com/q/49104411
tags question: http://stackoverflow.com/q/49078697
tags question: http://stackoverflow.com/q/48986387
tags question: http://stackoverflow.com/q/48991374
type: Tag
tags question: http://stackoverflow.com/q/49060138
tags question: http://stackoverflow.com/q/49082667

http://stackoverflow.com/a/49101561
downvote count: 0
answers question: http://stackoverflow.com/q/49101521
upvote count: 2
has body: You can do this for all of the types at the same time: df.groupby('type').apply(lambda dft: dft.nlargest(3, 'growth')) returns person_code type growth size type 32 6 434 32 0.82 90 0 231 32 0.54 32 2 432 32 0.44 21 43 1 233 43 0.12 333 56 3 431 56 0.32 23 89 4 654 89 0.12 89
type: Answer
score: 2

http://stackoverflow.com/comment/85186931
type: QuestionComment
comment on: http://stackoverflow.com/q/49090690
score: 0
has text: Possible duplicate of [Python dictionary, how to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-in-same-order-as-declared)
type: Comment

http://stackoverflow.com/q/49055834
tagged with: web2py-modules
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49057211
accepted answer: http://stackoverflow.com/a/49057211
type: Question
tagged with: python-2.7
score: 0
answer count: 1
has title: Web2py - how to create a group "manager" using appadmin
tagged with: web2py
tagged with: python-3.x
has body: I'm going through Web2py book documentation because i'm new to it and i can't find any better tutorial anywhere (recommendations are welcomed). While going through the overview section, i got to an instruction that says Using appadmin create a group "manager" and make some users members of the group. I've been trying to figure out how to do this for the past few hours and still no success. I can't find any interface in the app admin for creating groups. I tried this plugin manager for managing groups and i was still getting errors. All suggestions are welcomed
tagged with: python

http://stackoverflow.com/comment/84934022
type: QuestionComment
comment on: http://stackoverflow.com/q/48964009
score: 0
has text: Though your pip list does not show tensorflow cpu version, did you have a look at this issue anyway: https://github.com/tensorflow/tensorflow/issues/12388 May be uninstall tensorflow completely and install tensorflow-gpu by specifing the version as mentioned in the github issue.
type: Comment

http://stackoverflow.com/comment/85135770
has text: perfect, this is what I needed :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49063017
type: Comment
score: 0

http://stackoverflow.com/comment/85127296
type: QuestionComment
comment on: http://stackoverflow.com/q/49060927
has text: Thanks for the link! Will study.
score: 0
type: Comment

http://stackoverflow.com/a/56688280
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49033806
has body: If you want to debug code in Spyder, it's probably best to run the module it's in by clicking the blue Play/Pause button for debug. So how do we debug a module that is all classes or functions, with no script? We add script that only runs when this module was the one we clicked Play for, by putting it all under if __name__=="__main__":. (See here for more info on how that works.) Then we can put a break point in the function or class we want to debug, call that from within if __name__==__"__main__":, run the module with the blue Play/Pause button, and access what's happening from the IPython console.
type: Answer

http://stackoverflow.com/a/49067378
has comment: http://stackoverflow.com/comment/132032344
score: 1
has body: [Time(t1, t2, t3) for t1, t2, t3 in (line.split() for line in f.splitlines())] With or without splitlines depends of your variable f
downvote count: 0
answers question: http://stackoverflow.com/q/49066799
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85141054

http://stackoverflow.com/comment/85001326
comment on: http://stackoverflow.com/q/48997385
type: Comment
type: QuestionComment
has text: Do you use BatchNormalization` in your model?
score: 0

http://stackoverflow.com/comment/84958002
comment on: http://stackoverflow.com/q/48976237
type: Comment
type: QuestionComment
has text: you are getting three values.`07+0080BB5B+67`. `int( "0080BB5B",16) = 0008436571`
score: 1

http://stackoverflow.com/a/49082216
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49080911
has body: For this type of problem you should really consider seaborn. import seaborn as sns # reshape the data into 'tidy form' for seaborn melted = pd.melt(db.reset_index(), value_vars=[c for c in db.columns if '-Q' in c], value_name='Mean', var_name='Quarter', id_vars=['Type', 'Category']) g = sns.factorplot(data=melted, x='Quarter', y='Mean', col='Type', hue='Category', kind='point') You can change what type of plot you have and explore around really fast and easily. For example: And change the 'kind' keyword: [edited because its 2:30 am] Maybe fit a trend to the means?
has comment: http://stackoverflow.com/comment/85187164
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49080911
has comment: http://stackoverflow.com/comment/85180812

http://stackoverflow.com/q/49068438
accepted answer: http://stackoverflow.com/a/49068669
answer count: 1
has body: I query the sqlite db quite a few times and with some queries I pass in the row from a csv file to insert and some queries I just select with one query. DB Manager class: class DatabaseManager(object): def __init__(self, db): self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() def query(self, arg, arg2=None): self.cursor.execute(arg, arg2) self.conn.commit() return self.cursor def __del__(self): self.conn.close() So an example: Query1: db.query('INSERT OR REPLACE INTO randomtable VALUES (?,?,?,?)', row) Query2: db.query('select * from random_tabletwo') Or would I need to create two methods which have the same exact code but different arguments?
has comment: http://stackoverflow.com/comment/85141909
score: 0
tagged with: sqlite
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85141860
type: AnsweredQuestion
has title: Is it possible to have an option parameter for executing a sqlite statements
has answer: http://stackoverflow.com/a/49068669
type: Question

http://stackoverflow.com/comment/85027320
type: AnswerComment
comment on: http://stackoverflow.com/a/49011344
type: Comment
score: 0
has text: Oh god! Yeah I was thinking something like that... In that case, What would you recommened to do in that case if I want to run something similar?

http://stackoverflow.com/comment/85097572
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49046501
type: Comment
has text: In that case use a dictionary

http://stackoverflow.com/q/48968242
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84943464
answer count: 0
tagged with: scientific-computing
has comment: http://stackoverflow.com/comment/84944269
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/84943262
has title: Scipy Optimization Errors: divide by zero encountered
has comment: http://stackoverflow.com/comment/84944270
tagged with: optimization
has comment: http://stackoverflow.com/comment/84944314
score: 0
has comment: http://stackoverflow.com/comment/84944289
has comment: http://stackoverflow.com/comment/84944235
has body: I'm confused as to how I am getting a divide by zero error when trying to maximize a function. solution = minimize(objective,x0, method='SLSQP', bounds = bnds, constraints = cons) __main__:36: RuntimeWarning: invalid value encountered in double_scalars C:\Users\loren\AppData\Roaming\Python\Python36\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater return (self.a &lt; x) &amp; (x &lt; self.b) C:\Users\loren\AppData\Roaming\Python\Python36\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less return (self.a &lt; x) &amp; (x &lt; self.b) C:\Users\loren\AppData\Roaming\Python\Python36\site-packages\scipy\stats\_distn_infrastructure.py:1738: RuntimeWarning: invalid value encountered in greater_equal cond2 = (x &gt;= self.b) &amp; cond0 __main__:38: RuntimeWarning: invalid value encountered in double_scalars __main__:40: RuntimeWarning: invalid value encountered in double_scalars __main__:29: RuntimeWarning: invalid value encountered in double_scalars __main__:31: RuntimeWarning: invalid value encountered in double_scalars __main__:33: RuntimeWarning: invalid value encountered in double_scalars __main__:36: RuntimeWarning: divide by zero encountered in double_scalars __main__:29: RuntimeWarning: divide by zero encountered in double_scalars __main__:38: RuntimeWarning: divide by zero encountered in double_scalars __main__:31: RuntimeWarning: divide by zero encountered in double_scalars __main__:40: RuntimeWarning: divide by zero encountered in double_scalars __main__:33: RuntimeWarning: divide by zero encountered in double_scalars The code still runs but I don't get anything useful. fun: nan jac: array([ nan, nan, nan, nan, nan, nan, nan, nan, nan, nan]) message: 'Iteration limit exceeded' nfev: 2212 nit: 101 njev: 101 status: 9 success: False x: array([ nan, nan, nan, nan, nan, nan, nan, nan, nan, nan]) Here is my objective function: def objective(x): #x &lt;-&gt…
has comment: http://stackoverflow.com/comment/84944304
has comment: http://stackoverflow.com/comment/84944307

svd
type: Tag
tags question: http://stackoverflow.com/q/49023337
tag name: svd

http://stackoverflow.com/a/50165264
answers question: http://stackoverflow.com/q/48979352
score: 0
type: Answer
has body: There might be a way to change the value passed to the argument locationmode to take state names instead of state codes. As an alternative if there's a dataframe statesdf with a column statesdf['state'] containing the state name you can use the below code to create state codes from state names: state_codes = { 'District of Columbia' : 'dc','Mississippi': 'MS', 'Oklahoma': 'OK', 'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR', 'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', 'Idaho': 'ID', 'Wyoming': 'WY', 'Tennessee': 'TN', 'Arizona': 'AZ', 'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT', 'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', 'California': 'CA', 'Massachusetts': 'MA', 'West Virginia': 'WV', 'South Carolina': 'SC', 'New Hampshire': 'NH', 'Wisconsin': 'WI', 'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', 'Pennsylvania': 'PA', 'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', 'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO', 'Ohio': 'OH', 'Alabama': 'AL', 'Rhode Island': 'RI', 'South Dakota': 'SD', 'Colorado': 'CO', 'New Jersey': 'NJ', 'Washington': 'WA', 'North Carolina': 'NC', 'New York': 'NY', 'Texas': 'TX', 'Nevada': 'NV', 'Maine': 'ME'} statesdf['state_code'] = statesdf['state'].apply(lambda x : state_codes[x])

http://stackoverflow.com/a/49100961
score: 0
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49100796
has body: If you don't mind to have a list of tuples as a result, I find this solution very readable. &gt;&gt;&gt; alist = [[0], [1], [2]] &gt;&gt;&gt; blist = [-1, 0, 1] &gt;&gt;&gt; import itertools as it &gt;&gt;&gt; list(zip(it.chain(*alist), blist)) [(0, -1), (1, 0), (2, 1)] If you must have a list of lists: list(list(el) for el in zip(it.chain(*alist), blist)) Basically, I am unpacking the variable alist into positional arguments, which I then pass to itertools.chain(). This results in a flat list [0, 1, 2]. After that, you can simple zip the two lists and get the desired result without using a for loop. It is not the fastest but a valid, possible solution.

http://stackoverflow.com/q/49049535
tagged with: numpy
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85103401
tagged with: arrays
has comment: http://stackoverflow.com/comment/85103483
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/85103334
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85103186
has answer: http://stackoverflow.com/a/49049657
accepted answer: http://stackoverflow.com/a/49049657
has body: I have a 3 dimensional numpy array similar to this: a = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]) What I'd like to do is intersperse each 2D array contained inside the outer array to produce this result: t = np.array([[[1, 2], [5, 6], [9, 10]], [[3, 4], [7, 8], [11, 12]]]) I could do this in Python like this, but I'm hoping there's a more efficient, numpy version: t = np.empty((a.shape[1], a.shape[0], a.shape[2]), a.dtype) for i, x in np.ndenumerate(a): t[i[1], i[0], i[2]] = x
type: Question
has title: Intersperse items of a numpy array
possible better answer: http://stackoverflow.com/a/49049654
has answer: http://stackoverflow.com/a/49049654

http://stackoverflow.com/comment/85054336
comment on: http://stackoverflow.com/a/49024828
type: Comment
has text: On Windows, I sometimes have to add `python -m` in front of the `pip` call.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49090335
answers question: http://stackoverflow.com/q/49090239
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/49090239
type: Answer
has body: There are several methods: The Python way, just add try: and except with the relevant exception classes. try: # parsing &amp; processing logic here pass except EmptyDataError as ex: # tell user we don't except empty data pass except ParserError as ex: # tell user we failed to parse their input pass except Exception as ex: # tell user that something went wrong. pass The Flask way, register error handlers with flask for specific exceptions (this effects the whole flask application): @app.errorhandler(pandas.errors.EmptyDataError) def handle_empty_data(): return 'Failed parsing Input', 200
has comment: http://stackoverflow.com/comment/85186522

http://stackoverflow.com/comment/85083573
score: 3
comment on: http://stackoverflow.com/q/49039113
has text: Fire up your python interpreter and try it out.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49113572
type: Question
has body: I have a problem with some of my python code. I want it to open a file, with few lines of text, and add header + footer to each line in that file. The problem is that 'create_output()' function returns only the first line with additional content. If I switch 'return' to 'print' at the end of this function it properly displays all lines from my file. What could be the reason? I want to understand what am I doing wrong here. file_path = '/home/user/Desktop/text.txt' file_path_edited = '/home/user/Desktop/text_new.txt' header = 'http://' footer = '.com' def open_file(): opened_file = open(file_path) return opened_file def edit_file(): edited_file = open(file_path_edited, 'w') return edited_file def create_output(): for line in open_file(): line = line.strip() edited_line = header+line+footer to_file = edit_file() to_file.writelines(edited_line) to_file.close() return edited_line print (create_output())
has title: Add header and footer to each line in a file. Function returns only first line
score: -2
has comment: http://stackoverflow.com/comment/85232799
tagged with: python-2.7
downvote count: 2
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/85232192
has comment: http://stackoverflow.com/comment/85232168
has comment: http://stackoverflow.com/comment/85232125
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49115080
tagged with: python
has answer: http://stackoverflow.com/a/49114040
upvote count: 0
has answer: http://stackoverflow.com/a/49114323
has comment: http://stackoverflow.com/comment/85232280
has comment: http://stackoverflow.com/comment/85232496
has comment: http://stackoverflow.com/comment/85232239

http://stackoverflow.com/comment/84950281
type: AnswerComment
type: Comment
has text: @doyz - Glad can help!
comment on: http://stackoverflow.com/a/48972379
score: 0

http://stackoverflow.com/comment/85189442
type: Comment
has text: @LoopTurn well as it said, your indentation is wrong, check that you are using tabs instead of spaces. Some editors like sublime, use spaces when you use the tab button so take care of that
comment on: http://stackoverflow.com/a/49091967
score: 0
type: AnswerComment

http://stackoverflow.com/q/49031690
has body: I am generating a binary file. I opened it using hexdump, it looks like this below enter image description here But when I try to read this file in python using file = open("lfsr.bin","rb") data = file.read(10) print data It's printing blank/empty But if I do print repr(data) It prints '\x00\x00\x00\x00\x01\x00\x01\x01\x01\x01' How can I read this file in chunks of 1023? This file is actually an o/p of PRN generator code.
has answer: http://stackoverflow.com/a/49032413
has comment: http://stackoverflow.com/comment/85068163
type: Question
tagged with: gnuradio
answer count: 1
tagged with: gnuradio-companion
accepted answer: http://stackoverflow.com/a/49032413
score: 0
has title: Reading .bin or .dat file in Python
tagged with: binaryfiles
tagged with: lfsr
has comment: http://stackoverflow.com/comment/85068031
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85216762
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49102974
has text: @Quasar No. Cross-validation is for you. Model will not use that. Cv is for you to analyse the effect of different data on your model. Check and change the parameters of model or modify the data so that it can handle such data and then fit on whole data.
type: Comment

http://stackoverflow.com/a/64756171
answers question: http://stackoverflow.com/q/49118209
type: Answer
score: 1
upvote count: 1
has body: You can simply do: data = soup.find_all('li',{'class':'z'}) print(data) If you only want to get text: for a in data: print(a.text)
downvote count: 0

http://stackoverflow.com/q/49033477
has title: Insert to Oracle Database with cx_Oracle python 2.7
tagged with: oracle-database
tagged with: python
has body: I connected to my oracle database with cx_Oracle, had good connection and read needed data from base. Then tried to insert something in base and failed. try: print uid2 + "/" + pwd2 + "@" + service1 dconn1 = cx_Oracle.connect(uid2 + "/" + pwd2 + "@" + service1) except: pass print dconn1 ver = dconn1.version.split(".") print ver cur = dconn1.cursor() pdb.set_trace() rows=[("NET-CI99999")] sql_test='insert into Device2M1 (logical_name) values (:1)' sql_test_2='insert into Device2M1 (logical_name) values ("NET-CI99999")' #cur.prepare(sql_insert) #cur.execute(sql_test_2) cur.prepare(sql_test) cur.executemany(None,rows) dconn1.commit() cur.execute("select logical_name,serial_no_,location,id,updated_by,contact_name,istatus,subtype,user_id,sysmodtime,sysmoduser,title,email,extension,ip_address,mac_address,updated_by, ig_fqdn,ig_domain,ig_model,ig_vendor,ig_inventory_numb,ig_network_equip,ig_name,ig_asset_tag,ig_it_asset_id,ig_it_asset_created,ig_registrator from Device2M1 where logical_name='NET-CI13681'") for result in cur: for i in result: # pdb.set_trace() print i cur.close() dconn1.close() Part of the code with selections worked well, when try do just cur.execute for insertion console hang and make no replay, when try to do something with executemany have an error "cx_Oracle.DatabaseError: ORA-01036: неверное имя/номер переменной (wrong name/number of the variable)". Any idea about what is this and what could I do for proper working of the code?
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85140605
type: Question
has comment: http://stackoverflow.com/comment/85085818
tagged with: sql-insert
has comment: http://stackoverflow.com/comment/85158080
tagged with: cx-oracle

http://stackoverflow.com/q/49009169
has comment: http://stackoverflow.com/comment/85022925
tagged with: django
has body: I am fairly new to Django and I have set up a sign up form with some additional fields. In my forms.py file I have the following code: class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) In my views.py I have the following code: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('index') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) Then in my signup.html view I am rendering the following: {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} {{ error }} {% endfor %} {% endfor %} Let's Go! Essentially what I want to do is add placeholder text in each field but this is not appearing the way I have set it up. To do this I need more control over the forms fields but I don't know how to do that because of the way I am rendering fields in a loop. How would I go about doing this?
has answer: http://stackoverflow.com/a/49009433
tagged with: django-views
tagged with: django-forms
has comment: http://stackoverflow.com/comment/85059664
type: Question
linked to: http://stackoverflow.com/q/4101258
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85022661
linked to: http://stackoverflow.com/q/13523286
tagged with: python
has title: Add placeholder field to basic UserCreation Django sign up form
has comment: http://stackoverflow.com/comment/116210234
tagged with: django-templates
type: UnansweredQuestion

http://stackoverflow.com/q/49013522
type: AnsweredQuestion
has title: Pandas: Select rows whose dictionary contains a specific key
tagged with: dataframe
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/49013628
has answer: http://stackoverflow.com/a/49013550
answer count: 2
has answer: http://stackoverflow.com/a/49013628
downvote count: 0
score: 4
accepted answer: http://stackoverflow.com/a/49013550
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: dictionary
has body: I have a dataframe, in which one column is all dictionary. I want to select rows whose dictionary contains a given key. &gt;&gt;&gt; df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":2}, {"c":3}]}) &gt;&gt;&gt; df A B 0 1 {'a': 1} 1 2 {'b': 2} 2 3 {'c': 3} &gt;&gt;&gt; df['b' in df['B']] # the desired result is the row with index 1. But this causes an error: KeyError: False

http://stackoverflow.com/comment/110672797
score: 0
type: AnswerComment
type: Comment
has text: Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.
comment on: http://stackoverflow.com/a/62580213

http://stackoverflow.com/comment/85208877
has text: Oh... query will not work with those column names starting with a special character or containing a space. You need to revert back to boolean indexing such as df[df['#CNAE'] == "64.34-4-00"]
comment on: http://stackoverflow.com/a/49101559
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/85257162
type: Comment
comment on: http://stackoverflow.com/a/49110204
has text: @pylearner - Aslo you can check [this](https://stackoverflow.com/questions/14262433/large-data-work-flows-using-pandas)
type: AnswerComment
score: 0

http://stackoverflow.com/a/49063113
downvote count: 0
has comment: http://stackoverflow.com/comment/85151987
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49059916
has body: EDIT: You can pass on the positional argument in the from_networkx(pos=) function. I tested your code with networkx 2.2 and python 3.5. It works with minor tweaks. import networkx as nx import pandas as pd from bokeh.models import Plot, ColumnDataSource, Range1d, from_networkx, Circle,MultiLine from bokeh.io import show, output_file from bokeh.palettes import Viridis #define graph source = ['A', 'A', 'A','a','B','B','B','b'] target = ['a', 'B','b','b','a','b','A','a'] weight = [1,-1000,1,1,1,1, -1000, 1] df = pd.DataFrame([source,target,weight]) df = df.transpose() df.columns = ['source','target','weight'] G=nx.from_pandas_edgelist(df) # function signature changes #set node attributes node_color = {'A':Viridis[10][0], 'B':Viridis[10][9],'a':Viridis[10][4],'b':Viridis[10][4]} node_size = {'A':50, 'B':40,'a':10,'b':10} node_initial_pos = {'A':(-0.5,0), 'B':(0.5,0),'a':(0,0.25),'b':(0,-0.25)} nx.set_node_attributes(G, node_color, name='node_color') # function signature changes nx.set_node_attributes(G, node_size, name='node_size') # function signature changes nx.set_node_attributes(G, node_initial_pos, name='node_initial_pos') # function signature changes #source with node color, size and initial pos (perhaps ) source = ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in G.nodes(data=True)}, orient='index')) plot = Plot(plot_width=400, plot_height=400, x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) graph_renderer = from_networkx(G, nx.spring_layout, scale=0.5, center=(0,0), pos=node_initial_pos) #style graph_renderer.node_renderer.data_source = source graph_renderer.node_renderer.glyph = Circle(fill_color = 'node_color',size = 'node_size', line_color = None) graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5) plot.renderers.append(graph_renderer) output_file('test.html') show(plot) Output: Without positional argument Output: With positional argument
answers question: http://stackoverflow.com/q/49059916
score: 6
has comment: http://stackoverflow.com/comment/85154986
has comment: http://stackoverflow.com/comment/85148207
type: AcceptedAnswer

http://stackoverflow.com/q/49106336
has comment: http://stackoverflow.com/comment/85262955
has comment: http://stackoverflow.com/comment/85264105
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49129877
has comment: http://stackoverflow.com/comment/85260602
has title: Docker and Conda: Differences when building the same container on Mac and on Ubuntu
type: Question
tagged with: anaconda
tagged with: conda
accepted answer: http://stackoverflow.com/a/49129877
tagged with: docker
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85263568
has body: I'm using to Docker to build a Python container with the intention of having a reproducible environment on several machines, which are a bunch of development Macbooks and several AWS EC2 servers. The container is based on continuumio/miniconda3, i.e. Dockerfile starts with FROM continuumio/miniconda3 A few days ago on Ubuntu the conda install and conda upgrade commands in the Docker file complained about a new Conda version (4.11) being available: ==&gt; WARNING: A newer version of conda exists. &lt;== current version: 4.4.10 latest version: 4.4.11 Please update conda by running $ conda update -n base conda If I ignore this, package installations quit with an error: Downloading and Extracting Packages The command '/bin/sh -c conda install -y pandas=0.22.0 matplotlib scikit-learn=0.19.1 pathos lazy openpyxl pytables dill pydro psycopg2 sqlalchemy pyarrow arrow-cpp parquet-cpp scipy tensorflow keras xgboost' returned a non-zero code: 1 When I add this conda update... to the Docker file, things work again. What's really annoying, however, is that the update that makes things run in Ubuntu does not work on Mac Docker. I get the following error: CondaEnvironmentNotFoundError: Could not find environment: base . You can list all discoverable environments with `conda info --envs`. Note that I get this error when I docker build the same Docker file that works on the Ubuntu machine, which kind of ruins the whole point about using Docker in the first place. On the Mac, the old version of the file (without conda update -n base conda) still runs fine and installs all packages. Docker / Conda experts, any ideas? Edit: Here's the full Dockerfile (the one that works in Ubuntu): # Use an official Python runtime as a parent image FROM continuumio/miniconda3 WORKDIR /app/dev/predictive.analytics RUN apt-get update; \ apt-get install -y gcc tmux htop RUN conda update -y -n base conda RUN conda config --add channels babbel; \ conda config --add channels conda-forge; RUN conda install -y…
upvote count: 2
tagged with: python

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/48998930
tags question: http://stackoverflow.com/q/49039581
type: Tag
tags question: http://stackoverflow.com/q/49080548
tags question: http://stackoverflow.com/q/49092807

http://stackoverflow.com/a/49047005
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85098838
has comment: http://stackoverflow.com/comment/85099372
has comment: http://stackoverflow.com/comment/85098990
has body: You want to access member or the other cols ? just do that : df.select("group_profile.group.id", "group_profile.group.members", "group_profile.intro", "group_profile.link", "group_profile.role", )
accepted answer of: http://stackoverflow.com/q/49046909
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49046909

http://stackoverflow.com/a/48968841
accepted answer of: http://stackoverflow.com/q/48968805
type: Answer
upvote count: 1
has body: Your decorator function signatures are reversed: wrapper should take the original wrapped function, and args_typecheck should take the type to check: def args_typecheck(type): def wrapper(func): def inner(*args): if not all(map(lambda x: isinstance(x, type), args)): raise TypeError return func(*args) return inner return wrapper @args_typecheck(str) def seq(*args): return reduce(operator.eq, args)
score: 1
answers question: http://stackoverflow.com/q/48968805
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85175635
score: 0
comment on: http://stackoverflow.com/q/49085106
type: Comment
type: QuestionComment
has text: Also, I don't think you meant to define input parameters to the nested functions since you talk about closures. Take a look at LEGB and the `nonlocal` keyword.

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/49114439
tags question: http://stackoverflow.com/q/49028069
type: Tag

http://stackoverflow.com/q/49049649
type: AnsweredQuestion
tagged with: key
favorite count: 0
accepted answer: http://stackoverflow.com/a/49049943
has answer: http://stackoverflow.com/a/49049881
type: Question
has title: For the common keys, how would you access the corresponding values
score: -2
possible better answer: http://stackoverflow.com/a/49049881
answer count: 2
downvote count: 3
upvote count: 1
tagged with: python
has body: def query_RR(postings, qtext): words = tokenize(qtext) allpostings = [postings[w] for w in words] for a in allpostings: print a.keys() And this was the result of the query [0, 2, 3, 4, 6] [1, 4, 5] [0, 2, 4] [4, 5] The query is taking a user input term (qtext), tokenizing and generating a postings list for each token. The posting list is a list of nested dictionaries. e.g. [{0 : 0.68426, 1: 0.26423}, {2: 0.6842332, 0: 0.9823}] For the common keys, how would you access the corresponding values, for my example the common value is 0so how would you access values {0 : 0.68426, 0: 0.9823}?
tagged with: dictionary
tagged with: list
has answer: http://stackoverflow.com/a/49049943
has comment: http://stackoverflow.com/comment/85103486

python-jira
tags question: http://stackoverflow.com/q/49119707
tag name: python-jira
type: Tag

http://stackoverflow.com/comment/84939936
type: QuestionComment
has text: Hi, I tried that but it came up with the error: `TypeError: insert() missing 1 required positional argument: 'string'`
comment on: http://stackoverflow.com/q/48966649
score: 0
type: Comment

http://stackoverflow.com/q/48997207
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: multithreading
downvote count: 1
type: Question
score: -1
tagged with: concurrency
has body: Does anyone know how to write a Hybrid mutex in python? By Hybrid Mutex I mean a mutex that does both: it spins for a time in anticipation of a quick lock, but eventually blocks the thread if things take too long, relinquishing the CPU. I know that people have given it a try in C but am looking for a pythonic way to do it. For eg: https://hackernoon.com/building-a-c-hybrid-spin-mutex-f98de535b4ac
has answer: http://stackoverflow.com/a/49010811
tagged with: python-2.7
has title: Adaptive Mutex in Python
upvote count: 0

http://stackoverflow.com/q/49072373
score: 0
answer count: 1
tagged with: python
tagged with: regex
has title: The cloud panel doesn't into directory in django
type: UnansweredQuestion
tagged with: django
tagged with: django-urls
has answer: http://stackoverflow.com/a/49072856
has body: I write cloud panel write python/django. My problem is, urls.py doesn't access next forward directory. I use apache. when it is go to next forward, this page is showing: https://postimg.org/image/b1t9s26b9/ my urls.py inside: from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$','explorer.views.home',name='home'), url(r'^servers/$','explorer.views.servers'), url(r'^addserver/$','explorer.views.addserver'), url(r'^removeserver/$','explorer.views.removeserver'), url(r'^manage/(?P<server>[\w]+)/(?P<path>[\w]+)/$','manager.views.filemanager'), url(r'^navback/(?P<server>[\w]+)/(?P<path>[\*\w]+)/$','manager.views.navbackward'), url(r'^naviforward(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P [\w]+)/$','manager.views.navforward'), url(r'^edit/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.editdata'), url(r'^saveandsend/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.senddata'), url(r'^upload/(?P<server>[\w]+)/(?P<path>[\*\w]+)/$','manager.views.uploadfile'), url(r'^delete/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.deletefile'), ] my views.py inside: https://postimg.org/image/s2c60qr2d/ views.py inside for ssh connection and sftp connection : https://postimg.org/image/635rdjhxx/ my routing to html file inside: {% if path != orginalpath %} {% endif %} {% for d in dirs %} {{ d }} {% endfor %} if you're access to project and image you can be look in link: https://postimg.org/gallery/3iakj1t7a/ https://gitlab.com/rection/Cloud-Panel-Django.git How to be solution my problem?
type: Question

http://stackoverflow.com/q/48969324
tagged with: python
tagged with: kivy
has body: i am a newbie to both python and kivy. I have been trying to develop a simple Pong game with Python. Everything was going well until i tried to put together a Menu. I used ScreenManager to try to navigate through the two screens. But when i press the button, nothing happens. Every answer or idea is well appreciated! Here is my .py code: from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty,ObjectProperty from kivy.vector import Vector from kivy.clock import Clock import pygame from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.gridlayout import GridLayout from kivy.lang import Builder class Menu(GridLayout,Screen): def __init__(self, **kwargs): super(Menu, self).__init__(**kwargs) pass class PongSpadi(Widget): stig = NumericProperty(0) def skoppa_bolti(self, bolti): if self.collide_widget(bolti): vx, vy = bolti.velocity offset = (bolti.center_y - self.center_y) / (self.height / 2) skoppadur = Vector(-1 * vx, vy) vel = skoppadur bolti.velocity = vel.x, vel.y + offset class PongBolti(Widget): velocity_x = NumericProperty(0) velocity_y = NumericProperty(100) velocity = ReferenceListProperty(velocity_x, velocity_y) def move(self): self.pos = Vector(*self.velocity) + self.pos class PongGame(Screen, Widget): bolti = ObjectProperty(None) spilari1 = ObjectProperty(None) spilari2 = ObjectProperty(None) h1 = NumericProperty(310) h2 = NumericProperty(310) def serve_bolti(self, vel=(12, 6)): self.bolti.center = self.center #Staðsetur boltann í miðjuna self.bolti.velocity = vel def update(self, dt): self.bolti.move() self.spilari1.skoppa_bolti(self.bolti) #skoppar bolta af spöðum self.spilari2.skoppa_bolti(self.bolti) if (self.bolti.y &lt; 0) or (self.bolti.top &gt; self.height): self.bolti.velocity_y *= -1 #Lætur boltan skoppa ef hann snertir vegginn uppi/niðri if self.bolti.x &lt;self.x: self.spilari2.stig += 1 #skráir stig ef bolti fer í hliðarnar se…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84944251
has title: Kivy ScreenManager does not switch screens
type: Question
has answer: http://stackoverflow.com/a/48969603
score: 0
has comment: http://stackoverflow.com/comment/84946163
answer count: 1

http://stackoverflow.com/a/48988696
has comment: http://stackoverflow.com/comment/85121253
upvote count: 1
answers question: http://stackoverflow.com/q/48988593
score: 1
has body: updates["result"] is a list of dictionaries. You will have to iterate through all of them and see if any of them have 'light' for the 'text' key: results = updates["result"] for result in results: if result['message']['text'] == 'light': print 'found light text' If you are certain that you will always have a single result you can only check the first one: result = updates["result"][0] if result['message']['text'] == 'light': print 'found light text' In this case you will want to use a try-except just in case you don't get back any result: try: result = updates["result"][0] except IndexError: print 'Empty result' else: if result['message']['text'] == 'light': print 'found light text'
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85231588
score: 0
type: AnswerComment
has text: I guess in the end it will be limited by disk write speed, anyways.
type: Comment
comment on: http://stackoverflow.com/a/49112389

http://stackoverflow.com/comment/86865838
type: AnswerComment
score: 0
type: Comment
has text: Thanks again.For me, deactivated constraints have a meaning. Without going into to much depth- we do something similar to the extended cutting plane method for convex MINLPs: We deactivate nonlinear constraints, pass the linear model to a solver and then check if the nonlinear constraints are satisfied at some minimizer of the linear model. If not, we add a cutting plane. However, explicitly using the nonlinearity, deactivating equality-constraints suffices. As I need to compute the gradient of violated constraint functions, deleting eliminated variables seems beneficial. Is this possible?
comment on: http://stackoverflow.com/a/49055076

http://stackoverflow.com/q/48979757
accepted answer: http://stackoverflow.com/a/48979963
has title: Page not found 404 URL config
tagged with: django
tagged with: python
tagged with: design-patterns
type: AnsweredQuestion
tagged with: mapping
type: Question
has answer: http://stackoverflow.com/a/48979963
has body: I keep getting the following error in my terminal (while running server) when I try to look at the home page. "GET / HTTP/1.1" 404 2028 here is the code that I have for mapping URLS: urls.py (main): from django.urls import path from django.contrib import admin from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path(r' ', include('learning_logs.urls', namespace='learning_logs')), ] urls.py(in learning_logs folder) """Define URL pattersn for learning_logs.""" from django.conf.urls import url from . import views app_name = 'learning_logs' urlpatterns = [ # Home page url(r'^$', views.index, name='index'), ] views.py: from django.shortcuts import render def index(request): """The home page for learning log""" return render(request, 'learning_logs/index.html') # Create your views here. index.html: Learning Log Learning log helps you keep track of your learning, for any topic you're learning about. this is the error I'm getting on the home page: Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ Thanks for the help in advance.
score: 0
answer count: 1
tagged with: url

http://stackoverflow.com/comment/85234373
has text: for Python 3, this has to be wrapped in a `list` constructor.
comment on: http://stackoverflow.com/a/49114678
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/85244359
type: QuestionComment
comment on: http://stackoverflow.com/q/49119392
score: 9
has text: Why are you using numpy? How about just `list(''.join(wd))`?
type: Comment

http://stackoverflow.com/q/49077771
answer count: 1
tagged with: python
has body: I have Blender and the add-on Blender.osm installed, and I'm trying to import a terrain programmatically from a Blender's Python script. By hovering on the add-on GUI, I get these information: which I try and implement as such: import bpy import csv import math bpy.data.scenes["Scene"].blander_osm.dataType = 'terrain' bpy.ops.blender_osm.import_data(0,10,0,10) But the console shows some errors: File "/Applications/blender/blender.app/Contents/Resources/2.79/scripts/modules/bpy/ops.py", line 186, in __call__ C_dict, C_exec, C_undo = BPyOpsSubModOp._parse_args(args) File "/Applications/blender/blender.app/Contents/Resources/2.79/scripts/modules/bpy/ops.py", line 143, in _parse_args raise ValueError("1-3 args execution context is supported") If it helps, here's the source code at the lines where the errors are raised: I'm guessing I'm not proving the coordinates in the right format, but can't figure out how to do it properly... What's the proper way to import a terrain using this add-on?
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49088608
tagged with: blender
type: Question
has title: Controlling Blender.osm with Python

http://stackoverflow.com/q/48991251
answer count: 1
has answer: http://stackoverflow.com/a/48993476
upvote count: 1
tagged with: c#
accepted answer: http://stackoverflow.com/a/48993476
has body: I'm trying to run Python from C# via a command line process. System.Diagnostics.Process proc = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = "/Users/username/.pyenv/shims/python", Arguments = cmd+" "+args, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; I derived the FileName from using which: username$ which python /Users/username/.pyenv/shims/python However, running python --version from the terminal, and then again through the C# process, yield different results: username$ python -V Python 2.7.11 And C#: Python 2.7.10 I understand the base problem - that it's calling another version of Python, probably the base one that came from Apple. But what I don't understand is why, because as I understand it I'm telling it to call python from pyenv directly. Is there a way to get C# to use the same python executable I'm using from the terminal?
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Calling Pyenv Python From C#
favorite count: 0
tagged with: terminal
type: Question
tagged with: python

http://stackoverflow.com/comment/85060887
type: QuestionComment
has text: "What I need is it be in a list, so essentially a list of dictionary" : sorry but this is not enough to warrant the right answer - please post the _exact_ result you expect.
comment on: http://stackoverflow.com/q/49027872
score: 0
type: Comment

http://stackoverflow.com/a/48996036
has comment: http://stackoverflow.com/comment/84998714
has body: Reading data from an temporary file-like object I do not have direct access to Google ML so I have to apologize if this answer doesn't work. I did something similiar to directly read h5-files from a zipped folder, but I hope this will work here to. from scipy import io import numpy as np from io import BytesIO #Creating a Testfile Array=np.random.rand(10,10,10) d = {"Array":Array} io.savemat("Test.mat",d) #Reading the data using a in memory file-like object with open('Test.mat', mode='rb') as input_f: output = BytesIO() num_b=output.write(input_f.read()) ab = io.loadmat(output)
has comment: http://stackoverflow.com/comment/85015317
answers question: http://stackoverflow.com/q/48986640
has comment: http://stackoverflow.com/comment/84997926
has comment: http://stackoverflow.com/comment/84998205
type: Answer
has comment: http://stackoverflow.com/comment/84998433
score: 0

http://stackoverflow.com/q/49068903
has body: I'm trying to grab every other letter from a string but i'm having some problem with print and return. Why when i use print, the output is what i want and when i use return i only get the first letter? string_bits(Hello) # Return string made of every other char starting with the first def string_bits(str): x = len(str) for i in range(0,x,2): print str[i] output: H l o vs def string_bits(str): x = len(str) for i in range(0,x,2): return str[i] output: H
has answer: http://stackoverflow.com/a/49069069
tagged with: python
has answer: http://stackoverflow.com/a/49069236
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85142607
has comment: http://stackoverflow.com/comment/85142817
accepted answer: http://stackoverflow.com/a/49069236
downvote count: 1
type: Question
has title: Python 2.7 print vs return
has answer: http://stackoverflow.com/a/49069483
tagged with: python-2.7
upvote count: 0
has answer: http://stackoverflow.com/a/49069046
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/85142627
has comment: http://stackoverflow.com/comment/85142709
possible better answer: http://stackoverflow.com/a/49069069

http://stackoverflow.com/q/49070248
score: 0
accepted answer: http://stackoverflow.com/a/49071635
answer count: 1
has title: Django - compare a matching column from two Querysets/models?
has comment: http://stackoverflow.com/comment/85147777
tagged with: django
tagged with: python
has body: I have two models. sitesubnets and devicesubnets. I would like to compare the two models so I can create two lists. one list will have matching subnets one will have non matching subnets across them I have tried using set difference but as they are different models I don think it works test queries: sitesubnet_data = SiteSubnets.objects.filter(site_id=site_id) devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id) data = set(sitesubnet_data).difference(set(devicesubnet_data)) when I compare sitesubnet_data with data, they are the same my models: class SiteSubnets(models.Model): site = models.ForeignKey(SiteData, on_delete=models.CASCADE) subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE) class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" unique_together = ('site', 'subnet',) class DeviceSubnets(models.Model): device = models.ForeignKey(DeviceData, on_delete=models.CASCADE) subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE) class Meta: verbose_name = "Device Subnets" verbose_name_plural = "Device Subnets" unique_together = ('device', 'subnet',)
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/49071635

http://stackoverflow.com/comment/85049986
type: Comment
has text: Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly)
comment on: http://stackoverflow.com/q/49000463
score: 0
type: QuestionComment

http://stackoverflow.com/a/49056817
type: Answer
answers question: http://stackoverflow.com/q/49056702
has body: The 2nd line of the output has a clue to the problem - "Using cached ..." You can skip the cache using the --skip-cache --no-cache-dir option to pip install or request an upgrade using the -U option edit: updated comment with the correct option (although, seems like that wasn't the problem in this specific case).
score: 0
has comment: http://stackoverflow.com/comment/85118464

http://stackoverflow.com/q/49022718
score: 0
has comment: http://stackoverflow.com/comment/85050591
answer count: 1
has comment: http://stackoverflow.com/comment/85050836
has comment: http://stackoverflow.com/comment/85050771
favorite count: 0
has answer: http://stackoverflow.com/a/49742854
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85074256
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85051280
has comment: http://stackoverflow.com/comment/85051747
accepted answer: http://stackoverflow.com/a/49742854
downvote count: 1
type: Question
has title: Flask ImportError: cannot import name routes
tagged with: flask
has body: I'm converting a cli application to use a REST api and I've read up on flask and I thought I understood things but apparently not :-D. based on this: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world I have a directory structure: --myApp myApp.py --APIService __init__.py WebService.py myApp.py: from APIService import app app.run(debug = True ) init: from flask import Flask app = Flask(__name__) from app import routes WebService.py: from APIService import app class WebService(object): ''' classdocs ''' def __init__(self,): ''' Constructor ''' @app.route('/') @app.route('/index') def index(): return "Hello, World!" I've tried this a few different ways like renaming app to APIService but I keep circling back to the same error: APIService\__init__.py", line 5, in &lt;module&gt; from app import routes ImportError: No module named app I just don't get what I'm doing wrong here. I did pip install flask so the module is there. I skipped the environment part but that's because I wasn't bothered with running globally for now. anyone have a clue as to what I messed up?

http://stackoverflow.com/comment/85107274
type: QuestionComment
has text: are you sure you are reaching `http://127.0.0.1:5000/register`? Can you run the flask `application.run(debug=True)` and provide the error displayed on the python console,
score: 0
comment on: http://stackoverflow.com/q/49051101
type: Comment

http://stackoverflow.com/comment/85479948
type: AnswerComment
has text: nothing.. you can do away with it... It's just a `"pretty print"`
comment on: http://stackoverflow.com/a/49012593
type: Comment
score: 0

http://stackoverflow.com/a/48992767
has comment: http://stackoverflow.com/comment/85066368
has comment: http://stackoverflow.com/comment/84992390
has comment: http://stackoverflow.com/comment/84991769
has comment: http://stackoverflow.com/comment/84991899
has comment: http://stackoverflow.com/comment/84991975
answers question: http://stackoverflow.com/q/48992644
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84991213
downvote count: 0
has body: Try this regex: \d+(?=\D*?value = 100 = 0x64 = 'd') Click for Demo Explanation: \d+ - matches 1+ occurrences of a digit (?=\D*?value = 100 = 0x64 = 'd') - positive lookahead to make sure that the current position is followed by 0+ occurrences of non-digits, as few as possible, followed by the string value = 100 = 0x64 = 'd'
type: Answer
accepted answer of: http://stackoverflow.com/q/48992644
score: 2
has comment: http://stackoverflow.com/comment/85066233
upvote count: 2
has comment: http://stackoverflow.com/comment/84991712
has comment: http://stackoverflow.com/comment/84991394

http://stackoverflow.com/comment/85778710
type: QuestionComment
comment on: http://stackoverflow.com/q/49083326
score: 0
type: Comment
has text: Do you have `seaborn` installed? If so you could use `sns.set_context('talk')` or `sns.set_context('poster')` to easily change the figure size although this doesn't answer your question.

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/49056028

http://stackoverflow.com/q/49000768
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/49000974
tagged with: pandas
answer count: 1
has title: Sorting csv data by headers but getting IndexError
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
upvote count: 1
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49000974
has comment: http://stackoverflow.com/comment/85008211
has body: It seems that my code fails when I try to set what headers/columns of data I want to use giving me an index error when trying to parse headers import pandas as pd import quandl import math, datetime import numpy as np from sklearn import preprocessing , cross_validation, svm from sklearn.linear_model import LinearRegression import scipy import matplotlib.pyplot as plt from matplotlib import style import pickle style.use('ggplot') df = pd.read_csv('convertcsv.csv',sep='\t') df = np.array(df) print(df) df = df'Open','High','Low','Close','Volume (BTC)' print("ok") df['HL_PCT'] = (df['High'] - df['Close']) / df['Close'] * 100.0 df['PCT_change'] = (df['Close'] - df['Open']) / df['Open'] * 100.0 df = df'Close','HL_PCT','PCT_change','Volume (BTC)' forecast_col = 'Close' df.fillna(-999999, inplace=True) forecast_out = int(math.ceil(0.01*len(df))) df['label'] = df[forecast_col].shift(-forecast_out) X = np.array(df.drop(['label'],1)) X = preprocessing.scale(X) X_lately = X[-forecast_out:] X = X[:-forecast_out:] df.dropna(inplace=True) y = np.array(df['label']) X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2) clf = LinearRegression(n_jobs=-1) clf.fit(X_train, y_train) with open('linearregression.pickle','wb') as f: pickle.dump(clf, f) pickle_in = open('linearregression.pickle','rb') clf =pickle.load(pickle_in) accuracy = clf.score(X_test,y_test) print(accuracy) forecast_set = clf.predict(X_lately) df['Forecast'] = np.nan last_date = df.iloc[-1].name last_unix = last_date.timestamp() one_day = 86400 next_unix = last_unix + one_day for i in forecast_set: next_date = datetime.datetime.fromtimestamp(next_unix) next_unix += one_day df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)] + [i] df['Close'].plot() df['Forecast'].plot() plt.legend(loc=4) plt.xlabel('Date') plt.ylabel('Price') plt.pause(1) plt.show() print("we done?")` ... I cant seem to figure out what I am doing wrong, it worked with the previous data set I was u…
type: Question

http://stackoverflow.com/q/49101962
tagged with: regex
has title: Remove non-alphabet characters, convert to lowercase, and remove words smaller than 3 letters for a list of lists
has answer: http://stackoverflow.com/a/49102368
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49102052
has answer: http://stackoverflow.com/a/49102052
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85209884
type: Question
accepted answer: http://stackoverflow.com/a/49102368
tagged with: python-2.7
score: 0
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/85209125
has body: I'm using Python 2.7 and I'm wondering if I can do many things at once with one line of code. What I have currently: csvarticles = [['[Beta-blockers]', 'Magic!', '1980', 'Presse medicale'],['Hypertension in the pregnant woman].', '', '2010', 'Medical'],['Arterial hypertension.', '', '1920', 'La Nouvelle']] output = [[re.sub("[^ '\w]"," ",x).strip().lower() for x in y] for y in csvarticles] output = [[re.sub(r'\b\w{,3}\b','',x) for x in y] for y in output] &gt;&gt;&gt; [['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', ' nouvelle']] This is the output I want, but with extra spaces. I'm not really worried about the extra spaces (unless it's an easy fix). Is there any way I could combine these two one-liners? What I've tried: output = [[re.sub("[^ '\w{,3}]"," ",x).strip().lower() for x in y] for y in csvarticles] &gt;&gt;&gt; [['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension in the pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', 'la nouvelle']] output = [[re.sub("[r '\b\w{,3}\b]"," ",x).strip().lower() for x in y] for y in csvarticles] &gt;&gt;&gt; [['[ - ]', '!', '', ''], ['].', '', '', ''], ['.', '', '', '']] Thanks to @'rahlf23' &amp; @'Jean-François Fabre' for solving my first question. I've read through the documentation for regex and I just can't wrap my mind around it.
tagged with: python

http://stackoverflow.com/q/49073765
tagged with: concatenation
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49074589
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85153635
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has body: I have two or more dataframes in Pandas in a list A Value1 1 ABC 2 HYT 3 IUF A Value2 1 IJT 2 GFH 3 QER When using df = pd.concat(dfs, axis = 0) And after writing to CSV, the final output is like this A Value1 Value2 1 ABC 1 IJT 2 HYT 2 GFH 3 IUF 3 QER But I'd like it to be like this A Value1 Value2 1 ABC IJT 2 HYT GFH 3 IUF QER Can someone point me in the right direction?
accepted answer: http://stackoverflow.com/a/49074589
answer count: 3
possible better answer: http://stackoverflow.com/a/49074136
has answer: http://stackoverflow.com/a/49074923
has answer: http://stackoverflow.com/a/49074136
has title: Python Pandas Concat list of Dataframes With Different Columns and Same Rows
tagged with: dataframe

http://stackoverflow.com/comment/85098047
has text: Just print the list once and check the index of the required part. Check the edit. I've added that part.
comment on: http://stackoverflow.com/a/49046534
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49036063
tagged with: scrapy
downvote count: 1
has answer: http://stackoverflow.com/a/49036260
type: Question
has body: How to find the number of URLs repeating in a website? As scrappy framework doesn't scrape duplicate urls by default. I just need to find which URLs are repeating and how many times. I tried to do it, by calculating the number of URLs repeating at function close spider but after some digging, I realized that we cannot yield anything in this function.
has comment: http://stackoverflow.com/comment/85077111
answer count: 2
has answer: http://stackoverflow.com/a/49036720
has comment: http://stackoverflow.com/comment/85089711
score: 0
has title: Finding count of urls repeating in website crawing using scrapy
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: web-scraping

http://stackoverflow.com/q/49100283
tagged with: datetime
upvote count: 1
tagged with: python
has title: YYMM to date time python
score: 1
type: Question
has answer: http://stackoverflow.com/a/49100306
has comment: http://stackoverflow.com/comment/85207065
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a dateframe column in Python that is in the format YYMM. E.g January 1996 is 9601. I'm having a hard time converting it from 9601 to a useable date time format. I want the new format to be 01-01-1996. Does anyone have any suggestions? I tried pd.to_datetime function but it's not getting the results I'm looking for.
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49061798
has comment: http://stackoverflow.com/comment/85157821
has body: I understand how to bind keys when it's just on a simple frame but since I built my app in a different way, I can't seem to figure out how to bind the return key to press the button or run the function that the button is bounded to. I've been searching for a similar question by others on the website but I haven't found one similar to mine. I've toned down the rest of my code and have it below: import tkinter as tk from tkinter import * class POS(tk.Tk): def __init__(self,*args,**kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side = "top", fill = "both", expand = True) container.grid_rowconfigure(0, weight = 1) container.grid_columnconfigure(0, weight = 1) self.frames = {} for F in (ErrorPage, MainPage): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column = 0, sticky = "nsew") self.show_frame(MainPage) def show_frame(self,cont): frame = self.frames[cont] frame.tkraise() class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) frame = tk.Frame(self) frame.pack(fill = BOTH) button = Button(frame, text = "OK", command = self.bindHello) button.pack(pady=5, padx=10) frame.bind("&lt;Return&gt;", self.bindHello) self.bind("&lt;Return&gt;", self.bindHello) def bindHello(self, event=None): print("HELLO1") #Yes this doesn't do anything but I need it for the frame container as set before class ErrorPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) frame = tk.Frame(self) frame.pack(fill = BOTH) button = Button(frame, text = "OK", command = self.bindHello) button.pack(pady=5, padx=10) frame.bind("&lt;Return&gt;", self.bindHello) def bindHello(self, event=None): print("HELLO2") app = POS() app.mainloop() Simple Button bind I had intended to work as is as follows: from tkinter import * master = Tk() def callback(event=None): print("Hello " + entry.get()) entry = StringVar() e = Entry(master, textvariable = entry, width = 15) e.pack() b = Butt…
favorite count: 0
has comment: http://stackoverflow.com/comment/85147161
tagged with: tkinter
upvote count: 2
tagged with: python
tagged with: bind
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49082605
score: 2
has comment: http://stackoverflow.com/comment/85128755
has title: Tkinter Return key bind doesn't work due to class structure
accepted answer: http://stackoverflow.com/a/49082605
has comment: http://stackoverflow.com/comment/85165973
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/85128683
answer count: 1

http://stackoverflow.com/q/48975874
has answer: http://stackoverflow.com/a/48988268
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I have Selenium code running, if the test fail i want to see the entire process from start to finish (not using a screenshot), something know how can record the screen while selenium running. from selenium import webdriver driver = webdriver.Chrome() # If test is fail i want to save video file who recorded the whole process def test1(): driver.get(...) e = driver.find_element(...) e.click() assert e.text == 'Some Text' Thx.
tagged with: opencv
downvote count: 3
has title: How record the screen while Selenium Python is running (Windows 10)
tagged with: selenium
linked to: http://stackoverflow.com/q/16511384
type: Question
answer count: 2
score: -1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/75714401

http://stackoverflow.com/a/49042561
upvote count: 0
answers question: http://stackoverflow.com/q/49042383
type: Answer
downvote count: 1
score: -1
has body: Numpy has 16bit-floats: In [64]: import numpy In [65]: a = numpy.float16(0.112312) In [66]: a Out[66]: 0.1123 Maybe you can convert between numpy.float16 and RawArray https://docs.python.org/3.6/library/multiprocessing.html#multiprocessing.sharedctypes.RawArray Shared-memory objects in multiprocessing

http://stackoverflow.com/comment/85191973
type: Comment
has text: can this be used forward? so I could get the min. value in the future time? lets say at 08:07 i would need the min. value for the range of 08:08 to 08:10, ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49089103

http://stackoverflow.com/comment/85207373
comment on: http://stackoverflow.com/q/49100921
score: 0
type: Comment
type: QuestionComment
has text: Thank you for the help, i did it a different way and got it working better.

http://stackoverflow.com/a/49055867
has body: Here's one way: df3 = df2[df2['col2'] != ''].sort_values('date', ascending=False).drop_duplicates('name') # col2 date name # 2 4 2018-02-28 19:55:29 bil However, the dataframe you provided and output you desire seem to be inconsistent.
has comment: http://stackoverflow.com/comment/85116723
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49055771
has comment: http://stackoverflow.com/comment/85116768
answers question: http://stackoverflow.com/q/49055771
score: 0
type: Answer

http://stackoverflow.com/q/49041313
has comment: http://stackoverflow.com/comment/85089480
has title: Assistant SDK on raspberry pi 3 throwing repeated location header errors
has comment: http://stackoverflow.com/comment/85088298
type: Question
tagged with: raspberry-pi
score: 0
answer count: 1
tagged with: raspberry-pi3
has body: Both an existing raspberry pi 3 assistant-sdk setup and a freshly created one are producing identical errors at all times idle or otherwise. The lines below are repeating over and do not seem to be affected by the state of the assistant. Replicates across multiple developer accounts, devices and projects. Present with both the stock hotword example and modified scripts that worked previously. All cases are library assistant and python 3 on raspberry pi 3 model B running raspbian stretch. [9780:9796:ERROR:assistant_ssdp_client.cc(210)] Failed to parse header: LOCATION: about:blank [9780:9796:ERROR:assistant_ssdp_client.cc(76)] LOCATION header doesn't contain a valid url
tagged with: google-assistant-sdk
has answer: http://stackoverflow.com/a/49223023
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85226372
type: QuestionComment
comment on: http://stackoverflow.com/q/49110560
has text: It was hidden in the text:D I've just edited my post @manandearth
score: 0
type: Comment

http://stackoverflow.com/q/49013196
score: 0
tagged with: api
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49014879
tagged with: tkinter
has title: Ùpdate API information regularly in python desktop widget
has body: I have been doing a beginner python desktop application with tkinter. I am pulling information via API and want this information to be updated every 10 second. Sadly I could not make it work via threading and sleep function. Any suggestions? from tkinter import * import urllib.request import json import threading from tkinter import ttk import time def main(): win = Tk() win.tk_setPalette(background='black', foreground='white') win.title('Crypto Desktop Ticker') win.geometry('250x35') #def getInfo(): url1 = urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/bitcoin/") data1 = json.loads(url1.read()) priceusd = data1[0]['price_usd'] onehourchange = data1[0]['percent_change_1h'] output1 = ("BTC "+priceusd+"USD ("+onehourchange+"%)" ) url2 = urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD") #as url: data2 = json.loads(url2.read()) priceusd = data2[0]['price_usd'] onehourchange = data2[0]['percent_change_1h'] output2 = ("ADA "+priceusd+"USD ("+onehourchange+"%)" ) T = Text(win, height=2, width=100) T.pack() T.insert(END, output1 + '\n' + output2) T.config(state=DISABLED) win.mainloop() time.sleep(10) main() #threading.Timer(10.0, main().start)
type: Question

http://stackoverflow.com/q/48972451
has answer: http://stackoverflow.com/a/48972526
tagged with: python
score: 2
upvote count: 2
tagged with: pandasql
type: Question
has body: I'd like to filter a dataframe based on specifics index. I've read things about query but I don't succeed. Here is the code which create my pivot table. I'd like to filter on specific members df = pd.DataFrame(my_dataframe) table = pd.pivot_table(df,index=["Date","member","Card"], columns=["Type"],values=["Heure"],aggfunc=[len]) #,fill_value=0) table.to_excel(writer, sheet_name='TcD') What should I do ? Thanks
has title: filter pandas data on specific index
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/84949934
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85130096
type: Comment
comment on: http://stackoverflow.com/a/49062253
score: 0
type: AnswerComment
has text: This is correct, but not optimal. It will give you O(N**2) complexity, so it will work slowly for big lists.

http://stackoverflow.com/comment/84944325
type: AnswerComment
has text: @TheClonerx Yeah I just realized that :P
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48969364

http://stackoverflow.com/a/49272928
answers question: http://stackoverflow.com/q/49008961
score: 0
has body: Disclaimer: This is not an answer, I post it as an answer because the original poster asked for it and because it won't fit in a comment, length wise and format wise. Here is the code I run. And I can't reproduce the error. I run on MacOs I am using the provided pdf file. The pdf file is in the same folder as the program. Tried both Python 2.7.13 and 3.6.3 The file is in the same folder at the test.py file. import PyPDF2 as pdf bikeins = open('pdffileproj12.pdf','rb') read_bikeins = pdf.PdfFileReader(bikeins) print(str(read_bikeins)) Here is the output when I run it, with Python 2.7.13 $ python --version Python 2.7.13 $ python test.py &lt;PyPDF2.pdf.PdfFileReader object at 0x101618810&gt; and with Python 3.6.3 $ python3 --version Python 3.6.3 $ python3 test.py &lt;PyPDF2.pdf.PdfFileReader object at 0x110588c88&gt; I do not get any error. Can you check your version of Python?
type: Answer

http://stackoverflow.com/a/49077870
has body: You are passing the "headers" as data? You should use headers instead. headers = {'User-Agent': 'Bot'} requests.get('example.com/params', headers=headers)
has comment: http://stackoverflow.com/comment/85202771
score: 0
answers question: http://stackoverflow.com/q/49077826
type: Answer

http://stackoverflow.com/q/49035086
answer count: 0
score: 0
type: Question
has comment: http://stackoverflow.com/comment/85075341
has body: I am making a project for school and I wanted to insert a python file with a code I'm writing into a picture so that when someone else opens the picture the code will run. My ideas were steganography and write/read but not sure how I can implement them into my solution. any suggestions or ideas are welcomed
tagged with: image
has comment: http://stackoverflow.com/comment/85075333
has title: how to activate a python project through a picture
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49101917
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49101984
tagged with: pandas
has comment: http://stackoverflow.com/comment/85209049
has title: Python/Pandas - How to slice a list up to the first 5 values when some lists might have less than 5 values?
has answer: http://stackoverflow.com/a/49102012
favorite count: 0
has comment: http://stackoverflow.com/comment/85227058
possible better answer: http://stackoverflow.com/a/49102012
tagged with: python
accepted answer: http://stackoverflow.com/a/49101984
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I have the following use case where I have a pandas DataFrame with a column of Series/lists. All of the Series/lists vary in length, but I want to take up to the first 5 elements of this list and set them to their own column. First, I tried just setting a new column up with a slice of the Series/list (e.g. df.full_column.tolist()[:5]), but I get an error: ValueError: Length of values does not match length of index So I basically have two problems: First getting the list of up to 5 from the original column. For further clarification, if there is only 4 in the list, then I want all 4. Taking this list and creating columns off of all of them. Something like value_0, value_1, value_2, value_3, value_4, where if the list didn't have the 4th or 5th, it will set to NaN Thanks!
type: Question

http://stackoverflow.com/a/49038764
score: 16
downvote count: 1
upvote count: 17
has comment: http://stackoverflow.com/comment/135389604
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103772225
has comment: http://stackoverflow.com/comment/103745145
accepted answer of: http://stackoverflow.com/q/49038616
answers question: http://stackoverflow.com/q/49038616
type: Answer
has body: Because you need to invoke the function manually by args.func(args): import argparse def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() command1_parser = subparsers.add_parser('command1') command1_parser.set_defaults(func=command1) command1_parser.add_argument('--name', dest='name') command2_parser = subparsers.add_parser('command2') command2_parser.set_defaults(func=command2) command2_parser.add_argument('--frequency', dest='frequency') args = parser.parse_args() args.func(args) def command1(args): print("command1: %s" % args.name) def command2(args): print("comamnd2: %s" % args.frequency) if __name__ == '__main__': main()

http://stackoverflow.com/comment/85030891
has text: would you explain your code more? the inner b is different from the outer one?
comment on: http://stackoverflow.com/a/49013043
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85050839
comment on: http://stackoverflow.com/a/49022356
has text: select_all() is a function that loops through all the checkboxes and makes sure they are checked
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49054534
has comment: http://stackoverflow.com/comment/85114129
type: Answer
has body: I guess that this module is kept in path where python does not look for when resolving for package. One thing you can do is add path where this folder is kept to PYTHONPATH environment variable so that python can detect it and import won't fail. Execute below command on Linux platform: export PYTHONPATH = $PYTHONPATH:/path/to/module
has comment: http://stackoverflow.com/comment/85114065
score: 0
has comment: http://stackoverflow.com/comment/85114105
answers question: http://stackoverflow.com/q/49053839

http://stackoverflow.com/a/49026888
answers question: http://stackoverflow.com/q/49026751
downvote count: 0
type: Answer
has body: You have to do the looping yourself, Python containers do not support vectorized operations, so something like: [x == pattern for x in my_list]
score: 1
upvote count: 1

http://stackoverflow.com/a/49114097
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/49113585
upvote count: 1
answers question: http://stackoverflow.com/q/49113585
has comment: http://stackoverflow.com/comment/85233327
has body: If you are just interested in applying a conditional filter to your dataframe then you could do the following: df[df.apply(lambda x: x&gt;4) | df.apply(lambda x: x&lt;2)] Then as a second step you can take the average of the columns which fulfilled your conditions: df[df.apply(lambda x: x&gt;4) | df.apply(lambda x: x&lt;2)].mean() This will let you know which columns have met your conditions with what mean.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85233614
has comment: http://stackoverflow.com/comment/85272299

http://stackoverflow.com/a/49101881
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49101761
has comment: http://stackoverflow.com/comment/85209241
has comment: http://stackoverflow.com/comment/85209082
type: AcceptedAnswer
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85209130
has comment: http://stackoverflow.com/comment/85209061
has comment: http://stackoverflow.com/comment/85209151
answers question: http://stackoverflow.com/q/49101761
has body: Since you do not show the code necessary to reproduce your error, for example the application must end in App, and the name of the .kv must be the remaining part of the class in lowercase. Another possible error is that Opening_Screen does not inherit of any kind so it will probably never be called, etc. So I will just provide an example: patientcare.kv ScreenManager Opening_Screen: name: 'Opening_Screen' Options_Screen: name: 'Options_Screen' &lt;Opening_Screen&gt;: BoxLayout: orientation: 'vertical' Label: text: 'Opening_Screen' &lt;Options_Screen&gt;: BoxLayout: orientation: 'vertical' Label: text: 'Options_Screen' main.py from kivy.app import App from kivy.uix.screenmanager import Screen from kivy.clock import Clock class Opening_Screen(Screen): def __init__(self, **kwargs): super(Opening_Screen, self).__init__(**kwargs) Clock.schedule_once(self.change_screen, 5) def change_screen(self, *kwargs): self.manager.current = 'Options_Screen' class Options_Screen(Screen): pass class PatientCareApp(App): pass if __name__ == '__main__': PatientCareApp().run() Update1: As you added more code you just have to map the new class: *.py from kivy.app import App from kivy.uix.screenmanager import Screen from kivy.clock import Clock class Opening_Screen(Screen): def __init__(self, **kwargs): super(Opening_Screen, self).__init__(**kwargs) Clock.schedule_once(self.change_screen, 5) def change_screen(self, *kwargs): self.manager.current = 'Options_Screen' class Patient_Care(App): pass if __name__ == '__main__': Patient_Care().run() *.kv #:import C kivy.utils.get_color_from_hex #:import RiseInTransition kivy.uix.screenmanager.RiseInTransition &lt;Opening_Screen&gt;: ScreenManager: transition: RiseInTransition() Opening_Screen: name: 'Opening_Screen' [...] Update2: If you do not want to implement it in a Screen you can do it in the App. from kivy.app import App from kivy.clock import Clock class Patient_Care(App): def on_start(self): Clock.schedule_once(self.change_screen, 5) def cha…

http://stackoverflow.com/q/49081819
has answer: http://stackoverflow.com/a/49542826
tagged with: python
accepted answer: http://stackoverflow.com/a/49603327
linked to: http://stackoverflow.com/q/17330160
tagged with: properties
has body: I was looking at how Python implements the property descriptor internally. According to the docs property() is implemented in terms of the descriptor protocol, reproducing it here for convenience: class Property(object): "Emulate PyProperty_Type() in Objects/descrobject.c" def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None: doc = fget.__doc__ self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute") return self.fget(obj) def __set__(self, obj, value): if self.fset is None: raise AttributeError("can't set attribute") self.fset(obj, value) def __delete__(self, obj): if self.fdel is None: raise AttributeError("can't delete attribute") self.fdel(obj) def getter(self, fget): return type(self)(fget, self.fset, self.fdel, self.__doc__) def setter(self, fset): return type(self)(self.fget, fset, self.fdel, self.__doc__) def deleter(self, fdel): return type(self)(self.fget, self.fset, fdel, self.__doc__) My question is: why aren't the last three methods implemented as follows: def getter(self, fget): self.fget = fget return self def setter(self, fset): self.fset = fset return self def deleter(self, fdel): self.fdel= fdel return self Is there a reason for returing new instances of property, internally pointing to basically the same get and set functions?
type: AnsweredQuestion
tagged with: mutators
possible better answer: http://stackoverflow.com/a/49543055
has answer: http://stackoverflow.com/a/49543055
score: 27
type: Question
upvote count: 27
answer count: 3
has answer: http://stackoverflow.com/a/49603327
downvote count: 0
has title: Python property descriptor design: why copy rather than mutate?
tagged with: inheritance
favorite count: 0

http://stackoverflow.com/q/48973202
has comment: http://stackoverflow.com/comment/84951360
upvote count: 4
tagged with: char
duplicate of: http://stackoverflow.com/q/12218796
answer count: 1
tagged with: string
linked to: http://stackoverflow.com/q/12218796
favorite count: 0
has body: I want to enter a word from keyboard, put it in a string variable and return first and last letter from the word. But I don't know to to do this. input: "Hello" output: "H", "o" P.S: I want to put this 2 letters in a variable: print(first) output:"H" print(last) output:"o" Please give me a solution!
has title: How to get first char of string in python?
has comment: http://stackoverflow.com/comment/84951367
downvote count: 8
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84951317
has answer: http://stackoverflow.com/a/48973233
has comment: http://stackoverflow.com/comment/84951333
score: -4
type: Question
tagged with: cpu-word

http://stackoverflow.com/q/48981967
has body: I am trying hackers rank to improve my python skills. I have picked a problem.I am able to solve this but I am not getting right output in all the scenarios. Below is the scenario Link to problem is this https://www.hackerrank.com/challenges/maximize-it/problem Below is my code import math import sys lis= sys.stdin.readlines() def newFunc(lis): numLines = lis[0].split(" ")[0] divisor = lis[0].split(" ")[1] iter = 1 newLis = [] while(int(numLines) &gt;= int(iter)) : paramNum = lis[iter].split(" ")[0] iter1 = 1 bigNum = 0 while(int(paramNum) &gt;= int(iter1)): if int(lis[iter].split(" ")[iter1]) &gt; bigNum: bigNum = int(lis[iter].split(" ")[iter1]) iter1 = iter1 + 1 newLis.append(bigNum) iter = iter + 1 sum = 0 for num in newLis: sum = sum + math.pow(num,2) finalNum = sum % int(divisor) return finalNum value = newFunc(lis) print int(value) When I am testing my code against below output 5 84 1 765952241 3 289380515 265118103 309882974 2 747649220 587740446 2 682866882 596381508 1 342723101 Expected output is 83 Actual I am getting is 48 I don't know why. Can somebody help me with this
answer count: 1
has answer: http://stackoverflow.com/a/48982095
tagged with: python
accepted answer: http://stackoverflow.com/a/48982095
type: AnsweredQuestion
has title: Finding squares of big numbers in python using math.pow
has comment: http://stackoverflow.com/comment/84969233
score: 0
type: Question
tagged with: math
has comment: http://stackoverflow.com/comment/84971218

http://stackoverflow.com/comment/130969994
score: 0
type: AnswerComment
has text: Note: Delegation can only be preformed on google workspace accounts, not on standard google account.
comment on: http://stackoverflow.com/a/68585923
type: Comment

http://stackoverflow.com/comment/84966323
has text: I don't really understand how I can have the words and values go separately into the dict.
score: 0
comment on: http://stackoverflow.com/a/48980381
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85231218
comment on: http://stackoverflow.com/a/49108810
has text: @HG123 If this solved your problem, you can accept an answer as the "correct" answer by clicking the check-mark on th left of it. Once you have earned enough reputation (15, which you will actually have after accepting an answer), you can also up-vote answers you found useful.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85048812
has text: When you compare `"dog" == "True"`, you are also comparing the type of these objects and not just their bool value.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49021823

http://stackoverflow.com/q/49062669
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/85130694
favorite count: 0
has comment: http://stackoverflow.com/comment/85131016
accepted answer: http://stackoverflow.com/a/49063052
has comment: http://stackoverflow.com/comment/85130654
has title: How to group Pandas DataFrame dates into custom date range bins using groupby/cut
has comment: http://stackoverflow.com/comment/85130896
score: 6
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49063052
has comment: http://stackoverflow.com/comment/85130551
linked to: http://stackoverflow.com/q/46525786
type: Question
has comment: http://stackoverflow.com/comment/85143662
upvote count: 6
linked to: http://stackoverflow.com/q/43500894
has body: I am trying to group dates with a custom range using groupby and cut with no success so far. From the error message being returned, I wonder if cut is trying to process my dates as a number. I want to group df1['date'] by custom date ranges and then sum the df1['HDD'] values. The custom ranges are found in df2: import pandas as pd df1 = pd.DataFrame( {'date': ['2/1/2015', '3/2/2015', '3/3/2015', '3/4/2015','4/17/2015','5/12/2015'], 'HDD' : ['7.5','8','5','23','11','55']}) HDD date 0 7.5 2/1/2015 1 8 3/2/2015 2 5 3/3/2015 3 23 3/4/2015 4 11 4/17/2015 5 55 5/12/2015 df2 has the custom date ranges: df2 = pd.DataFrame( {'Period': ['One','Two','Three','Four'], 'Start Dates': ['1/1/2015','2/15/2015','3/14/2015','4/14/2015'], 'End Dates' : ['2/14/2015','3/13/2015','4/13/2015','5/10/2015']}) Period Start Dates End Dates 0 One 1/1/2015 2/14/2015 1 Two 2/15/2015 3/13/2015 2 Three 3/14/2015 4/13/2015 3 Four 4/14/2015 5/10/2015 My Desired output is to group df1 by the custom date ranges and aggregate the HDD values for each Period. Should output something like this: Period HDD 0 One 7.5 1 Two 36 2 Three 0 3 Four 11 Here is one example of what I have tried to use custom grouping: df3 = df1.groupby(pd.cut(df1['date'], df2['Start Dates'])).agg({'HDD': sum}) ...and here is the error I get: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-103-55ea779bcd73&gt; in &lt;module&gt;() ----&gt; 1 df3 = df1.groupby(pd.cut(df1['date'], df2['Start Dates'])).agg({'HDD': sum}) /opt/conda/lib/python3.5/site-packages/pandas/tools/tile.py in cut(x, bins, right, labels, retbins, precision, include_lowest) 112 else: 113 bins = np.asarray(bins) --&gt; 114 if (np.diff(bins) &lt; 0).any(): 115 raise ValueError('bins must increase monotonically.') 116 /opt/conda/lib/python3.5/site-packages/numpy/lib/function_base.py in diff(a, n, axis) 1576 return diff(a[slice1]-a[slice2], n-1, axis=axis) 1577 else: -&gt; 1578 retur…

http://stackoverflow.com/comment/84963585
has text: can I use something else like pickle
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48979246

http://stackoverflow.com/comment/85136578
comment on: http://stackoverflow.com/a/49048501
type: AnswerComment
score: 0
has text: I think you should make clear which language your answer's first sentence refers to.
type: Comment

http://stackoverflow.com/a/49045712
type: Answer
has comment: http://stackoverflow.com/comment/85216835
score: 1
accepted answer of: http://stackoverflow.com/q/49044980
has body: Simply convert your image to an 128x128 numpy array with values between 0 and 1. Then: image = Variable(torch.from_numpy(image))[None, :, :] classification = model(image) classification is then a pytorch Variable containing probabilities of belonging to each class.
has comment: http://stackoverflow.com/comment/85135689
answers question: http://stackoverflow.com/q/49044980
has comment: http://stackoverflow.com/comment/85216867
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85135642
has comment: http://stackoverflow.com/comment/85168147
upvote count: 1
has comment: http://stackoverflow.com/comment/85121261
downvote count: 0

http://stackoverflow.com/comment/85049366
type: AnswerComment
score: 0
type: Comment
has text: Also, standard `==` is not testing type explicitly. Different numeric types are comparable, `set` can be compared to `frozenset`, many bytes-like types compare to each other as expected, etc. Don't bring in the explicit type checking of JS's `===` here, it just confuses the matter.
comment on: http://stackoverflow.com/a/49021934

multi-gpu
type: Tag
tag name: multi-gpu
tags question: http://stackoverflow.com/q/49081129

http://stackoverflow.com/comment/84961273
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48977380
type: AnswerComment
has text: Accept the answer if it helps you

http://stackoverflow.com/a/49112389
has comment: http://stackoverflow.com/comment/85230794
answers question: http://stackoverflow.com/q/49112231
has comment: http://stackoverflow.com/comment/116464874
score: 5
type: AcceptedAnswer
has body: If you're really just looking for a faster way to do this, pandas has such methods built-in, and pretty well optimized! Take the following code for example: import numpy as np import pandas as pd # This is just to generate a dictionary with 1000 values: data_dict = {'value':[i for i in np.random.randn(1000)]} # This is to translate dict to dataframe, and then same it df = pd.DataFrame(data_dict) df.to_csv('test.csv') Takes about 0.008 seconds to write the dictionary to a dataframe and write the dataframe to a csv on my machine
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85231588
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49112231

http://stackoverflow.com/comment/85225610
has text: @Tom1416 You should add it to your project the same way you added the `selenium` package.
comment on: http://stackoverflow.com/a/49098982
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/67871071
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49007292
has body: I needed to remove the Visible only for this project flag from the Deployment configuration that was attached to the remote interpreter. Then I invalidated the cache and restarted as suggested by the other answer.
type: Answer

http://stackoverflow.com/comment/85089497
type: Comment
comment on: http://stackoverflow.com/q/49042076
score: 0
has text: whats the problem ?
type: QuestionComment

http://stackoverflow.com/comment/85043846
has text: A list would be more appropriate, don't you think? The names are useless, Natch gave names because he's a beginner and maybe doesn't know about Python datastructures.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49018494

http://stackoverflow.com/q/48986997
has title: Unable to get complete data using pyserial when compared to logs from putty
type: UnansweredQuestion
has body: I am looking for options to collect serial log using python. Tried the pyserial module but I get incomplete logs when compare to logs collected using putty Below is code that I am using. def getSerialLogs(comport, fileName='SerialLog.txt', baudrate=115200): ser = serial.Serial(comport, baudrate, xonxoff =True, timeout=20) sio = io.TextIOWrapper( io.BufferedRWPair(ser, ser, 100) ) with open(fileName, 'a') as f: while ser.isOpen(): datastring = sio.readline() f.write(datastring) These logs are collected during android device boot.
tagged with: pyserial
answer count: 0
has comment: http://stackoverflow.com/comment/85057762
tagged with: python-2.7
type: Question
has comment: http://stackoverflow.com/comment/85057187
tagged with: python
has comment: http://stackoverflow.com/comment/84979030
score: 0

http://stackoverflow.com/a/49087568
has comment: http://stackoverflow.com/comment/85180993
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49087282
has comment: http://stackoverflow.com/comment/85180885
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85181122
has body: ints = [] for x in amount: if 'million' in x: ints.append(int(float(x.split()[0]) * 10**6)) elif ',' in x: ints.append(int(x.replace(',',''))) else: ints.append(0) Output: [60000000, 1000000, 0, 1150000, 1000000, 0, 2480000, 0, 0, 75000000, 1250000, 3000000, 67000, 4000000, 0, 63000000, 5900000, 170000, 5000000, 22000000, 15750000, 36500000, 0, 0, 0, 19900000, 0] Code demo
answers question: http://stackoverflow.com/q/49087282
type: AcceptedAnswer

django
tags question: http://stackoverflow.com/q/49082214
tags question: http://stackoverflow.com/q/49098458
tags question: http://stackoverflow.com/q/48981145
tags question: http://stackoverflow.com/q/49037998
tags question: http://stackoverflow.com/q/49108697
tags question: http://stackoverflow.com/q/48992253
tags question: http://stackoverflow.com/q/49068613
tags question: http://stackoverflow.com/q/49098953
tags question: http://stackoverflow.com/q/49007469
tags question: http://stackoverflow.com/q/48968097
tags question: http://stackoverflow.com/q/49078340
tags question: http://stackoverflow.com/q/48973318
tags question: http://stackoverflow.com/q/49032171
tags question: http://stackoverflow.com/q/49058127
tags question: http://stackoverflow.com/q/49097426
tags question: http://stackoverflow.com/q/49116926
tags question: http://stackoverflow.com/q/49082196
tags question: http://stackoverflow.com/q/49097487
tags question: http://stackoverflow.com/q/49008630
tags question: http://stackoverflow.com/q/48997218
tags question: http://stackoverflow.com/q/49029196
tags question: http://stackoverflow.com/q/49013133
tags question: http://stackoverflow.com/q/49099308
tags question: http://stackoverflow.com/q/49058790
tags question: http://stackoverflow.com/q/49055367
tags question: http://stackoverflow.com/q/49108331
tags question: http://stackoverflow.com/q/49062058
tags question: http://stackoverflow.com/q/48973855
tags question: http://stackoverflow.com/q/49112945
tags question: http://stackoverflow.com/q/48972216
tags question: http://stackoverflow.com/q/49024212
tags question: http://stackoverflow.com/q/49070023
tags question: http://stackoverflow.com/q/48971517
tags question: http://stackoverflow.com/q/49042185
tags question: http://stackoverflow.com/q/48996067
tags question: http://stackoverflow.com/q/49003144
type: Tag
tags question: http://stackoverflow.com/q/49042381
tags question: http://stackoverflow.com/q/49113839
tags question: http://stackoverflow.com/q/48995735
tags question: http://stackoverflow.com/q/49018026
tags question: http://stackoverflow.com/q/49004046
tags question: http://stackoverflow.com/q/48966032
tags question: http://stackoverflow.com/q/49101128
tags question: http://stackoverflow.com/q/49099193
tags question: http://stackoverflow.com/q/48968742
tags question: http://stackoverflow.com/q/49050108
tags question: http://stackoverflow.com/q/48985145
tags question: http://stackoverflow.com/q/49040807
tags question: http://stackoverflow.com/q/49091870
tags question: http://stackoverflow.com/q/48976705
tags question: http://stackoverflow.com/q/48972677
tags question: http://stackoverflow.com/q/49093286
tags question: http://stackoverflow.com/q/48979757
tags question: http://stackoverflow.com/q/49055570
tags question: http://stackoverflow.com/q/49089158
tags question: http://stackoverflow.com/q/49058831
tags question: http://stackoverflow.com/q/49060790
tags question: http://stackoverflow.com/q/48983144
tags question: http://stackoverflow.com/q/49012844
tags question: http://stackoverflow.com/q/48990427
tags question: http://stackoverflow.com/q/49109884
tags question: http://stackoverflow.com/q/49115242
tags question: http://stackoverflow.com/q/49026356
tags question: http://stackoverflow.com/q/48969623
tags question: http://stackoverflow.com/q/49115909
tags question: http://stackoverflow.com/q/49010952
tags question: http://stackoverflow.com/q/49094482
tags question: http://stackoverflow.com/q/48994701
tags question: http://stackoverflow.com/q/49034094
tags question: http://stackoverflow.com/q/48978976
tags question: http://stackoverflow.com/q/49013884
tags question: http://stackoverflow.com/q/49108090
tags question: http://stackoverflow.com/q/49017297
tags question: http://stackoverflow.com/q/49013956
tags question: http://stackoverflow.com/q/49115298
tags question: http://stackoverflow.com/q/49045348
tags question: http://stackoverflow.com/q/49005247
tags question: http://stackoverflow.com/q/49112365
tags question: http://stackoverflow.com/q/49096810

http://stackoverflow.com/a/48968428
has comment: http://stackoverflow.com/comment/84942448
has comment: http://stackoverflow.com/comment/84943073
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48968376
has comment: http://stackoverflow.com/comment/84943061
score: 0
has comment: http://stackoverflow.com/comment/84943084
has comment: http://stackoverflow.com/comment/84943048
has comment: http://stackoverflow.com/comment/84942398
has comment: http://stackoverflow.com/comment/84942594
has comment: http://stackoverflow.com/comment/84942982
type: Answer
has body: Check for existance using the in operator and have some value for item. Right now your code is checking to see if an element of business_name is equal tobusiness_name for item in business_name: if item == business_name: break To: if 'somevaluehere' in business_names: break
has comment: http://stackoverflow.com/comment/84942469

http://stackoverflow.com/a/49079851
score: 0
has body: Ok after doing a lot of experimenting I found a solution, although it's quite unelegant. def generic_eval_add(self, first, second): my_locals = { 'self': self } string_code = """def real_operation(): self.{0} = self.{0} + self.{1}""".format(first, second) print(string_code) exec(string_code, my_locals) return my_locals['real_operation'] Since this can be evaluated at initialization, it makes exactly what I needed. The big trade offs are elegance, readability, error handling, etc. Y think Paul Cornelius solution is good enough for this use case. Although I may consider jinja templating for generating python code Thanks for you help.
type: Answer
answers question: http://stackoverflow.com/q/49078780

http://stackoverflow.com/a/49102443
answers question: http://stackoverflow.com/q/49101978
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85210213
has body: import os import sys def this_file(): print(os.path.realpath(__file__)) def that_file(): print(os.getcwd() + "/" + sys.argv[0]) I think this is what you're looking for.

http://stackoverflow.com/q/49068622
has comment: http://stackoverflow.com/comment/85424104
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85177799
favorite count: 0
tagged with: geometry
type: UnansweredQuestion
tagged with: computational-geometry
has body: Given a list of paths(with start and end coordinates) that are only horizontal and vertical, how can I find all the rectangles that they form? Details: The end points of the rectangle must be end-points of their constituent edges. i.e rectangles formed from the intersections of lines are not needed. The x,y of start and end, represented as complex numbers of each line is given. The output should be four lines representing each edge of the rectangle This is my naive implementation which is too slow. Are there any other approaches? def find_rectangles(paths): vertical_paths = filter(lambda path: is_vertical(path), paths) horizontal_paths = filter(lambda path: is_horizontal(path), paths) vertical_paths.sort(key=lambda path: path.start.imag, reverse=True) horizontal_paths.sort(key=lambda path: path.start.real) h_pairs = [] for i in range(0, len(horizontal_paths) - 1): for j in range(1, len(horizontal_paths)): if horizontal_paths[i].start.real == horizontal_paths[j].start.real and horizontal_paths[i].end.real == horizontal_paths[j].end.real: h_pairs.append((horizontal_paths[i], horizontal_paths[j])) v_pairs = [] for i in range(0, len(vertical_paths) - 1): for j in range(1, len(vertical_paths)): if vertical_paths[i].start.imag == vertical_paths[j].start.imag and vertical_paths[i].end.imag == vertical_paths[j].end.imag: v_pairs.append((vertical_paths[i], vertical_paths[j])) rects = [] for h1, h2 in h_pairs: for v1, v2 in v_pairs: if h1.start == v1.start and v1.end == h2.start and h1.end == v2.start and h2.end == v2.end: rects.append(Rect(h1.start, h1.end, h2.end, h2.start)) return rects Edit:(Improvements from all suggestions) Main difference is I am storing all horizontal edges' end-points in a set so look up for them is O(1): def find_rectangles(paths): vertical_paths = [path for path in paths if is_vertical(path)] horizontal_paths_set = set([(path.start, path.end) for path in paths if is_horizontal(path)]) vertical_paths.sort(key=lambda pair: path.start.imag, reverse=Tr…
tagged with: python
has answer: http://stackoverflow.com/a/49070196
has comment: http://stackoverflow.com/comment/85144161
has comment: http://stackoverflow.com/comment/85142538
has comment: http://stackoverflow.com/comment/85154859
has comment: http://stackoverflow.com/comment/85176829
score: 1
type: Question
tagged with: algorithm
tagged with: rectangles
has comment: http://stackoverflow.com/comment/85153827
has title: Efficient algorithm to find rectangles from lines?
upvote count: 2
has comment: http://stackoverflow.com/comment/85142467

http://stackoverflow.com/comment/85110362
type: Comment
has text: @Steven there can be multiple layers, so the loop is to calculate the raw prediction thing for Multilayer Perceptron which isn't provided by default. The activation functions are different for different layers, I've implemented them accordingly
type: QuestionComment
comment on: http://stackoverflow.com/q/49051910
score: 0

http://stackoverflow.com/q/49046909
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/49047005
tagged with: python
has title: Access data frames elements pyspark in jupyter
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49047005
tagged with: dataframe
type: Question
tagged with: pyspark
answer count: 1
has body: I am new in spark and pyspark. My DataFrame is composed of several columns and Inside some columns, the is arrays or sub dataframes. the printSchema of the df is in the image below My question is how can I access the elements such as the "role" the "member" Thank you for your help
score: 0

http://stackoverflow.com/comment/84963113
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48978916
has text: The whitespace on the post is for visual reasons. the response comes without whitespace on my code.
type: AnswerComment

http://stackoverflow.com/comment/84988652
comment on: http://stackoverflow.com/q/48991850
has text: cross site dupe: https://unix.stackexchange.com/questions/337819/how-to-export-variable-for-use-with-sudo. Use `sudo -E` to propagate variables
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49026457
answers question: http://stackoverflow.com/q/49014697
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: Here is a simple paginator that splits the query execution into paginated queries. from itertools import count class PaginatedCursor(object): def __init__(self, cur, limit=100): self.cur = cur self.limit = limit self.count = cur.count() def __iter__(self): skipper = count(start=0, step=self.limit) for skip in skipper: if skip &gt;= self.count: break for document in self.cur.skip(skip).limit(self.limit): yield document self.cur.rewind() ... cur = collection.find({'is_timeline_valid': True}) ... for doc in PaginatedCursor(cur, limit=100): ...

http://stackoverflow.com/a/49087042
type: Answer
accepted answer of: http://stackoverflow.com/q/49086900
score: 1
upvote count: 1
has body: Here is one way: lst = ["8_19_dm12_file", "3_19_dm14_file", "8_19_dm9_file", "2_19_dm1_file", "3_19_dm2_file"] def orderer(x): s = x.split('_') return list(map(int, s[:2])) + [int(s[2][2:])] lst_sorted = sorted(lst, key=orderer) # ['2_19_dm1_file', '3_19_dm2_file', '3_19_dm14_file', '8_19_dm9_file', '8_19_dm12_file']
has comment: http://stackoverflow.com/comment/85179777
answers question: http://stackoverflow.com/q/49086900
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85113223
has text: I still get an error "You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [batch,height,width,depth]" After batching the dataset it returns [?,height,width,depth] with the question mark "?" in place of the batch size.
score: 0
comment on: http://stackoverflow.com/q/49053569
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48993918
downvote count: 0
possible better answer: http://stackoverflow.com/a/57109015
answer count: 3
has answer: http://stackoverflow.com/a/57109015
has answer: http://stackoverflow.com/a/50252419
tagged with: arff
favorite count: 0
accepted answer: http://stackoverflow.com/a/50252419
tagged with: python
has body: I am trying to export a pandas dataframe to .arff file to use it in Weka. I have seen that the module liac-arff can be used for that purpose. Going on the documentation here it seems I have to use arff.dump(obj,fp) Though, I am struggling with obj ( a dictionary) I'm guessing I have to create this by myself. How do you suggest me to do that properly? in a big dataset (3 000 000 lines and 95 columns) is there any example you can provide me to export from pandas dataframe to .arff file using python (v 2.7)?
has answer: http://stackoverflow.com/a/68817333
type: AnsweredQuestion
upvote count: 5
type: Question
has title: exporting dataframe to arff file python
score: 5

http://stackoverflow.com/a/49108372
has body: You can build a Trie data structure for the list of words with the end nodes containing the index of the points array. From WikipediaA trie structure for the input = ["A","to", "tea", "ted", "ten", "i", "in", and "inn"] would look like this By Booyabazooka (based on PNG image by Deco). Modifications by Superm401. - own work (based on PNG image by Deco), Public Domain, Link So we can run through the entire length of the input string and every time we encounter a end of word node add it's points and move on. So the search for the entire word can be done in linear time. But in case of overlapping list items like ["ab", "cd", "abcd"], with points [3, 4, 1] and the word was abcd. The we will not be able to have a linear time solution after pre-processing because after every time we encounter a end of word the max points can come from either. Extending the string so far word and looking further ahead. Starting to look for remaining string as an individual word from the list. Time and space complexity to build the Trie structure : O(w * m) where w is the amount of words and m is the max size of the word in the list. Search can be done in O(m) where m is the length of the word being searched for.
answers question: http://stackoverflow.com/q/49107491
has comment: http://stackoverflow.com/comment/85221606
has comment: http://stackoverflow.com/comment/85223247
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/48973777
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/48997875
favorite count: 0
tagged with: python
tagged with: edge-detection
downvote count: 2
has comment: http://stackoverflow.com/comment/84952676
type: Question
tagged with: opencv
type: AnsweredQuestion
has body: I have a number of lobster images as shown in the photo. My goal is to identify the edge between the carapace and the body and its coordinates. However, it seems like the methods of finding contours based on HSV thresholds or Canny edge detection output didn't work well when I applied to these images. My idea is to find a way to 'amplify' the color difference between two areas of an image to make it easier for finding mask/contours based on color threshold? For example, if I can make the yellow of the edge in the image stronger, then I can easily find the mask of this area using color threshold, can we do that? Thanks.
has title: Increase the degree of a specific color range in an image for object detection
has answer: http://stackoverflow.com/a/48997875
tagged with: contour
has comment: http://stackoverflow.com/comment/84953328
upvote count: 0

http://stackoverflow.com/q/48977652
score: -3
tagged with: python
has title: Rounding to 2 decimal places in Python
has comment: http://stackoverflow.com/comment/84960744
answer count: 4
has answer: http://stackoverflow.com/a/48978094
has answer: http://stackoverflow.com/a/48977919
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48978112
has answer: http://stackoverflow.com/a/48979811
has comment: http://stackoverflow.com/comment/84960751
downvote count: 4
has comment: http://stackoverflow.com/comment/84960509
has comment: http://stackoverflow.com/comment/84961193
has body: This isn't a duplicate because I have checked everything before this post on this site. I think I have managed to do the first two bullet points. The first one I will do through a string but I am willing to change that if you know another way. The 2nd one is using comma seperators for the $'s. So I will use a float but once again am willing to change if better way is found. But I am stuck. And the "print("%.2f") % str) is something I found but I need work on rounding to two decimal spaces and the last bullet point. Code: import random def random_number(): random_dollars = random.uniform(1.00, 10000.00) print(round(random_dollars, 2)) print("%.2f") % str print(random_number()) Shell: C:\Users\jacke\PycharmProjects\ASLevelHomeworkWeek18\venv\Scripts\python.exe C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py 6567.62 Traceback (most recent call last): %.2f File C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py", line 10, in &lt;module&gt; print(random_number()) File C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py", line 7, in random_number print("%.2f") % str TypeError: unsupported operand type(s) for %: 'NoneType' and 'type' Process finished with exit code 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84947945
comment on: http://stackoverflow.com/q/48971247
has text: yup it solved the problem.......thnx a lot mate!!!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84998571
type: AnswerComment
has text: I'm using matplotlib 2.2 while the answer to the other question uses earlier versions and needs to put `numticks=12` as well. Possibly that changed in between versions.
type: Comment
comment on: http://stackoverflow.com/a/48994101
score: 0

http://stackoverflow.com/a/48985704
answers question: http://stackoverflow.com/q/48985667
has body: import glob files = glob.glob("*VEGETATION*") should do the trick. It should find all files in the current directory that contain "VEGETATION" somewhere in the filename
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/49101902
favorite count: 0
has comment: http://stackoverflow.com/comment/85209033
tagged with: python
has comment: http://stackoverflow.com/comment/85208988
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/85209008
type: Question
has answer: http://stackoverflow.com/a/49101916
has body: I'm trying to print the stack but I'm getting this instead: str_i += e[0] + "\t" + e[1] + "\n" TypeError: unsupported operand type(s) for +: 'int' and 'str' How can I get the stack to print? def __str__(self): str_i = 0 for e in self.items: str_i += e[0] + "\t" + e[1] + "\n" return str_i s1 = Stack_2Queues() s1.push(903, 12) s1.push(767, 13) s1.push(950, 14) print(s1)
upvote count: 0
score: -2
has title: str_i += e[0] + "\t" + e[1] + "\n"
answer count: 1

http://stackoverflow.com/q/49090811
has body: I have a piece of code that looks something like this: loc2 = {} with open('loc.txt') as filename: for line in filename: a = line.strip() if a.replace('.','',1).isdigit(): loc2[float(a[0])] = a[1:] return loc2 in which I need to check if a number [which is always at the start of the line in file loc.txt, and always alone on the entire line] that can be either a negative, an int or a float, and add it to a dictionary as a key. Could someone help me out please? Not sure how to approach this. I tried replacing the '.' with empty space, but it didn't work, and also didn't fix my negative numbers problem, obviously. I'm a noob in python still. Thanks! example of loc.txt: 1 stuff 1.1 stuff -4 stuff where stuff is things that will be added to the dictionary as values later on.
has comment: http://stackoverflow.com/comment/85187391
tagged with: python
has comment: http://stackoverflow.com/comment/85187223
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85187700
has answer: http://stackoverflow.com/a/49090892
type: Question
has comment: http://stackoverflow.com/comment/85187701
has comment: http://stackoverflow.com/comment/85187515
has comment: http://stackoverflow.com/comment/85187705
has title: How do I check if a string starts with a negative number and a float? [python]
score: 0
accepted answer: http://stackoverflow.com/a/49090892
answer count: 1
has comment: http://stackoverflow.com/comment/85187716
has comment: http://stackoverflow.com/comment/85187214

http://stackoverflow.com/q/49019517
type: Question
has comment: http://stackoverflow.com/comment/93984511
has comment: http://stackoverflow.com/comment/93770411
has body: I'm using Python's curses-menu package and understand how to make submenus in a menu when the menu is statically defined before .show() is called. I am trying to make a menu item which, when selected, will dynamically make the selected submenu's items. In other words, when I select an item, I want run code to, say, take some user input, and make something like a SelectMenu with each string as an item. Lastly, I then want to use the selected string as input to a function. Here's what I'm trying: # Import the necessary packages from cursesmenu import * from cursesmenu.items import * def work_with_selection(selection): print('You selected {}'.format(selection)) def build_sub(): items = [] for i in range(3): item = input('Type an item: ') items.append(item) selection = SelectionMenu(items).get_selection(items) work_with_selection(selection) # Create the menu menu = CursesMenu("Title", "Subtitle") # Create some items # Dynamically build submenu build_item = FunctionItem("Build dynamic submenu", build_sub) menu.append_item(build_item) # Finally, we call show to show the menu and allow the user to interact menu.show() It appears to work except that once I chose Exit from the submenu, the parent menu redraws, and the cursor keys stop working. Instead of moving the selector, it give control-characters with letters as in the top left of this: ^[[B^[[A^[[B───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ │ │ Title │ │ │ │ Subtitle │ │ 1 - Build dynamic submenu │ │ 2 - Exit │ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ │ 4 - Exit │ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ I'm using Python 3. Is using SelectionMenu the right way to go? If so, how do I fix the parent main menu once I return to it? If not, h…
score: 0
has comment: http://stackoverflow.com/comment/93879592
tagged with: python
tagged with: curses
tagged with: menu
answer count: 0
type: UnansweredQuestion
has title: Dynamic submenu items with cursesmenu

http://stackoverflow.com/a/49074158
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49074117
has body: def two_length_run(n): i = 0 while i &lt; len(n): if len(n) &gt;= 2: if (i + 1 &lt; len( n )) and ( n[i] == n[i + 1]) and (n[i + 1] &lt;= len(n)): return True else: i = i + 1 else: return False The inner if condition may overflow due to i + 1 when i = len( n ) - 1, so add a check there.

http://stackoverflow.com/comment/85044828
comment on: http://stackoverflow.com/q/49019724
has text: I have used regex by basic parsing of the expression but that doesnt give you the flexibility of adding more complex expressions and the code is really not maintainable.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48980696
has body: I am new to Python and the 'import' in Python is confusing me. It seems that it sometimes imports functions in the module recursively and sometimes doesn't. For example, if I do import numpy then I can use all the functions in numpy, including the functions in the 'sub-modules' (not sure if it is a proper name), such as a = numpy.fft.fft2(b) c = numpy.random.rand() However, if I do import skimage I can not use functions in the 'sub-modules' of skimage, such as skimage.color.rgb2gray() skimage.transform.resize() I have to import the 'sub-modules' explicitly as from skimage import color from skimage import transform So how to know whether import will work recursively for a module? And why does Python not make it consistent for all modules?
type: Question
has answer: http://stackoverflow.com/a/48980863
accepted answer: http://stackoverflow.com/a/48980863
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: When does 'import' work recursively in Python

http://stackoverflow.com/comment/84988754
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48968488
has text: I tried this, it gave me a empty column called count.
score: 0

http://stackoverflow.com/comment/85128555
type: AnswerComment
has text: Thanks! I completely forgot that it took input as a string and that even if it was a number that it would still be a string.
comment on: http://stackoverflow.com/a/49060291
type: Comment
score: 1

http://stackoverflow.com/a/48995262
has body: Here is one way: import pandas as pd, numpy as np df = pd.DataFrame({'col1': [[[1,2,3,4,5,5]], [[3,4,5,6,7,8]], [[2,3,4,1,2,1]]]}) df = pd.DataFrame(np.array([x[0] for x in df['col1'].values]), columns=['col'+str(i) for i in range(1, 7)]) # col1 col2 col3 col4 col5 col6 # 0 1 2 3 4 5 5 # 1 3 4 5 6 7 8 # 2 2 3 4 1 2 1
upvote count: 1
answers question: http://stackoverflow.com/q/48995018
score: 1
has comment: http://stackoverflow.com/comment/84996286
downvote count: 0
type: Answer

http://stackoverflow.com/a/49044079
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/49043009
answers question: http://stackoverflow.com/q/49043009
has comment: http://stackoverflow.com/comment/85093187
upvote count: 1
has body: Get the list of all distance from the input, then sort it Tested in Python3 from operator import itemgetter # Use raw_input() with Python 2 lat = float(input("Latitude:")) lon = float(input("Longitude:")) distances = (distance(v['lat'],v['lon'],lat,lon) for v in sdata) for lat_lng, d in sorted(zip(sdata, distances), key=itemgetter(1)): print(lat_lng['lat'], lat_lng['lon'], d) Output Latitude: 0.0 Longitude: 0.0 37.82 86.142 9668.762962674926 40.42 86.123 9679.445101487952 39.66 87.11 9760.193791714297 38.88 87.251 9769.623036766754 39.78 89.336 9950.802415333788 41.35 90.21 10025.072644640604

http://stackoverflow.com/comment/85184285
has text: This is not fast when the rows are plenty. (It is faster but not really fast as you shown.)
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/49089338

http://stackoverflow.com/q/48980344
has comment: http://stackoverflow.com/comment/85070358
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84966062
type: UnansweredQuestion
has title: PyQt4: QTreeView constructor causes crash: QWidget: Must construct a QApplication before a QPaintDevice
has comment: http://stackoverflow.com/comment/84972817
tagged with: python
answer count: 0
has body: I run into a strange behavior, where my QApplication seems not initialize correctly. I have two modules: foo.py and bar.py. bar.py content: module: bar from PyQt4 import QtGui class MyTreeView(QtGui.QTreeView): def __init__(self, name, parent=None): super(MyTreeView, self).__init__(parent) foo.py content: # module: foo from PyQt4 import QtGui import bar class MyDialog(QtGui.QDialog): def __init__(self, name, parent=None): super(MyDialog, self).__init__(parent) self._name = name self.setMinimumSize(500, 200) self.setLayout(QtGui.QHBoxLayout()) self._tree = bar.MyTreeView(name) self.layout().addWidget(self._tree) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) dialog = MyDialog('foo') dialog.exec_() sys.exit(app.exec_()) When running foo.py I get the following error message: QWidget: Must construct a QApplication before a QPaintDevice The debugger stops while calling the QTreeView constructor: super(MyTreeView, self).__init__(parent) What's going wrong here? System: Windows 7 Python: 2.7.9 PyQt: PyQt4 - 4.8.6
type: Question
tagged with: crash
has comment: http://stackoverflow.com/comment/84974707
tagged with: pyside
tagged with: qapplication
score: 0

http://stackoverflow.com/q/49000667
answer count: 2
has body: I have a list like this: $ mylist = [(u'nr',&lt;object&gt;,'string1'),(u'fm',&lt;object&gt;,'string2'),(u'nr',&lt;object&gt;,'string3')] I would like to get the unique values of nrand fm from that list (ie, no repeat ones for that first element). I've been looking at getting unique lists using set() and such, and I tried this (from another thread): $ unique = reduce(lambda l, x: l.append(x) or l if x not in l else l, mylist, []) but that didn't work. Was asked to clarify: I want ['nr','fm'] in the final result
has answer: http://stackoverflow.com/a/49000885
tagged with: python
accepted answer: http://stackoverflow.com/a/49000707
type: AnsweredQuestion
has title: Getting unique values from specific point in a nested list
has answer: http://stackoverflow.com/a/49000707
has comment: http://stackoverflow.com/comment/85006506
type: Question
has comment: http://stackoverflow.com/comment/85006647
has comment: http://stackoverflow.com/comment/85006606
has comment: http://stackoverflow.com/comment/85006532
tagged with: renpy
possible better answer: http://stackoverflow.com/a/49000885
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/48969297
answers question: http://stackoverflow.com/q/48966355
score: 0
has body: Ditch the sleeps, find the element using selenium's WebdriverWait().until along with the visibility_of_element_located or similar Expected Condition. It stops waiting the moment it finds the desired element, and you can catch the TimeoutException if it doesn't find it and raise a nice readable exception so you'll know exactly why your attempt failed, not just tomorrow but years from now. The Timeout and Poll times are all customizable. Each time you find yourself reaching for time.sleep, ask yourself if you are facing the 1% of automation use cases where it is considered the best approach.
type: Answer

http://stackoverflow.com/comment/94093909
comment on: http://stackoverflow.com/a/53559883
has text: I'm not related to the project, I just found your question while looking for how to do the same task. From reading the documentation, it seems that the frontend api is only implemented for the angular context. Other interpreters still can access the methods of the `BaseZeppelinContext` class, where the backend api is implemented.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/120745434
comment on: http://stackoverflow.com/a/59400942
has text: Wouldn't `err.message.split('array ')[1][0]` only work for 1-digit indexes? `int(err.message.split()[-4])` (for python 2) or `int(str(err).split()[-4])` (for python 3) should work for any indexes
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/49115010
has body: I think using list comprehension works fine for you: data = [{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}, {'name': 'Jim','id_str': '03'}] id = ['01','1133', '02', '2222'] out = [d for d in data if d['id_str'] in id] print(out) But if you want a more procedural way this might suite you better: def id_filter(data, id): out = [] for d in data: if d['id_str'] in id: out.append(d) return out print(id_filter(data, id))
answers question: http://stackoverflow.com/q/49114633
score: 0
type: Answer

http://stackoverflow.com/a/49001861
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49001784
accepted answer of: http://stackoverflow.com/q/49001784
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85008765
has body: You can either get the data from the request attribute of the response object, or you can decorate or otherwise modify/extend get or mapto print before executing the rest of the function. I would go with checking the request attribute of the response object.

http://stackoverflow.com/comment/85062949
comment on: http://stackoverflow.com/q/49029309
has text: @Kasramvd floats, specifically `numpy.float32`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84941973
comment on: http://stackoverflow.com/q/48968181
score: 2
has text: How would you do this by hand? Do all of the rows have the person's name and title separated by a comma?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85187591
type: AnswerComment
type: Comment
has text: This works fine for the input dataset you gave in the question.. I'm not sure what your other dataframes look like. Perhaps have a look at [this question](https://stackoverflow.com/questions/45167175/typeerror-cannot-concatenate-a-non-ndframe-object).
comment on: http://stackoverflow.com/a/49024574
score: 0

http://stackoverflow.com/q/49098848
score: 0
tagged with: parsing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85240882
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has body: <Row ss:Index="14"> 10000 S00001 SPI-37-2018 02/26/2018 22 02/26/2018 I want to extract data from the specific ss:StyleId and ss:Index. Can you please suggest a way I tried print(xmlTree.find('.//Cell').attrib['ss:StyleID']), but it shows NoneType has no attrib
has comment: http://stackoverflow.com/comment/85203687
answer count: 0
has comment: http://stackoverflow.com/comment/85202933
type: Question
has title: How to process the below xml that I have using python
linked to: http://stackoverflow.com/q/1912434
has comment: http://stackoverflow.com/comment/85240597

http://stackoverflow.com/comment/85215687
comment on: http://stackoverflow.com/q/49105159
has text: Tomalak is correct, it's just one URL line
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/77181669
type: Answer
has comment: http://stackoverflow.com/comment/136076111
score: 0
answers question: http://stackoverflow.com/q/48967861
has body: The pandas documentation for df.to_excel function shows that you do not have a parameter to specify encoding. So you can try using the df.to_csv function instead and specify the utf8 encoding like below: dataframe.to_csv(csv_buffer, encoding = 'utf8', index = False) Also, I see that you can upgrade your pandas version and it will allow you to specify the encoding parameter as mentioned in this thread.

http://stackoverflow.com/comment/85035057
score: 0
type: Comment
type: QuestionComment
has text: What is 4 and 5 in 1st and 2nd lines? Can you be more specific about your problem statement?
comment on: http://stackoverflow.com/q/49014444

http://stackoverflow.com/q/49086903
has body: Goal: Merge JSON files into one big file Background: I am using the code below taken from here Issue with merging multiple JSON files in Python import json import glob result = [] for f in glob.glob("/Users/EER/Desktop/JSON_Combo/*.json"): with open(f, "rb") as infile: result.append(json.load(infile)) with open("merged_file.json", "wb") as outfile: json.dump(result, outfile) However, I get the following error: JSONDecodeError: Extra data: line 2 column 1 (char 5733) I checked Python json.loads shows ValueError: Extra data and JSONDecodeError: Extra data: line 1 column 228 (char 227) and ValueError: Extra Data error when importing json file using python but they are a bit different. A potential reason for the error seems to be that my .json files are a list of strings but I am not sure Question: Any thoughts on how to fix this error?
linked to: http://stackoverflow.com/q/38474277
linked to: http://stackoverflow.com/q/21058935
type: Question
linked to: http://stackoverflow.com/q/23520542
tagged with: http://stackoverflow.com/tag/json
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/38577399
has title: Merge JSON files JSONDecodeError
has answer: http://stackoverflow.com/a/49087014
has comment: http://stackoverflow.com/comment/85179245
tagged with: glob
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33054527
tagged with: python

http://stackoverflow.com/q/49099816
has comment: http://stackoverflow.com/comment/85205352
upvote count: 0
has title: What data structure is good for maintaining file paths?
has body: I'm working on the "Longest Absolute filepath" problem on LeetCode. This is a simple problem that asks "What is the length of the longest absolute file path in a given directory". And my working solution is as follows. The file directory is given as a string. def lengthLongestPath(self, input): """ :type input: str, the file directory :rtype: int """ current_folder_path = [""] * 40 longest_file_path_size = 0 for item in input.split("\n"): num_tabs = item.count("\t") print num_tabs if "." not in item: current_folder_path[num_tabs] = item.lstrip("\t") else: absolute_file_path = "/".join(current_folder_path[:num_tabs] + [item.lstrip("\t")]) print item print num_tabs, absolute_file_path, current_folder_path longest_file_path_size = max(len(absolute_file_path), longest_file_path_size) return longest_file_path_size This works. However, note that on line current_folder_path = [""] * 40 is very unelegant. This was a line to remember the current file path. I wonder if there is a way to remove this.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85212935
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85206082
has answer: http://stackoverflow.com/a/49101045
has comment: http://stackoverflow.com/comment/85204881
downvote count: 1
has comment: http://stackoverflow.com/comment/85205919
type: Question
tagged with: algorithm
score: -1
has comment: http://stackoverflow.com/comment/85206087

http://stackoverflow.com/q/49047631
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49047758
has body: I am using Python on Windows platform and I need to periodically execute a piece of code every 100ms or lower. For an example: while (packetNumber &lt; 30000): sock.sendto(bytes(MESSAGE, "utf-8"), (SERVER_IP, SERVER_PORT)) packetNumber = packetNumber + 1 print("Sent the", packetNumber, "th packet") I only care about calling time of this line: sock.sendto(bytes(MESSAGE, "utf-8"), (SERVER_IP, SERVER_PORT)) and it needs to be called every 100ms (or as accurate as possible), in periods like: 11:24:07.00000 11:24:07.10000 11:24:07.20000 11:24:07.30000 etc. What is the most accurate method of achieving this?
type: Question
tagged with: udp
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49047758
tagged with: python
has title: Very precise periodic function calls in Python

http://stackoverflow.com/q/48985233
score: 0
has comment: http://stackoverflow.com/comment/84975267
has title: Get complete list of keyword arguments of an object's class
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84975320
has comment: http://stackoverflow.com/comment/84975292
tagged with: python
has comment: http://stackoverflow.com/comment/84975205
has comment: http://stackoverflow.com/comment/84975109
has comment: http://stackoverflow.com/comment/84975098
type: Question
has body: I want to find out the arguments of an object's method. The problem is that the arguments are optional so when I try either of the following, I don't get the required information #1 import inspect import pygraphviz as PG sig = inspect.signature(PG.AGraph.add_node) #2 full_arg = inspect.getfullargspec(PG.AGraph.add_node) # 3 PG.AGraph.add_node.__defaults__ None of the above methods give the result I am looking for. For example, I know for a fact that the add_node function takes in arguments like color,style and others but I don't see them in either of these outputs. Is there a way to get this? PS: The methods I mentioned above come from other SO questions addressing similar issues
has comment: http://stackoverflow.com/comment/84975348

http://stackoverflow.com/a/49038413
has comment: http://stackoverflow.com/comment/85082365
downvote count: 0
has body: By using np.put a=df.index.values a Out[637]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64) np.put(a,a,np.array([1,2,3])) a Out[639]: array([1, 2, 3, 1, 2, 3, 1, 2, 3, 1], dtype=int64) df['New']=a df Out[641]: counter item New 1 1 a 1 2 2 b 2 3 3 c 3 1 1 d 1 2 2 e 2 3 3 f 3 1 1 g 1 2 2 h 2 3 3 i 3 1 1 k 1
upvote count: 2
answers question: http://stackoverflow.com/q/49038164
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85082208
has comment: http://stackoverflow.com/comment/85082258
has comment: http://stackoverflow.com/comment/85082193

http://stackoverflow.com/q/49079461
has comment: http://stackoverflow.com/comment/85164881
possible better answer: http://stackoverflow.com/a/49079502
upvote count: 1
has answer: http://stackoverflow.com/a/49079502
has title: How to get a reference to an object attribute?
tagged with: object
has body: I am looking for a way to alter an objects attribute depending upon a value parsed to a method. For example: class Character(object): def __init__(self, hp, mp, st, ag): self.hp = hp self.mp = mp self.st = st self.ag = ag def increase_stat(self, stat, value): ''' Increase one of the attributes (hp, mp, st, ag) by a given value. ''' stat_dict = {'hp': self.hp, 'mp': self.mp, 'st': self.st, 'ag': self.ag} stat_attr = stat_dict.get(stat) # below should be equivalent to self.hp += value stat_attr += value hero = Character(hp=10, mp=4, st=3, ag=2) hero.increase_stat(stat='hp', value=2) # this should increase the hp by 2 print(hero.hp == 12) I understand this doesn't work as stat_dict.get(stat) returns the value self.hp is pointing to rather than the actual self.hp object. Current Solution Instead of having the attributes as values for the dict, I have methods which increase each individual stat. class Character(object): def __init__(self, hp, mp, st, ag): self.hp = hp self.mp = mp self.st = st self.ag = ag def increase_stat(self, stat, value): ''' Increase one of the attributes (hp, mp, st, ag) by a given value. ''' stat_method_dict = {'hp': self._increase_hp, 'mp': self._increase_mp, 'st': self._increase_st, 'ag': self._increase_ag} alter_stat_method = stat_method_dict.get(stat) alter_stat_method(value) def _increase_hp(self, value): self.hp += value def _increase_mp(self, value): self.mp += value def _increase_st(self, value): self.st += value def _increase_ag(self, value): self.ag = value hero = Character(hp=10, mp=4, st=3, ag=2) hero.increase_stat(stat='hp', value=2) # this should increase the hp by 2 print(hero.hp == 12) My problem with this is it is repetitive and if I decide to add more attributes/stats to the class then this will only increase the number of repetitive methods. I was wondering if there is a better solution to this than what I have produced above? SOLUTION Seems very obvious now. Thanks all. class Character(object): def __init__(self, hp, mp, st, a…
has comment: http://stackoverflow.com/comment/85164884
linked to: http://stackoverflow.com/q/27819819
accepted answer: http://stackoverflow.com/a/49079506
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
score: 1
tagged with: attributes
has answer: http://stackoverflow.com/a/49079506
answer count: 2

http://stackoverflow.com/a/49112053
type: Answer
answers question: http://stackoverflow.com/q/49110675
score: 1
upvote count: 1
has body: Yes, you can use a loop. There's nothing special about tkinter objects that make them any different than any other python object. for col, heading in enumerate(("Name", "Amount", "Date", "Planting #", "batch #")): label = tk.Label(self, text=heading, width=10) label.grid(row=1, column=col)
downvote count: 0

http://stackoverflow.com/comment/84958954
has text: Then what is the type of df1 ?
comment on: http://stackoverflow.com/a/48969825
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85037165
score: 1
type: QuestionComment
has text: why are you trying to write a one liner for while loops ?
type: Comment
comment on: http://stackoverflow.com/q/49016088

turtle-graphics
tags question: http://stackoverflow.com/q/48980691
tags question: http://stackoverflow.com/q/49118920
tags question: http://stackoverflow.com/q/48967114
tags question: http://stackoverflow.com/q/48996361
tags question: http://stackoverflow.com/q/49051781
tag name: turtle-graphics
tags question: http://stackoverflow.com/q/49034728
type: Tag
tags question: http://stackoverflow.com/q/49086447
tags question: http://stackoverflow.com/q/49076949
tags question: http://stackoverflow.com/q/49038809
tags question: http://stackoverflow.com/q/49032070
tags question: http://stackoverflow.com/q/49018345
tags question: http://stackoverflow.com/q/49002427
tags question: http://stackoverflow.com/q/49116608

http://stackoverflow.com/comment/85020311
score: 1
type: AnswerComment
type: Comment
has text: @Dhairya please see buildbot's docs (the link is in my answer). 2.7.11.3 has build step example. At minimum it is a class inherited from steps.BuildStep with run method: class ShowReportStep(steps.BuildStep): @ defer.inlineCallbacks def run(self): // your python code here
comment on: http://stackoverflow.com/a/48988979

http://stackoverflow.com/a/49075158
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49074327
downvote count: 0
has comment: http://stackoverflow.com/comment/85158230
has body: I've installed a long list of Python versions including 3.6.4 to ~/.local. Never had any problem with --prefix. This is the script I use to (re)compile and install: #! /bin/sh prefix="$HOME"/.local [ -f Makefile ] &amp;&amp; make distclean OPT="-DNDEBUG=1 -O3" LDFLAGS="-L$prefix/lib -Xlinker -R$prefix/lib" \ LD_LIBRARY_PATH="`pwd`:$prefix/lib" \ CC="${CC:-gcc}" CPPFLAGS="-DNDEBUG=1 $CPPFLAGS" CFLAGS="-O3 $CFLAGS" \ CXX="${CXX:-g++}" CXXFLAGS="-O3 $CXXFLAGS" LDFLAGS="-s $LDFLAGS" \ ./configure --enable-shared --prefix="$prefix" &amp;&amp; make &amp;&amp; chmod -R a+rX build &amp;&amp; exec make install
upvote count: 2

http://stackoverflow.com/a/48966791
answers question: http://stackoverflow.com/q/48966743
type: Answer
accepted answer of: http://stackoverflow.com/q/48966743
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84941640
type: AcceptedAnswer
has body: You can wait for the child process to terminate. If you want the STDOUT and/or STDERR streams from the subprocess (and/or send data to process' STDIN), use process.communicate method: stdout, stderr = process.communicate() process.returncode will have the exit status. On the other hand, if you just need to wait for the process termination, without any stream capturing, use process.wait method: returncode = process.wait() returncode will contain the exit status of the subprocess. ** Note that, in case of shell=True, the subprocess would be shell itself (unless you exec any command directly).
downvote count: 0

http://stackoverflow.com/comment/85086657
score: 1
type: Comment
type: QuestionComment
has text: Welcome to SO! Please share your existing code so we can assist you better. In addition, please read [mcve].
comment on: http://stackoverflow.com/q/49040575

http://stackoverflow.com/q/49051766
tagged with: python
upvote count: 4
answer count: 0
type: UnansweredQuestion
has body: If I execute command execute "python import sys; print(sys.path)" in vim, I get the following path list: ['/Users/&lt;myuser&gt;/.vim/bundle/python-mode/pymode/libs', '/Users/&lt;myuser&gt;/.vim/bundle/python-mode', '/Users/&lt;myuser&gt;', '/Users/&lt;myuser&gt;/Library/Python/2.7/lib/python/site-packages', '/usr/local/Cellar/python/2.7 .14_3/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/usr/local/Cellar/python/2.7.14_3/Framework s/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/usr/local/Cellar/python/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/usr/local/Cellar/python/2.7.14_3/Framew orks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/usr/local/Cellar/python/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/usr/local/Cellar/pytho n/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/usr/local/Cellar/python/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/usr/local/Cellar/pyt hon/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '_vim_path_'] but if I try it with bpython in shell, I'll get a different list: &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/usr/local/bin', '/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg', '/Library/Python/2.7/site-packages/percol-0.2.1-py2.7.egg', '/Library/Python/2.7/site-packages/cmigemo-0.1.6-py2.7.egg', ' /Library/Python/2.7/site-packages/six-1.11.0-py2.7.egg', '/Library/Python/2.7/site-packages', '/Users/&lt;myuser&gt;', '/Users/&lt;myuser&gt;/Library/Python/2.7/lib/python/site-packages', '/System/Library/Frameworks/Py thon.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darw in', '/System…
downvote count: 1
tagged with: vim
score: 3
has comment: http://stackoverflow.com/comment/85126920
type: Question
tagged with: macvim
has title: Why sys.path inside vim is different with sys.path in shell?
favorite count: 0
has comment: http://stackoverflow.com/comment/85108350

http://stackoverflow.com/q/49094907
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49095541
type: UnansweredQuestion
tagged with: python
has title: GPG : Sorry, no terminal at all requested - can't get input
score: 1
upvote count: 1
tagged with: gnupg
type: Question
has body: Here's as snippet I am using to encrypt a file. import os, gnupg def encrypt(key, src, dst): home = os.path.join(os.getcwd(), "gnupg") gpg = gnupg.GPG(use_agent=True,homedir=home) with open(key, "rb") as f: keys = gpg.import_keys(f.read()) with open(src, "rb") as f: result = gpg.encrypt(f.read(), keys.fingerprints,output=dst) print result.stderr # print result # if not result: # raise RuntimeError(result.status) encrypt('/Users/zone2/Desktop/Script/Playground/key.asc','/Users/zone2/Desktop/Script/Playground/sam.csv','/Users/zone2/Desktop/Script/Playground/res.csv') This currently fails with gpg: Sorry, no terminal at all requested - can't get input Any help or resource to fixing it?

http://stackoverflow.com/a/48977075
has comment: http://stackoverflow.com/comment/84960468
has comment: http://stackoverflow.com/comment/84960296
has comment: http://stackoverflow.com/comment/84959967
accepted answer of: http://stackoverflow.com/q/48976564
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84959580
has body: You can use regular expression or IP address module to resolve your problem import re import os import urllib2 import json while True: ip = raw_input("What Your Target IP : ") if not re.match(("^\d{0,9}\.\d{0,9}\.\d{0,9}\.\d{0,9}$"), ip): print ("Error! Make sure you only use numbers") else: print("You picked number "+ ip) url = "https://blablabla/" response = urllib2.urlopen(url + ip) data = response.read() values = json.loads(data) print("------------------------------------") print "\r" print(" IP : " + values['ip']) print(" City : " + values['city']) print(" Region : " + values['region']) print(" Country : " + values['country_name']) print(" Continent : " + values['continent_name']) print(" Time Zone : " + values['time_zone']) print(" Currency : " + values['currency']) print(" Calling Code : " + "+" + values['calling_code']) print(" Organisation : " + values['organisation']) print(" ASN : " + values['asn']) print "\r"
has comment: http://stackoverflow.com/comment/84959353
has comment: http://stackoverflow.com/comment/84959608
has comment: http://stackoverflow.com/comment/84959375
answers question: http://stackoverflow.com/q/48976564
type: Answer
has comment: http://stackoverflow.com/comment/84959793
has comment: http://stackoverflow.com/comment/84960149
has comment: http://stackoverflow.com/comment/84959385

http://stackoverflow.com/q/49028221
has comment: http://stackoverflow.com/comment/85061576
upvote count: 1
tagged with: inputstream
has comment: http://stackoverflow.com/comment/85060739
type: Question
has body: I have written a Java project that uses Runtime.getRuntime.exec() to launch a .exe which then launches a python script. Within the py script are several 'print(..)' commands that I wish to be read by java using getInputStream(). However, as the script is being launched by another .exe, 'print()' or sys.stdout.write() outputs do not appear in the cmd window. Is there a way to ensure all outputs return to cmd, or is there another way round it? Thanks in advance!
has comment: http://stackoverflow.com/comment/85061239
has comment: http://stackoverflow.com/comment/85061677
has comment: http://stackoverflow.com/comment/85062585
has comment: http://stackoverflow.com/comment/85061081
downvote count: 0
tagged with: cmd
linked to: http://stackoverflow.com/q/3774432
has comment: http://stackoverflow.com/comment/85061889
favorite count: 0
has comment: http://stackoverflow.com/comment/85060997
has comment: http://stackoverflow.com/comment/85066971
has comment: http://stackoverflow.com/comment/85062044
type: UnansweredQuestion
tagged with: python
has title: Reading python script cmd output when executed by another .exe from cmd
has comment: http://stackoverflow.com/comment/85061290
answer count: 0
score: 1
tagged with: java

http://stackoverflow.com/q/48970059
has body: After a long time writing this small script, it finally worked; or better to say, it's almost done. I am having just a small problem. I am not able to send COOKIES as add.headers in the urllib.request. What am I doing wrong? I need to send a given COOKIE or the website will not allow me to download the .pdf file, but I believe I'm doing this the wrong way. Here is my code; please let me know what is wrong: import os import threading import urllib.request from queue import Queue class Downloader(threading.Thread): """Threaded File Downloader""" def __init__(self, queue): """Initialize the thread""" threading.Thread.__init__(self) self.queue = queue def run(self): """Run the thread""" while True: # gets the url from the queue url = self.queue.get() # download the file self.download_file(url) # send a signal to the queue that the job is done self.queue.task_done() def download_file(self, url): """Download the file""" handle = urllib.request.urlopen(url) faturanum = 20184009433300 fatura = str(faturanum) fname = fatura + ".pdf" handle.addheaders = [('Cookie', 'ASP.NET_SessionId=zstuzktl0x1laoqhxgkm4ign')] with open(fname, "wb") as f: while True: chunk = handle.read(1024) if not chunk: break f.write(chunk) def main(urls): """ Run the program """ queue = Queue() # create a thread pool and give them a queue for i in range(5): t = Downloader(queue) t.setDaemon(True) t.start() # give the queue some data for url in urls: queue.put(url) # wait for the queue to finish queue.join() if __name__ == "__main__": urls = ["https://pagamentodigitaltsting.com/Fatura/Pdf?nrFatura=20193981821"] main(urls) What is wrong that I can not send cookies with the request? As you can see, the website is being served through https. Once the page loads, it renders a pdf file.
answer count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84945691
has title: Why doesn't my python script send COOKIES together?
has comment: http://stackoverflow.com/comment/84950892
score: 0
tagged with: urllib
has comment: http://stackoverflow.com/comment/84945728
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84945614
has comment: http://stackoverflow.com/comment/84945630

http://stackoverflow.com/comment/85022246
type: QuestionComment
score: 1
has text: According to Wikipedia, a [Toepelitz tridiagonal matrix](https://en.wikipedia.org/wiki/Tridiagonal_matrix#Eigenvalues) (which this appears to be) should have real eignevalues if the product of the off-diagonal values is positive (in this case `0.5*1.5 = .75`)
comment on: http://stackoverflow.com/q/48999970
type: Comment

http://stackoverflow.com/comment/84956210
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48975436
has text: I'm going to choose `lb.event_generate('<<SelectAll>>')` because it makes the fewest assumptions. Thank you.

http://stackoverflow.com/a/49145575
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49121162
has comment: http://stackoverflow.com/comment/85374638
upvote count: 1
has body: Instead of creating multiple __init__ methods, which doesn't work in Python because the second one 'overwrites' the first, you have two options: Use keyword arguments: class FileAndDirectory(object): def __init__(self, name, path, children=None, file_offset=None, file_size=None) ... The problem with this is that you need to remember which set of inputs are required for different types of things you are creating. So the second option is to have multiple separate constructors, which are usually achieved in Python using classmethods or staticmethods. These typically wrap the normal constructor. It looks like this: class FileAndDirectory(object): @classmethod def create_file(cls, name, full_path, file_offset, file_size): return cls(name, full_path, file_offset=file_offset, file_size=file_size) @classmethod def create_directory(cls, name, full_path, children): return cls(name, full_path, children=children) You would then use these like: FileAndDirectory.create_file(name, full_path, offset_in_LIF, file_size) FileAndDirectory.create_directory(folder_name, path_thus_far, folder_contents_list) As explanation - when you call a normal instance method the self parameter becomes the instance that is being called 'from'. When you call a classmethod, the cls parameter is the class that is called from (which could in fact be a subclass if there are any). The cls(...) call then does the same as FileAndDirectory(...) i.e. it calls the constructor and initializer. This code might be surprising to someone from a Java background - it Python, classes are runtime objects that can be passed around and used just the same as instances of classes. A final consideration - if you need two different constructors, that suggests to me that two different classes for these objects might be preferable. If they have some similarities, they could inherit from a base class that has the shared behaviour. But you know this better than me! (Note - I 'corrected' all your code to use PEP8 variable name conve…
has comment: http://stackoverflow.com/comment/85765356
type: Answer

http://stackoverflow.com/a/49061590
answers question: http://stackoverflow.com/q/49059296
type: Answer
has comment: http://stackoverflow.com/comment/112709359
has body: Here is one way. There is no need for an explicit merge or to drop duplicates. This is where you might see a performance improvement. Solution s = df2[df2['Price_code'].isin([13, 14, 15])].groupby('KEY')['payment_price'].sum() df1['calculated_price'] = df1['original_price'] - df1['KEY'].map(s).fillna(0) Result KEY area original_price calculated_price 0 100000555 12 1205.20 1071.16 1 100000009 13 1253.25 354.27 2 100000034 12 1852.15 1575.14 3 100000035 12 1452.36 1452.36 4 100000036 12 1653.21 1653.21 Explanation Filter df2 by Price_code as required, aggregate payment_price by KEY and finally sum. The result is a series mapping KEY to sum of payments. Use map to map these summations to KEY in df1 and subtract from original_price.
score: 5
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49059296
downvote count: 0

http://stackoverflow.com/q/48994844
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/22833404
type: UnansweredQuestion
has title: Fill barchart with patterns
tagged with: python
has body: I am currently working on plotting a bar chart. For easier readability and to make the different bars distinguishable after b&amp;w-printing I want to plot the bars using different patterns and if at all possible different colors and patterns similar to this or this. Is this possible while using pandas or matplotlib? If so, are there pattern palettes similar to color palettes? My current code looks like this df.transpose().plot.bar(width=0.8)
score: 2
tagged with: matplotlib
type: Question
duplicate of: http://stackoverflow.com/q/22833404
upvote count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48995004

http://stackoverflow.com/comment/85380349
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49103679
has text: I'm not set up with sagemaker to test, but I think the answer you're looking for might be in the [sdk README](https://github.com/aws/sagemaker-python-sdk). It looks like there is a [models.get_model](https://github.com/aws/sagemaker-python-sdk#model-serving) command listed immediately above the linked section and then the python calls to use the loaded model below that.
score: 0

http://stackoverflow.com/q/48969799
has answer: http://stackoverflow.com/a/48969886
tagged with: python
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48974690
score: -1
type: Question
has comment: http://stackoverflow.com/comment/84945119
has body: I have two lists with variables x and y. They are sorted out in a sense that x[n] corresponds to y[n], where n is the index of the list. I need to compute f(x,y). The function is a simple polynomial depending on x and y. Say, f(x,y) = x^2+2xy.Below, I will put the code I tried which did not work. list_x=[1,2,3,4,5] list_y=[2,4,5,8,10] x=list_x[n] y=list_y[n] def f(x,y): for n in range (0,4): return x**2+2*x*y print(f(x,y))
has comment: http://stackoverflow.com/comment/84945163
tagged with: function
has comment: http://stackoverflow.com/comment/84945122
has answer: http://stackoverflow.com/a/48969879
favorite count: 0
answer count: 3
has title: How to compute values of function, f(X,Y), over a range of values of X and Y in two separate lists

http://stackoverflow.com/comment/85006045
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48999460
type: Comment
has text: I up-voted your answer @Wen .. would you mind editing your answer to walk through that one line of code? I'm learning Pandas and replicated this dataframe on Jupyter, and trying to understand each part of your code. An explanation would be great, such as what `x.iloc[-1]-x.iloc[0]` is referencing exactly per time value, and whether we can apply the same to buy==0 in general

http://stackoverflow.com/comment/85156456
type: QuestionComment
has text: shouldnt it be `"select id, name, url from categories where", id_parent=%s`
comment on: http://stackoverflow.com/q/49075238
score: 0
type: Comment

http://stackoverflow.com/comment/84990452
has text: Yes.. this fixes the problem. Thank you! In fact there was something reported on effbot.org [link](http://effbot.org/tkinterbook/listbox.htm). I came across that article yesterday during my research, but didn't connect the dots. Sorry.
type: Comment
comment on: http://stackoverflow.com/a/48992537
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85151393
type: AnswerComment
comment on: http://stackoverflow.com/a/49072288
score: 0
has text: I get 'taken camera from index: 0'
type: Comment

http://stackoverflow.com/comment/85097543
comment on: http://stackoverflow.com/q/49046342
score: 1
has text: How working `print(removed_pd['filtered'].map(lemmatizer))` or `removed_pd['filtered'].apply(lemmatizer)` ?
type: Comment
type: QuestionComment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/49067168
tags question: http://stackoverflow.com/q/48963808
tag name: kivy-language
tags question: http://stackoverflow.com/q/48995284
tags question: http://stackoverflow.com/q/49073331
tags question: http://stackoverflow.com/q/49108836

http://stackoverflow.com/a/48978824
score: 1
type: AcceptedAnswer
downvote count: 0
has body: p1 will only have n if if has length 1. It may be worthwhile to add if len(p1)==1 as the conditional instead.
answers question: http://stackoverflow.com/q/48978773
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48978773

http://stackoverflow.com/a/49083206
downvote count: 0
has body: The solution I found was to create a subclass of webapp2.WSGIApplication and have that modify the environ dictionary before calling the superclass to run the app. To set the instance as an attribute of the request, rather than having to access it via Request.environ, I added it to the environ's 'webob.adhoc_attrs' value. This is because webapp2's Request class inherits from webob's, which in turn inherits from a mixin class that manages attribute access. Here's an example application that sets an attribute on all requests: import webapp2 class Handler(webapp2.RequestHandler): def get(self): try: foo = self.request.foo except AttributeError: foo = 'Default' self.response.write('Hello %s' % foo) routes = [('/', Handler)] class MyWSGIApplication(webapp2.WSGIApplication): def __call__(self, environ, start_response): adhoc_attrs = {'foo': 'Foo'} if 'webob.adhoc_attrs' in environ: environ['webob.adhoc_attrs'].update(adhoc_attrs) else: environ['webob.adhoc_attrs'] = adhoc_attrs return super(MyWSGIApplication, self).__call__(environ, start_response) app = MyWSGIApplication(routes)
answers question: http://stackoverflow.com/q/49083196
accepted answer of: http://stackoverflow.com/q/49083196
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/85095409
type: Comment
type: QuestionComment
score: 4
has text: You can't use variable syntax in tags, why don't you expose a *dictionary* mapping currency to transactions instead?
comment on: http://stackoverflow.com/q/49045348

http://stackoverflow.com/q/49118027
type: Question
tagged with: python
answer count: 1
has body: So I created this lab assignment for class. It seemed fine, except for it doesn't run at all in idle. Idle opens, and then immediately closes. It ran fine in powershell, and the IDE i was using, but would not run at all for my professor. The program just opens randomNumbers.txt and then lists the values inside. I have had no problems with any of my programs before this one, and this one seems to be the simplest. Is there a simple mistake I'm overlooking? As well as that, if you have any suggestions as to methods i can use to optimize this code id love the suggestions, I've been using python for 2 months now. Sorry if this post was a bit long, just really confused. import time, sys def main(): global file file = open("randomNumber.txt","r") prepArray() print("\n-----------\n# | Value\n-----------") printArray() file.close() closeInput = input("\nPress ENTER to exit") print("Closing...") def prepArray(): global numberSplit global file openFile = input("Open randomNumber.txt (Y/N): ") print("\n") if openFile.lower() == "y": try: f = open("randomNumber.txt","r") except IOError: print("Error opening file: Did you run the generator first?") main() elif openFile.lower() == "n": sys.exit() else: print("\nInvalid input, enter either (Y for yes, N for no)\n") main() numberSplit = file.readline() numberSplit = numberSplit.split(",") numberSplit = numberSplit[:-1] def printArray(): global numberSplit lineCount = 1 totalCount = 0 for item in numberSplit: print(lineCount,"-",item) lineCount += 1 totalCount += float(item) print("\nTotal:",round((totalCount),2)) main() randomNumbers.txt just contains 119.18,470.54,159.89,360.56,47.15,489.77,242.54,
has answer: http://stackoverflow.com/a/49118298
score: 0
has comment: http://stackoverflow.com/comment/85243600
has comment: http://stackoverflow.com/comment/85241378
type: UnansweredQuestion
has title: Python file-reader will not run in IDLE but works fine in terminal?

http://stackoverflow.com/q/49033905
has answer: http://stackoverflow.com/a/49034143
has title: Add to dictionary in if loop
type: Question
has comment: http://stackoverflow.com/comment/85072592
has answer: http://stackoverflow.com/a/49034062
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49033988
answer count: 3
tagged with: python
downvote count: 0
has body: I have an if loop in which I am trying to; (1) Create a dataframe from a filepath. (2) Format this dataframe (3) Add that dataframe to a dictionary that is a property of an instance of a class. Here is my code defining the class and the method: class myClass: def __init__(self, name, filepathlist): self.name = name self.filepathlist = filepathlist def formatData(self): i = 0 self.dataframeDict = {} if i &lt; (len(self.filepathlist) - 1): DFRAW = pd.read_csv(self.filepathlist[i], header = 9) #Row 9 is the row that is not blank (all blank auto-skipped) DFRAW['DateTime'], DFRAW['dummycol1'] = DFRAW[' ;W;W;W;W'].str.split(';', 1).str DFRAW['Col1'], DFRAW['dummycol2'] = DFRAW['dummycol1'].str.split(';', 1).str DFRAW['Col2'], DFRAW['dummycol3'] = DFRAW['dummycol2'].str.split(';', 1).str DFRAW['Col3'], DFRAW['Col4'] = DFRAW['dummycol3'].str.split(';', 1).str DFRAW = DFRAW.drop([' ;W;W;W;W', 'dummycol1', 'dummycol2', 'dummycol3'], axis = 1) dictIndex = self.filepathlist[i][39:44] self.dataframeDict.update({dictIndex: DFRAW}) i = i + 1 Then I create an instance of the class and run the method: filepathlist = ['filepath1','filepath2'] myINST = myClass('Mydataname', filepathlist) myINST.formatData() I then expect myINST.dataframeDict to have two dataframes as per the 2 input filepaths and thus 2 iterations of the if loop. However only 1 is present. What is the error in my code or my approach?
has comment: http://stackoverflow.com/comment/85072607
type: AnsweredQuestion
tagged with: object
possible better answer: http://stackoverflow.com/a/49033988
accepted answer: http://stackoverflow.com/a/49034062
score: 1

http://stackoverflow.com/comment/84965513
has text: I previously checked this link out but could not figure out how to embed the solutions written over there to my code. The issue is that I do not read any data from a csv but write on it. Could you please provide me the main codes I need to use?
comment on: http://stackoverflow.com/q/48980079
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85044105
score: 0
type: Comment
type: QuestionComment
has text: Can you please provide example of image data? Images are encoded using `base64` encoding scheme. Maybe you can try `data.decode('base64')`?
comment on: http://stackoverflow.com/q/49019415

http://stackoverflow.com/q/48988584
downvote count: 0
favorite count: 0
has title: KVM made with Libvirt not persisting after host restart
upvote count: 1
tagged with: python
tagged with: kvm
type: AnsweredQuestion
score: 1
has body: I currently am making a ubuntu KVM with libvirt using the following code import libvirt conn = libvirt.open('qemu:///system') pool_name = 'VMPOOL' name = 'ubuntu0' pools = conn.listAllStoragePools(0) for pool in pools: # check if pool is active print(pool.isActive()) if pool.isActive() == 0: #activate pool pool.create() stgvols = pool.listVolumes() print('Storage pool: '+pool.name()) for stgvol in stgvols : print(' Storage vol: '+stgvol) def createStoragePool(conn, pool_name): xmlDesc = """ """ + pool_name + """ 10 237457858 4069322956 /var/lib/libvirt/pool <format type='qcow2'/> 0755 -1 -1 """ pool = conn.storagePoolDefineXML(xmlDesc, 0) # set storage pool autostart pool.setAutostart(1) print(pool.name(), 'pool name in create') return pool for pool in pools: # check if pool is active print(pool.isActive()) if pool.isActive() == 0: #activate pool pool.create() stgvols = pool.listVolumes() print('Storage pool: '+pool.name()) for stgvol in stgvols : print(' Storage vol: '+stgvol) def createStoragePoolVolume(pool, name): stpVolXml = """ """ + name + """.img 0 10 /var/lib/libvirt/pool/""" + name + """.img 107 107 0744 virt_image_t """ stpVol = pool.createXML(stpVolXml, 0) return stpVol def deleteVolStoragePool(conn, name): volume = conn.storageVolLookupByPath('/var/lib/libvirt/pool/%s.img' % name) volume.wipe() volume.delete() return True ##make kvm via xml def makeKvm(name, conn): xmldesc = """ """ + name + """ 1 1 hvm <boot dev='cdrom'/> 1 <on_poweroff>destroy</on_poweroff> <on_reboot>restart</on_reboot> <on_crash>preserve</on_crash> /usr/bin/qemu-system-x86_64 <driver name='qemu' type='raw'/> <driver name='qemu' type='raw'/> <readonly/> <model type='virtio'/> <graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0' keymap='en-us'/> """ dom = conn.createLinux(xmldesc, 0) return dom try: pool = conn.storagePoolLookupByName(pool_name) except: pool = createStoragePool(conn, pool_name) createStoragePoolVolume(pool, name) makeKvm(name, conn) The problem I'm having is…
has answer: http://stackoverflow.com/a/48995407
type: Question
linked to: http://stackoverflow.com/q/33892909
answer count: 1
accepted answer: http://stackoverflow.com/a/48995407
tagged with: ubuntu
tagged with: libvirt

http://stackoverflow.com/comment/85112241
score: 0
type: Comment
type: QuestionComment
has text: your code only generates a window without content and shows no errors except imports
comment on: http://stackoverflow.com/q/49053729

http://stackoverflow.com/comment/96821093
score: 3
comment on: http://stackoverflow.com/q/49006287
has text: You can also use arguments in FacetGrid like height. Example: ```sns.FacetGrid(data=df, col="x", hue="category", height=15)```
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49063738
has comment: http://stackoverflow.com/comment/85133899
type: Question
has comment: http://stackoverflow.com/comment/85132609
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49063881
accepted answer: http://stackoverflow.com/a/49063758
has answer: http://stackoverflow.com/a/49063881
linked to: http://stackoverflow.com/q/37377478
answer count: 3
downvote count: 0
has body: I have a column of positive and negative number. How to convert this column to a new column to realize convert positive number to 1 and negative number to -1?
favorite count: 0
has answer: http://stackoverflow.com/a/49063768
upvote count: 8
tagged with: pandas
has answer: http://stackoverflow.com/a/49063758
tagged with: python
has comment: http://stackoverflow.com/comment/85132517
score: 8
has title: Pandas convert positive number to 1 and negative number to -1

http://stackoverflow.com/comment/84959067
score: 0
type: Comment
type: QuestionComment
has text: Sorry, I was just examining some old python code and didn't understood much of it and was just stuck at this part. I am still a beginner.
comment on: http://stackoverflow.com/q/48976588

http://stackoverflow.com/q/49086833
score: -1
possible better answer: http://stackoverflow.com/a/49086864
type: Question
has answer: http://stackoverflow.com/a/49086864
answer count: 2
upvote count: 0
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49086868
has title: Tkinter Scrollbar and Menu crashing for no reason
favorite count: 0
tagged with: tkinter
has body: I'm trying to make a simple GUI with tkinter in Python 2.7. Yesterday it was working perfectly, but today it crashes for a very odd error: sbar.pack(side=RIGHT, fill=Y) NameError: name 'RIGHT' is not defined When I remove the arguments, there still is another error quite similar: menubar=Menu(mgui) NameError: name 'Menu' is not defined I have no idea why this happens, why it stopped working. I'm not sure if it's because the code is wrong or maybe the tools I'm working with are. Here's the code: import Tkinter as tk import tkMessageBox from ScrolledText import * mgui=tk.Tk() mgui.geometry('700x450') mgui.title('Adminstrador de ntoas') mtitle=tk.StringVar() mtext=tk.StringVar() sbar = tk.Scrollbar(mgui) sbar.pack() menubar=Menu(mgui) def donothing(): filewin = Toplevel(mgui) button = Button(filewin, text="Do nothing button") button.pack() def llama_crea_notebook(): cng_gui=tk.Toplevel(width=700,height=200) cng_gui.title("Generado de Notebooks") filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Create Notebook", command=donothing) filemenu.add_command(label="Change Notebook", command=donothing) filemenu.add_separator() filemenu.add_command(label="Close", command=quit) menubar.add_cascade(label="File", menu=filemenu) notemenu = Menu(menubar, tearoff=0) notemenu.add_command(label="Read Note", command=donothing) notemenu.add_command(label="Delete Note", command=donothing) menubar.add_cascade(label="Note", menu=notemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Manual", command=donothing) helpmenu.add_command(label="About...", command=donothing) menubar.add_cascade(label="Help", menu=helpmenu)
tagged with: python
has comment: http://stackoverflow.com/comment/85182949
has comment: http://stackoverflow.com/comment/85181274
downvote count: 1
accepted answer: http://stackoverflow.com/a/49086868
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85182820

http://stackoverflow.com/a/49112475
type: Answer
has body: Yes, you can specify it using "languageHints": [ "de"] { "requests": [ { "imageContext": { "languageHints": ["de"] } } ] } For all types of language codes, check supported Google vision languages
accepted answer of: http://stackoverflow.com/q/49096942
score: 0
answers question: http://stackoverflow.com/q/49096942
type: AcceptedAnswer

http://stackoverflow.com/comment/84937269
has text: can you share more code, like how you are calling `model.fit` and how you are creating fork1,2?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48964836
type: Comment

http://stackoverflow.com/a/49016146
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49015697
has comment: http://stackoverflow.com/comment/85040344
has body: It is not possible to store 3D numpy arrays in one 3D numpy array if their shape is not same. You can store this in a simple python list or a set. However, figuring out from your comments on the question. I think you need to resize your images. For this you can use OpenCV. OpenCV is a library/package for python. If you choose to use OpenCV, you can do this to resize your images. import cv2 import numpy as np number_of_images = 10000 target_size = [400, 400] resized_images = np.empty([10000, 400, 400, 3]) for i, img in enumerate(all_images): resized_images[i] = cv2.resize(img, target_size) resized_images is now a 4D numpy array which contains all your images.

http://stackoverflow.com/a/49030468
has comment: http://stackoverflow.com/comment/85066045
type: Answer
has comment: http://stackoverflow.com/comment/85065883
accepted answer of: http://stackoverflow.com/q/49028789
has comment: http://stackoverflow.com/comment/85070458
has body: I have reduced your code to this (removing everything I could not reproduce given your code): import os import time s = "foo" pid = os.fork() from subprocess import Popen if pid == 0: proc = Popen(["sleep", "3"]) with open(s, "w") as p: p.write(str(proc.pid)) # &lt;- Only real error I could see os._exit(0) else: start = time.time() while not os.path.isfile(s): if time.time() - start &gt;= 30: raise TimeoutError("Command took to long") time.sleep(5) print("Read from file: " + open(s, 'r').read()) However, it works just fine, it prints Read from file: 12075. So the issue is not in the part that can be reproduced, given your code. To read/write the procid to the binary file I succesfully used the pickle module: pickle.dump(proc.pid,p) # write to file pickle.load(open(s, "rb")) #read from file
has comment: http://stackoverflow.com/comment/85066719
score: 0
answers question: http://stackoverflow.com/q/49028789
type: AcceptedAnswer

http://stackoverflow.com/a/49096518
type: AcceptedAnswer
downvote count: 0
has body: The error message says did you set model.trainable without calling model.compile after ? In your "vgg16_model" you compile your model first and then start changing the trainable flag of the contained layers. To begin with, you should compile your model after the trainability-changes instead of before and see whether this will resolve your issues.
type: Answer
has comment: http://stackoverflow.com/comment/85199502
accepted answer of: http://stackoverflow.com/q/49091553
score: 13
answers question: http://stackoverflow.com/q/49091553
upvote count: 13
has comment: http://stackoverflow.com/comment/118817057

http://stackoverflow.com/q/48978388
favorite count: 0
has title: Why heappop time complexity is O(logn) (not O(n)) in python?
upvote count: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48978473
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48980095
type: Question
score: 8
has body: For a list, the heappop will pop out the front element. Remove an element from the front of a list has time complexity O(n). Do I miss anything?
has answer: http://stackoverflow.com/a/48978497
has answer: http://stackoverflow.com/a/48978482
tagged with: heap
downvote count: 0

http://stackoverflow.com/comment/85104893
comment on: http://stackoverflow.com/a/49007825
score: 0
type: AnswerComment
type: Comment
has text: @komodovaran_ Thanks, I didn't notice that. According to the docs [`inspect.getfullargspec`](https://docs.python.org/3/library/inspect.html#inspect.getfullargspec) should be a valid drop-in replacement, but you can do it however it works best for you.

http://stackoverflow.com/a/48969319
has body: The trick here is to do a bit of work away from the dataframe. You can break this down into three steps: assemble a list of all tuples (a,b) assign a random value to each pair so that (a,b) and (b,a) have the same value fill in the new column Assuming your dataframe is called df, we can make a list of all the pairs ordered so that a &lt;= b. I think this will be easier than trying to keep track of both (a,b) and (b,a). pairs = set([(a,b) if a &lt;= b else (b,a) for a, b in df.itertuples(index=False,name=None)) It's simple enough to assign a random number to each of these pairs and store it in a dictionary, so I'll leave that to you. Call it pair_dict. Now, we just have to lookup the values. We'll ultimately want to write df['Val'] = df.apply(&lt;some function&gt;, axis=1) where our function looks up the appropriate value in pair_dict. Rather than try to cram it into a lambda (though we could), let's write it separately. def func(row): if row['Sou'] &lt;= row['Des']: key = (row['Sou'], row['Des']) else: key = (row['Des'], row['Sou']) return pair_dict[key]
answers question: http://stackoverflow.com/q/48969151
score: 0
type: Answer

http://stackoverflow.com/a/57015475
type: Answer
score: 2
upvote count: 2
has body: Converting to CSV (proposed by @irenemeanspeace) will not work if some columns of the original dataframe contain lists or dicts. I have found a workaround which can deal with simple objects like lists and dicts. Convert it to json in py27 and then read it from py3.6. # Run this in py2.7 ################################################### import pandas as pd # read dataframe in py2.7 path = 'df.hdf5' # path to dataframe saved in py2.7 df = pd.read_hdf(path) json_string = pd.to_json(compression='gzip') with open('df.json.gz', 'w') as fp: fp.write(json_string) ################################################### # Now run in py3.6 ################################################### import pandas as pd with open('df.json.gz', 'r') as fp: json_string = fp.read() df = pd.read_json(json_string) This is more general solution.
downvote count: 0
answers question: http://stackoverflow.com/q/49108596

http://stackoverflow.com/comment/85165270
has text: Any other methods to accomplish this task? @DanielHarms
comment on: http://stackoverflow.com/q/49021736
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84989968
type: QuestionComment
comment on: http://stackoverflow.com/q/48992179
has text: I think so. Can you try with `locale.setlocale(locale.LC_ALL, '')` to get the locale setting from environment?
score: 3
type: Comment

http://stackoverflow.com/q/49120961
has answer: http://stackoverflow.com/a/49161528
score: 0
answer count: 2
has title: Keras - Difference between output_shape and actual shape
tagged with: keras
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49121612
tagged with: tensorflow
has body: I'm trying to build a neural network using some layers from a pretrained ResNet50 ( the one included in keras.applications ) To do it, I'm using the get_layer method of the model. like this. input = Input( (224, 224 , 3) ) resnet = ResNet50(weights='imagenet', pooling=max, include_top = False , input_tensor=input ) firstconv = resnet.get_layer("conv1") then I print out the shape of firstconv with: print( firstconv.output_shape ) And I get the expected result ( according to the model.summary() ) : (?, 112 , 112 , 64 ) Then later on the code I call the firstconv layer over the input tensor: x = firstconv( inputs ) Then I print the shape of this x and i get ( ? , 109 , 109 , 64 ) after that the code breaks because the shape conflicts. I want to know why this is happening, and how can I fix it. I'm still learning from keras and deep learning, and maybe there is something wrong with the way I try to access the layers inside Resnet50. Thanks in advance I'm using Ubuntu 14.04 , Keras 2.1.4 , and Tensorflow 1.6 installed from pip as backend for keras. EDIT: self.input = Input( (224, 224 , 3) ) self.resnet = ResNet50(weights='imagenet', pooling=max, include_top = False , input_tensor=self.input ) for layer in self.resnet.layers: layer.trainable = False self.firstconv = self.resnet.get_layer("conv1") print(" first convt output ") # this outputs (? , 112 , 112 , 3) , the desired shape print( self.firstconv.output_shape ) ... later on the code x = self.firstconv( self.input) print( x.shape ) # this outputs ( ? , 109 , 109 , 64 ), but the expected shape is ( ? , 112 , 112 , 64 ) That is. in between the code I'm not doing anything on self.firstconv or input
type: Question

http://stackoverflow.com/q/49060423
has comment: http://stackoverflow.com/comment/85126236
has answer: http://stackoverflow.com/a/49060716
has title: How to make bash and make install use virtual environment
has comment: http://stackoverflow.com/comment/85126245
has comment: http://stackoverflow.com/comment/85126249
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/85126267
has comment: http://stackoverflow.com/comment/85125887
answer count: 1
has comment: http://stackoverflow.com/comment/85126120
accepted answer: http://stackoverflow.com/a/49060716
tagged with: linux
has comment: http://stackoverflow.com/comment/85125929
has body: I've been trying to switch my coding to Linux. I have ironed out most of my issues but one last thing I am not able to find any explanation of is the virtualization of make and bash commands. I have installed PyCharm which virtualizes everything from what I have seen. However, when I am cloning repositories from Github, the instructions require building some code using make and then installing them and later on using bash to build dependencies. I am running the commands in PyCharm terminal but instead of installing into the venv, it's installing the data in /usr/xxx instead. How do I tell PyCharm to use bash and make in a similar way to pip to virtualize the setup ? Edit: One of the projects in question is gym-gazebo which requires: git clone https://github.com/erlerobot/gym-gazebo/blob/master/INSTALL.md Then make and make install which installs it in the root Later on there is also bash setup_kinetic.bash Which also uses root folders and not venv I was able to install it but it is not virtualized the way it should when compared with coding on Windows
tagged with: makefile
tagged with: python
has comment: http://stackoverflow.com/comment/85126173
has comment: http://stackoverflow.com/comment/85126175
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85125917
has comment: http://stackoverflow.com/comment/85126086
has comment: http://stackoverflow.com/comment/85125858
has comment: http://stackoverflow.com/comment/85125985
type: Question

http://stackoverflow.com/a/49037117
type: Answer
has body: collections.defaultdict is one way: from collections import defaultdict d = defaultdict(list) dictList = [ {'name': 'some name'}, {'name': 'some other name'}, {'age': 'some age'}, {'last_name': 'some last name'} ] for i in dictList: for k, v in i.items(): d[k].append(v) # defaultdict(list, # {'age': ['some age'], # 'last_name': ['some last name'], # 'name': ['some name', 'some other name']})
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85079281
downvote count: 0
answers question: http://stackoverflow.com/q/49036969

http://stackoverflow.com/comment/84985428
type: Comment
has text: sudo -H pip3 install --upgrade pip --force-reinstall did the job. From what I found it might be a mix within pip2 and pip3.
type: QuestionComment
comment on: http://stackoverflow.com/q/48988232
score: 1

http://stackoverflow.com/comment/84962689
type: AnswerComment
comment on: http://stackoverflow.com/a/48977505
type: Comment
score: 0
has text: 2.Input file also contains namespaces info as below: <JavaHost xmlns="SomeInfo/v1.1"> If i delete this and make it only <JavaHost> the code is working fine, but i don't want to delete this. Any other way to do this?

class
tags question: http://stackoverflow.com/q/49046501
tags question: http://stackoverflow.com/q/49098039
tags question: http://stackoverflow.com/q/49039473
tags question: http://stackoverflow.com/q/49051965
tags question: http://stackoverflow.com/q/49020632
tags question: http://stackoverflow.com/q/49103070
tags question: http://stackoverflow.com/q/49097030
tags question: http://stackoverflow.com/q/49014195
tags question: http://stackoverflow.com/q/49088078
tags question: http://stackoverflow.com/q/49039778
tags question: http://stackoverflow.com/q/49103877
tags question: http://stackoverflow.com/q/49033116
tags question: http://stackoverflow.com/q/48979233
tags question: http://stackoverflow.com/q/49088836
tags question: http://stackoverflow.com/q/49112661
tags question: http://stackoverflow.com/q/49117163
tags question: http://stackoverflow.com/q/48972758
tags question: http://stackoverflow.com/q/48963842
tags question: http://stackoverflow.com/q/49014127
type: Tag
tags question: http://stackoverflow.com/q/49109291
tags question: http://stackoverflow.com/q/49023497
tags question: http://stackoverflow.com/q/48990001
tags question: http://stackoverflow.com/q/49106663
tags question: http://stackoverflow.com/q/49057951
tags question: http://stackoverflow.com/q/49063868
tags question: http://stackoverflow.com/q/49102284
tags question: http://stackoverflow.com/q/49092728
tags question: http://stackoverflow.com/q/48966182
tags question: http://stackoverflow.com/q/48983314
tag name: class
tags question: http://stackoverflow.com/q/49073934
tags question: http://stackoverflow.com/q/49110920
tags question: http://stackoverflow.com/q/49080090
tags question: http://stackoverflow.com/q/49011625
tags question: http://stackoverflow.com/q/49090796
tags question: http://stackoverflow.com/q/49040518
tags question: http://stackoverflow.com/q/49027131
tags question: http://stackoverflow.com/q/49100309
tags question: http://stackoverflow.com/q/49047336
tags question: http://stackoverflow.com/q/49052359
tags question: http://stackoverflow.com/q/49038098
tags question: http://stackoverflow.com/q/49013245
tags question: http://stackoverflow.com/q/49101761
tags question: http://stackoverflow.com/q/48975975

http://stackoverflow.com/q/49071081
tagged with: merge
upvote count: 5
has answer: http://stackoverflow.com/a/49074669
type: Question
has answer: http://stackoverflow.com/a/70904901
score: 5
tagged with: algorithm
has comment: http://stackoverflow.com/comment/85153651
downvote count: 0
tagged with: data-structures
answer count: 6
has answer: http://stackoverflow.com/a/65586317
has answer: http://stackoverflow.com/a/68953818
has answer: http://stackoverflow.com/a/49076157
has body: I am trying to solve a question where in overlapping intervals need to be merged. The question is: Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. I tried my solution: # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): &quot;&quot;&quot; :type intervals: List[Interval] :rtype: List[Interval] &quot;&quot;&quot; start = sorted([x.start for x in intervals]) end = sorted([x.end for x in intervals]) merged = [] j = 0 new_start = 0 for i in range(len(start)): if start[i]&lt;end[j]: continue else: j = j + 1 merged.append([start[new_start], end[j]]) new_start = i return merged However it is clearly missing the last interval as: Input : [[1,3],[2,6],[8,10],[15,18]] Answer :[[1,6],[8,10]] Expected answer: [[1,6],[8,10],[15,18]] Not sure how to include the last interval as overlap can only be checked in forward mode. How to fix my algorithm so that it works till the last slot?
has title: Merging Overlapping Intervals in Python
linked to: http://stackoverflow.com/q/43600878
favorite count: 0
tagged with: overlap
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49072633
duplicate of: http://stackoverflow.com/q/43600878
tagged with: python

http://stackoverflow.com/q/49102080
has comment: http://stackoverflow.com/comment/85226806
has body: TLDR: How can I speed up queries against a null relationship field? Update: Here is the SQL being used by SQLAlchemy. Does anyone know why LIMIT ? OFFSET ? exists? SELECT addresses.id, addresses.street, addresses.city, addresses.state, addresses.zipcode, addresses.parcel FROM addresses WHERE NOT (EXISTS (SELECT 1 FROM results WHERE addresses.id = results.address_id)) LIMIT ? OFFSET ? Some of the queries I'm doing on my SQLite3 database are moving VERY slowly. I'm surprised, because I only have about 90,000 Results instances. Here's some object info: class Address(Base): # There are 1.45M addresses ... results = relationship("Result", back_populates="address") class Result(Base): # There are 90k results ... address_id = Column(Integer, ForeignKey('addresses.id')) address = relationship("Address", back_populates="results") And this query is taking 25 minutes!! q = session.query(Address) addresses = [ [row.street, row.zipcode, row.id] for row in q.filter(Address.results == None).limit(350).all() ] Is this an indexing problem? Even without an index I feel like the limit clause should make things much faster than they are.
tagged with: python
answer count: 0
has title: Efficient relationship filter in SQLite3 and SQLAlchemy
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/85227321
score: 0
tagged with: sql
has comment: http://stackoverflow.com/comment/85252280
tagged with: sqlite
has comment: http://stackoverflow.com/comment/85242242
has comment: http://stackoverflow.com/comment/85250176
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85279337

http://stackoverflow.com/comment/85176062
has text: Thank you Mike... can you tell me what is meant by nonlocal?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49085250
type: AnswerComment

http://stackoverflow.com/comment/85560005
has text: If I understand correctly, creating a subplot with `sharex` and `sharey` as I did only guarantees that the limits will be the same for the linked axes, but does not turn off and label and tick labels. On the other hand, `plt.subplots` also turns these things off when it creates the grid. My interpretation is that matplotlib only turns off the labels if all axes are created at the same time.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48973597

http://stackoverflow.com/a/49013813
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49013787
has body: Use get_dummies which accept list also: a = ['dog', 'cat', 'fish', 'dog', 'dog', 'bird', 'cat', 'bird'] df = pd.get_dummies(a) print (df) bird cat dog fish 0 0 0 1 0 1 0 1 0 0 2 0 0 0 1 3 0 0 1 0 4 0 0 1 0 5 1 0 0 0 6 0 1 0 0 7 1 0 0 0 If ordering of columns is important add reindex with unique: df = pd.get_dummies(a).reindex(columns=pd.unique(a)) print (df) dog cat fish bird 0 1 0 0 0 1 0 1 0 0 2 0 0 1 0 3 1 0 0 0 4 1 0 0 0 5 0 0 0 1 6 0 1 0 0 7 0 0 0 1
answers question: http://stackoverflow.com/q/49013787
score: 1

http://stackoverflow.com/q/49112642
has comment: http://stackoverflow.com/comment/85230550
has answer: http://stackoverflow.com/a/49112903
type: Question
score: 2
has title: Python CSV Writer Appending ".0" to all integers
has comment: http://stackoverflow.com/comment/85230356
answer count: 1
downvote count: 0
tagged with: writer
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/85743105
linked to: http://stackoverflow.com/q/8825681
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/8825681
has comment: http://stackoverflow.com/comment/85233077
has body: I wrote some code and trying to refactor it to cut out a few steps and i cant seem to find an answer for this. Im reading an excel file and doing a bunch of column renaming and dropping columns i dont need. My end goal is to write the Excel file as an text tab delimited file and accomplished all this but in a very hacky way. I have a function convertToText() that reads the excel file and turns it into a txt file. However every single integer in the file gets a .0 appended to the end. Ex. Excel value 1234321 Txt File = 1234321.0 Im just doing a simple read and write using pandas, openpyxl and xlrd. def convertToText(): with open(os.path.join(outFile, 'target2.txt'), 'wb') as myTxtfile: wr = csv.writer(myTxtfile, delimiter="\t") myfile = xlrd.open_workbook(outFile + fileName) mysheet = myfile.sheet_by_index(0) for rownum in xrange(mysheet.nrows): wr.writerow(mysheet.row_values(rownum)) I had to write a second function just to do a find and replace on the .0 and trying to cut that step out of the process. If anyone has any ideas how to do this in the above function would be greatly appreciated!!
has comment: http://stackoverflow.com/comment/85232860
has comment: http://stackoverflow.com/comment/85230316
has comment: http://stackoverflow.com/comment/85231920

http://stackoverflow.com/q/49116113
tagged with: airflow
possible better answer: http://stackoverflow.com/a/51450301
has comment: http://stackoverflow.com/comment/89874865
linked to: http://stackoverflow.com/q/3085029
upvote count: 4
answer count: 2
tagged with: yaml
downvote count: 0
score: 4
has title: Job Scheduler - YAML for writing job definition?
favorite count: 0
has answer: http://stackoverflow.com/a/51451290
linked to: http://stackoverflow.com/q/51187751
tagged with: luigi
tagged with: python
has comment: http://stackoverflow.com/comment/89871028
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51450301
accepted answer: http://stackoverflow.com/a/51451290
has comment: http://stackoverflow.com/comment/89875858
type: Question
has body: In our legacy job scheduling software (built on top of crontab), we are using apache config format (parser) for writing a job definition and we are using perl config general to parse the config files. This software is highly customized and have functionalities like running commands in my job after checking if dependency of that command is met or not, rescheduling jobs in case command fails, supporting custom notifications etc. We are now planning to rewrite this software in python and considering options like YAML instead of apache config to write job definition. Is YAML good for writing such dynamic configurations? Example of job definition (run this job at 2AM daily, check if it is tuesday and not holiday in India, if yes reserve my flight and send notification): // python function to check if it is tuesday checkIfTuesdayAndNotHoliday() &lt;job&gt; calendar: indian &lt;dependency: arbitrary_python_code: checkIfTuesdayAndNotHoliday()&gt; &lt;command&gt; check availability of flight &lt;/command&gt; &lt;success: notify: email: agrawall/&gt; &lt;failure: notify: email: ops&gt; &lt;command&gt; some command to book my flight &lt;/command&gt; &lt;/job&gt; &lt;crontab&gt; 0 2 * * * &lt;/crontab&gt; I am struggling to understand what format should I use to define job (YAML, Apache Config, XML, JSON etc). Note that this job definition will be converted to job object inside my python script. Apache config parser in perl that we currently use https://metacpan.org/source/TLINDEN/Config-General-2.63/General.pm#L769 Apache config parser in python we plan to use https://github.com/etingof/apacheconfig
has comment: http://stackoverflow.com/comment/89875917
has comment: http://stackoverflow.com/comment/89875907
tagged with: job-scheduling

http://stackoverflow.com/a/49026986
type: Answer
has body: import math def is_prime(n): if n % 2 == 0 and n &gt; 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) for i in range(10): number = input("Choose number #%s : " % i) if is_prime(int(number)): print("%s is prime" % number) else: print("%s is not prime" % number)
has comment: http://stackoverflow.com/comment/85059161
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85058826
score: 0
has comment: http://stackoverflow.com/comment/85059203
answers question: http://stackoverflow.com/q/49026796

http://stackoverflow.com/q/49064948
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85134879
has comment: http://stackoverflow.com/comment/85134870
has answer: http://stackoverflow.com/a/49065068
score: -1
has answer: http://stackoverflow.com/a/49065287
answer count: 3
possible better answer: http://stackoverflow.com/a/49065068
favorite count: 0
has comment: http://stackoverflow.com/comment/85135266
has answer: http://stackoverflow.com/a/49065048
accepted answer: http://stackoverflow.com/a/49065287
tagged with: python
has title: Why does my loop start output from 4?
downvote count: 2
has body: I know that using of it probably make no sense, but I'm interested in why it works this way. Why it starts from 4 ? Why it doesn't include 10 ? Why we are out of range ? n=[2, 3, 4, 7, 9, 10] for a in n: print (n[a]) Output 4 7 9 Traceback (most recent call last): File "D:\PyPro\new1.py", line 3, in &lt;module&gt; print (n[a]) IndexError: list index out of range

data-analysis
tags question: http://stackoverflow.com/q/49067073
type: Tag
tags question: http://stackoverflow.com/q/49080955
tags question: http://stackoverflow.com/q/48996822
tags question: http://stackoverflow.com/q/49044379
tags question: http://stackoverflow.com/q/49008179
tags question: http://stackoverflow.com/q/49086896
tags question: http://stackoverflow.com/q/49022851
tags question: http://stackoverflow.com/q/49111859
tag name: data-analysis

http://stackoverflow.com/comment/85045092
comment on: http://stackoverflow.com/a/49019915
type: AnswerComment
has text: That is what i want yes but I tried and I got int object is not iterable
score: 0
type: Comment

http://stackoverflow.com/q/48966446
tagged with: svm
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/48966586
has body: I am trying to train an svm classifier on an MNIST dataset to distinguish between two characters. I am using an exponential kernel with C=10 and gamma=10^-6. I have also printed the support vectors: clfretrainC=svm.SVC(C=Cfinal,kernel="rbf",gamma=gammafinal) clfretrainC.fit(ReTraintotx,ReTraintoty) Pefinal=1-clfretrainC.score(Testtotx,Testtoty) print "Test Error" print Pefinal print "Number of Support Vectors" print clfretrainC.support_vectors_ print clfretrainC.support_vectors_.shape sv=clfretrainC.support_vectors_ However, I wish to find the support vectors that are the closest to the separating hyperplane and hence the hardest to classify. Is there a function that allows me to do this? If not, how do I go about this?
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has title: Finding Support vectors from a dataset that are the hardest to classify
has answer: http://stackoverflow.com/a/48966586

http://stackoverflow.com/comment/85140357
comment on: http://stackoverflow.com/q/49061103
has text: to q3, no, then sounds like your issue is query logging?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84953942
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48970356
has text: Thank you so much! I am doing this exactly, but I receive a new error now, which I put in my question

http://stackoverflow.com/a/49099047
upvote count: 1
has comment: http://stackoverflow.com/comment/85204362
answers question: http://stackoverflow.com/q/49098955
type: Answer
score: 1
has body: I know that if I use anyList = [] * 10 it will create a list with 10 slots. This is in fact incorrect. If you write somelist * somenumber, it will construct a list with as length the length of somelist times somenumber, and it will repeat the list. For example: &gt;&gt;&gt; [1, 'a', 2, 5] * 3 [1, 'a', 2, 5, 1, 'a', 2, 5, 1, 'a', 2, 5] But the above definition thus hints that an empty list (that has length zero) times any number, is just an empty list. There are no "empty" slots in Python (well there are no empty slots at all in most programming languages). Most programming languages will write a default value as initial values to an array or list that is constructed. Other languages like C++, will not write a default value to the list, but will simply interpret what is at that moment in memory (so if by accident the memory had the number 1425 at that location, then the array/list contains that number). So we need to decide what initial value to use. We can for instance use a None, a 4, or anything else. Let us here use None. Now to answer the question in general, we can multiply it with any integral number. So we can ask the user for input, convert it to an int, and then multiply the list with that number. For example: d = int(input('Initial length?')) our_list = [None] * d
downvote count: 0

http://stackoverflow.com/a/49007384
has comment: http://stackoverflow.com/comment/85019350
score: 0
has body: Try to use curly braces it will help you. self.cur.execute("UPDATE Trainers SET Name={}, DOB={}, Gender={}",(Name, DOB, Gender))
has comment: http://stackoverflow.com/comment/85050336
answers question: http://stackoverflow.com/q/49007276
type: Answer

http://stackoverflow.com/comment/85083633
has text: @DennisGathagu Did CMS_TEMPLATES point to the correct child template? Can you show your templates and CMS_TEMPLATES setting?
comment on: http://stackoverflow.com/a/49038783
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49073294
answer count: 1
downvote count: 0
has title: how to add NaN groupwise for missing values
has body: I have a DataFrame analogous to this one: import pandas dd = pandas.DataFrame({'name' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar'], 'year' : ['1900', '1903', '1904', '1900', '1901', '1902', '1903', '1904'], 'value' : np.arange(8) }) Further along the pipeline I will need to compare foo and bar in terms of magnitudes derived from value. This is why I would like to add rows for the missing years in foo and fill them with NaN. So the final dd should have additional rows and look like this: value name year 0 0.0 foo 1900 1 NaN foo 1901 2 NaN foo 1902 3 0.1 foo 1903 4 0.2 foo 1904 5 0.3 bar 1900 6 0.4 bar 1901 7 0.5 bar 1902 8 0.6 bar 1903 9 0.7 bar 1904 I tried using this solution but it doesn't work in this case because I have duplicate values in the year column. I realize I have to add rows grouping by 'name' but I couldn't see how. What should I do?
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49073403
accepted answer: http://stackoverflow.com/a/49073403
score: 1
type: Question
linked to: http://stackoverflow.com/q/25909984
tagged with: pandas

http://stackoverflow.com/comment/85202962
type: Comment
comment on: http://stackoverflow.com/a/49092491
has text: Thank you for taking your time on this, your solution looks very close to what I want, except I need to return the result from askGoogle(), not the term itself. If you could implement that in your answer, I think we are at a closure here :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/49146800
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49003874
has body: As my understand, you may need to prepare third-party program for collect flow information (e.g. sFlow). and write one program for communicating with SDN Controller. SDN Controller cover all traffic on switches. It don't handle over L4 event in general case
has comment: http://stackoverflow.com/comment/85556654

http://stackoverflow.com/comment/85302252
type: AnswerComment
type: Comment
has text: @kitman0804 Hi, sorry for the late reply been busy with work. the JSON is too long to be posted here so I put it on pastebin (you can't do code snippets in comments on SO). https://pastebin.com/7TbJNdiK. I want to extract the "name" and the "id" from the json.
comment on: http://stackoverflow.com/a/49025455
score: 0

http://stackoverflow.com/a/49032549
has body: Your package doesn’t register a package named PyLT3. Your project stucture should look like this: PyLT3/ # This is your project directory. Its name is irrelevant from the packaging point of view. |- .git/ |- .idea/ |- setup.py |- README.rst |- LICENSE.txt |- .gitignore |- PyLT3/ # This is directory holds your python package. |- __init__.py |- FileHelpers.py |- TypeHelpers.py |- XmlHelpers.py You can try this locally by running pip install -e . from your project directory. This allows you to validate this works, before you publish. A personal note: I would also strongly suggest using lower case package and module names, as per PEP8
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85076106
accepted answer of: http://stackoverflow.com/q/49031878
answers question: http://stackoverflow.com/q/49031878
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49073355
tagged with: bit-manipulation
type: Question
has comment: http://stackoverflow.com/comment/85153296
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/85152674
has comment: http://stackoverflow.com/comment/85152539
tagged with: arrays
has title: Bitwise operations between every pair of elements in array
has body: Here is the situation: I have a graph type structure, an adjacency list, and each element of this adjacency list is a 1 dimensional array (either numpy, or bcolz.. not sure if I will use bcolz or not). Each 1-dimensional array represents graph elements that could possibly connect, in the form of binary sequences. For them to connect, they need to have a specific bitwise intersection value. Therefore, for each 1 dimensional array in my adjacency list, I want to do the bitwise "and" between every combination of two elements in the given array. This will possibly be used for huge graph breadth-first traversal, so we may be talking a very very large number of elements. Is this something I can do with vectorized operations? Should I be using a different structure? What is a good way to do this? I am willing to completely restructure everything if there could be a significant performance boost. Is it as simple as looping through the individual elements and then broadcasting(correct terminology?) &amp; against the entire array? Thanks. quick edit As an extra note, I am using python integers for my byte sequences. Which from my understanding, doesn't play well with numpy(the integers get too big, type long long). I have to create arrays of object type. Does this potentially cause a huge slowdown? Is it a reason to use a different structure? An Example //create an nxn adjacency list, where n is number of graph nodes. //map each graph node to a value 2^k: nodevals = defaultdict() for i in xrange(n): nodevals[i] = 2**(i+1) //for each edge in our graph it is comprised of two nodes, which are mapped as powers of two. Take their sum, and place them in the adjacency list: for i in xrange(n): for j in xrange(n): adjlist[i][j].append((nodevals[i]|nodevals[j])) //We now have our first Adjacency list, which is just bare edges. These edges can be connected by row or column, by taking intersection of the sum (nodevals[i]|nodevals[j]) with the other edge (nodevals[i2]|nodevals[j2]), and …
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
answer count: 0

http://stackoverflow.com/comment/85226986
has text: https://stackoverflow.com/questions/49110713/how-to-add-the-dictionary-in-parse-qs-results see this please
type: Comment
comment on: http://stackoverflow.com/a/49108867
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85156640
comment on: http://stackoverflow.com/a/49050209
type: Comment
has text: I converted the code yet however the installation failed. Tried your second hint and got: (base) C:\Users\>conda create --name MYFIPYENV --channel guyer --channel conda-forge fipy nomkl python=2.7 Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: - fipy - gmsh - fipy - pysparse - fipy - trilinos - fipy - nomkl - nomkl
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85210920
score: 0
type: Comment
type: QuestionComment
has text: The best way to understand and solve this type of problem is to provide a [mcve] :D
comment on: http://stackoverflow.com/q/49102849

http://stackoverflow.com/q/49104927
has comment: http://stackoverflow.com/comment/85214890
has comment: http://stackoverflow.com/comment/85214844
has comment: http://stackoverflow.com/comment/85215148
has comment: http://stackoverflow.com/comment/85221486
type: UnansweredQuestion
tagged with: word2vec
tagged with: python
has comment: http://stackoverflow.com/comment/85215013
type: Question
has comment: http://stackoverflow.com/comment/85215215
has body: My data has mix of text and categorical features. It looks like: cr_id description business type status 1 More robust system required secured loan system rejected 2 More robust system required secured loan system rejected 3 grant access to all products mortgage system rejected 4 EDAP Scenario secured loan regulatory accepted 5 grant access to all products secured loan regulatory accepted Now on description column I am applying word2vec approach. As a result I get a trained vector of 300 columns. Now my question is how to include categorical features in the model too. I mean how to combine the output of word2vec and one-hot coded vectors as they are of different shape.Code used to form wordvec is: def review_to_wordlist(review, remove_stopwords=False): """ Convert a review to a list of words. Removal of stop words is optional. """ # remove non-letters review_text = re.sub("[^a-zA-Z]"," ", review) # convert to lower case and split at whitespace words = review_text.lower().split() # remove stop words (false by default) if remove_stopwords: stops = set(stopwords.words("english")) words = [w for w in words if not w in stops] return words def review_to_sentences(review, tokenizer, remove_stopwords=False): """ Split review into list of sentences where each sentence is a list of words. Removal of stop words is optional. """ # use the NLTK tokenizer to split the paragraph into sentences raw_sentences = tokenizer.tokenize(review.strip()) # each sentence is furthermore split into words sentences = [] for raw_sentence in raw_sentences: # If a sentence is empty, skip it if len(raw_sentence) &gt; 0: sentences.append(review_to_wordlist(raw_sentence, remove_stopwords)) return sentences train_sentences = [] # Initialize an empty list of sentences for review in data['description']: train_sentences += review_to_sentences(review, tokenizer) model_name = 'train_model' # Set values for various word2vec parameters num_features = 300 # Word vector dimensionality min_word_count = 3 # Minimu…
has answer: http://stackoverflow.com/a/49105518
has title: Including categorical features along with text in wordvec approach- Python
score: 0
tagged with: categorical-data
answer count: 1

http://stackoverflow.com/comment/85242708
type: Comment
has text: Oh wow! Thank you very much for your effort folks! Not an expert in matplotlib, but I would consider the functionality described in this topic very useful (at least useful enough) to warrant a spot in the library. Maybe we should ping the developers ? Thank you again!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49115448

http://stackoverflow.com/q/49068100
downvote count: 0
tagged with: desktop-application
answer count: 1
has title: Remove items from QListWidget in PyQt5
favorite count: 0
has comment: http://stackoverflow.com/comment/85141330
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85141834
accepted answer: http://stackoverflow.com/a/49068673
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/49068673
upvote count: 9
has body: I am trying to make a refresh button in pyqt5. I am building a desktop app. I wrote the code that scans particular folder and saves filenames and their paths as an array. Array values are added to QListWidget as items self.sampleChoose_list.addItems(sample_directory[0]) I am trying to make a function that refreshes values of the array and passes it to QListWidget. Something like this self.refreshSamples.clicked.connect(self.refreshSample) def refreshSample(self): sample_directory = [] sample_files = [] for (dirpath, dirnames, filenames) in walk('./Samples'): filenames = [f for f in filenames if not f[0] == '.'] sample_files.extend(filenames) break the_dir = "Samples" paths = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')] sample_directory.append(sample_files) sample_directory.append(paths) self.sampleChoose_list.addItems(sample_directory[0]) The problem that I struggle with is: when I push refresh button, new items get added, but the old ones are not deleted. How to remove items from QListWidget?
score: 9
tagged with: pyqt

http://stackoverflow.com/comment/85226447
has text: Hmm, I also see that generating the mapping is 1000x more expensive than the indexing operation. Definitely not worth it.
comment on: http://stackoverflow.com/a/49103701
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85198150
has text: What are `csg` and `cmdscale`?
comment on: http://stackoverflow.com/q/49095320
score: 0
type: Comment
type: QuestionComment

neo4j
tags question: http://stackoverflow.com/q/49030430
tags question: http://stackoverflow.com/q/49038781
tag name: neo4j
tags question: http://stackoverflow.com/q/48972406
tags question: http://stackoverflow.com/q/49024029
type: Tag
tags question: http://stackoverflow.com/q/48982511

http://stackoverflow.com/comment/85247830
type: Comment
has text: how can it be `'"'` if it is newline character?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49121142

http://stackoverflow.com/comment/84960640
type: Comment
type: QuestionComment
score: 2
has text: A *pattern* is `/.../` where the `...` is a Python regular expression. (See the Python documentation for the`re` package.) In a Python regular expression `(?i)` means "start ignoring case", so `/(?i).../` is a case insensitive pattern. (There are other ways to write Tatsu patterns. See the docs.)
comment on: http://stackoverflow.com/q/48975486

http://stackoverflow.com/comment/85103258
score: 0
has text: Hi. I will make a slight correction to the above that in fact if I plot the exact data above, I get the y axis format 'dd HH:MM' (full dataset is longer). So the above gives day, hour minute, and no seconds. Sorry. Nevertheless, it is still not right. You get just HH:MM:SS? It's python 2.7.12, matplotlib version '2.1.1', numpy version '1.13.3'. thanks!
comment on: http://stackoverflow.com/q/49048143
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90313163
comment on: http://stackoverflow.com/a/51673851
type: AnswerComment
type: Comment
score: 1
has text: Unfortunately, using a thread works for the simple case of printing a message, but will cause problems when accessing other variables and context.

http://stackoverflow.com/comment/85201890
type: QuestionComment
has text: @vikvanderlinden Nope, but I would prefer to keep the first one, though, not a big deal in my case.
comment on: http://stackoverflow.com/q/49098295
score: 0
type: Comment

http://stackoverflow.com/a/49078372
has comment: http://stackoverflow.com/comment/85162939
has comment: http://stackoverflow.com/comment/85162930
has comment: http://stackoverflow.com/comment/85163237
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49073934
type: AcceptedAnswer
has body: Calling super with 1 argument produces an "unbound" super object. Those are weird and undocumented and mostly useless, and I won't go into how they were intended to be used, but for the purposes of this answer, we really only need to know one thing about them. super(SomethingElse).__init__ doesn't go through the usual super proxy logic. You're getting the super instance's own __init__ method, not anything related to SomethingElse. From there, the rest of the behavior follows. The TypeError: super() takes at least 1 argument (0 given) on Python 2 is because super.__init__ takes at least 1 argument, and you're passing it 0. (You might expect it to say TypeError: super() takes at least 2 arguments (1 given) because it's still getting self - the super object self, not the SomethingElse instance - but due to weird implementation details, methods implemented in C generally don't count self for this kind of error message.) SomethingElse() succeeds on Python 3 because the super constructor pulls __class__ and self from the usual stack inspection magic. Calling super(SomethingElse).__init__() manually from outside the class produces RuntimeError: super(): no arguments because super.__init__ tries to do its stack inspection magic and doesn't find __class__ or self. super(SomethingElse).__init__(SomethingElse()) fails because the first argument to the super constructor is supposed to be a type, not an instance.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49073934
has comment: http://stackoverflow.com/comment/85162835
type: Answer

http://stackoverflow.com/comment/85006409
comment on: http://stackoverflow.com/q/48999887
has text: Thank you so much -- this fixed my problem. I'd mark this as the correct answer but it is a comment so I think I can't do that. Please feel free to write it to an answer, I'll check mark it! :) Thanks so much again.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85238164
type: AnswerComment
comment on: http://stackoverflow.com/a/49113622
type: Comment
has text: Yep! works, but does add a count column to the index which I was able to get rid of with: `df.reset_index(inplace=True)` `df.drop(df.columns[1], axis=1, inplace=True)` `df.set_index('timestamp',inplace=True)` `df.sort_index(axis=0, inplace=True)`
score: 0

http://stackoverflow.com/q/48988309
has body: I am trying to do Multi-class classification in Keras. I am using the crowdflower dataset.Here is my code below: import pandas as pd from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import numpy as np from sklearn.preprocessing import LabelEncoder from keras.models import Sequential from keras.layers import Embedding, Flatten, Dense from sklearn.preprocessing import LabelEncoder df=pd.read_csv('text_emotion.csv') df.drop(['tweet_id','author'],axis=1,inplace=True) df=df[~df['sentiment'].isin(['empty','enthusiasm','boredom','anger'])] df = df.sample(frac=1).reset_index(drop=True) labels = [] texts = [] for i,row in df.iterrows(): texts.append(row['content']) labels.append(row['sentiment']) tokenizer = Tokenizer() tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) data = pad_sequences(sequences) encoder = LabelEncoder() encoder.fit(labels) encoded_Y = encoder.transform(labels) labels = np.asarray(encoded_Y) print('Shape of data tensor:', data.shape) print('Shape of label tensor:', labels.shape) indices = np.arange(data.shape[0]) np.random.shuffle(indices) data = data[indices] labels = labels[indices] print labels.shape model = Sequential() model.add(Embedding(40000, 8,input_length=37)) model.add(Flatten()) model.add(Dense(100,activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(9, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(data,labels, validation_split=0.2, epochs=150, batch_size=100) I am getting this error: ValueError: Error when checking target: expected dense_3 to have shape (9,) but got array with shape (1,) Can someone please point out the fault with my logic? I understand my question is kind of similar to Exception: Error when checking model target: expected dense_3 to have shape (None, 1000) but got a…
score: 1
has comment: http://stackoverflow.com/comment/84982524
tagged with: keras
accepted answer: http://stackoverflow.com/a/48991007
favorite count: 0
tagged with: multiclass-classification
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84983729
has title: Error in Keras while doing Multi-class classification
has comment: http://stackoverflow.com/comment/84984981
upvote count: 1
has comment: http://stackoverflow.com/comment/84981962
has answer: http://stackoverflow.com/a/48991007
has comment: http://stackoverflow.com/comment/84983623
linked to: http://stackoverflow.com/q/39335434
type: AnsweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/94136503
score: 0
comment on: http://stackoverflow.com/a/49093252
type: Comment
has text: Can you explain what this means and how this can be done?
type: AnswerComment

http://stackoverflow.com/comment/85052389
has text: Any algorithmic requirements on the data structure? I guess `O(1)` "access" and "insertion" is probably impossible. Is `O(n)` sufficient?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49023497

http://stackoverflow.com/comment/85060281
type: QuestionComment
type: Comment
has text: The problem is I don't see the part implement.teacherid when the template is opened on the browser. I don't know how should I do it if I want to get the teacherid.
comment on: http://stackoverflow.com/q/49027544
score: 0

http://stackoverflow.com/q/48963751
favorite count: 0
has title: Antlr parsers for target language Python2
tagged with: antlr4
has comment: http://stackoverflow.com/comment/84973336
tagged with: python
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48964149
score: -2
tagged with: antlr
type: Question
tagged with: python-2.7
has body: Can someone link me to an antlr parser already made for python2. I need to parse python code for variables extraction in any python program.
upvote count: 0
answer count: 1

http://stackoverflow.com/q/48970914
answer count: 2
possible better answer: http://stackoverflow.com/a/48971082
has body: I am new to python. And I want to install some modules, but it kept telling me the wheel is not supported. Could anyone help me? Thank you. Details: python ver. 3.6.4 x64 Pillow-5.0.0-cp36-cp36m-win_amd64.whl Here is what I got when I tried to install the module via pip. C:\Python\Scripts&gt;pip install Pillow-5.0.0-cp36-cp36m-win_amd64.whl Pillow-5.0.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. When I run import pip print(pip.pep425tags.get_supported()) I get the following output: [('cp36', 'cp36m', 'win_amd64'), ('cp36', 'none', 'win_amd64'), ('py3', 'none', 'win_amd64'), ('cp36', 'none', 'any'), ('cp3', 'none', 'any'), ('py36', 'none', 'any'), ('py3', 'none', 'any'), ('py35', 'none', 'any'), ('py34', 'none', 'any'), ('py33', 'none', 'any'), ('py32', 'none', 'any'), ('py31', 'none', 'any'), ('py30', 'none', 'any')]
has answer: http://stackoverflow.com/a/48971082
accepted answer: http://stackoverflow.com/a/48970978
tagged with: python
type: AnsweredQuestion
tagged with: installation
tagged with: python-wheel
tagged with: pip
has comment: http://stackoverflow.com/comment/84947423
type: Question
has answer: http://stackoverflow.com/a/48970978
has title: Can't install modules via pip, said not supported
has comment: http://stackoverflow.com/comment/84947181
score: 0

http://stackoverflow.com/comment/86938497
score: 0
type: AnswerComment
has text: Your "fancy one liner" performs _way_ more checks that necessary. Is there a reason you think you need a one-liner? Take a look here for actual, efficient ways to calculate primes: https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n
type: Comment
comment on: http://stackoverflow.com/a/49021021

http://stackoverflow.com/comment/85142262
comment on: http://stackoverflow.com/a/49068495
score: 0
type: Comment
has text: Thanks for you time Edwin ! IT still does not work but i think that i have an idea : when i print my name_box, those ' are indeed missing. Should i conclude that name_box is not a real list?
type: AnswerComment

http://stackoverflow.com/a/48967247
answers question: http://stackoverflow.com/q/48967112
accepted answer of: http://stackoverflow.com/q/48967112
downvote count: 0
has comment: http://stackoverflow.com/comment/84940230
has body: How does this fit you needs? import pandas as pd s = '''\ DOCNO RSLTN1 MP00059189 72386.0 MP0059189A 65492.0 MP00066187 96497.0 MP00061663 43677.0 MP00063387 42465.0''' # Recreate dataframe df = pd.read_csv(pd.compat.StringIO(s), sep='\s+') # Create mask # We sort to make sure we keep only highest value # Remove all non-digit according to: https://stackoverflow.com/questions/44117326/ m = (df.sort_values(by='RSLTN1',ascending=False)['DOCNO'] .str.extract('(\d+)', expand=False) .astype(int).duplicated()) # Apply inverted `~` mask df = df.loc[~m] Resulting df: DOCNO RSLTN1 0 MP00059189 72386.0 2 MP00066187 96497.0 3 MP00061663 43677.0 4 MP00063387 42465.0 In this example the following row was removed: MP0059189A 65492.0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84954071
has comment: http://stackoverflow.com/comment/84940440
has comment: http://stackoverflow.com/comment/84940214
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/107785862
has text: @mrangry777 Did you get it working then? If so, can you please tell how?
type: QuestionComment
comment on: http://stackoverflow.com/q/49108322
type: Comment
score: 0

http://stackoverflow.com/a/49088642
has comment: http://stackoverflow.com/comment/85183471
has comment: http://stackoverflow.com/comment/85182824
accepted answer of: http://stackoverflow.com/q/49088524
has comment: http://stackoverflow.com/comment/85183736
has comment: http://stackoverflow.com/comment/85183603
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85183789
has comment: http://stackoverflow.com/comment/85183553
type: Answer
has comment: http://stackoverflow.com/comment/85184203
has comment: http://stackoverflow.com/comment/85183675
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85183886
has body: Try to update your script as below: wait.until(EC.presence_of_element_located((By.ID, "autocomplete"))).send_keys("5068 SW 141st Ave, Miramar, FL 33027") wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "pac-item"))).click() wait.until(EC.presence_of_element_located((By.ID, "map-search"))).click() This should allow you to confirm your choice (the address you want to use) before searching for results Update If first suggestion doesn't work, try below one input_address = wait.until(EC.presence_of_element_located((By.ID, "autocomplete"))) input_address.send_keys("5068 SW 141st Ave, Miramar, FL 33027") suggestion = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "pac-item"))) input_address.send_keys(Keys.DOWN) suggestion.click() input_address.send_keys(Keys.RETURN)
has comment: http://stackoverflow.com/comment/85183620
answers question: http://stackoverflow.com/q/49088524

http://stackoverflow.com/q/49035812
has comment: http://stackoverflow.com/comment/85297596
has comment: http://stackoverflow.com/comment/85325736
type: Question
has comment: http://stackoverflow.com/comment/85325305
has body: I am working on text analytics project comparing two different reports at a time and saving the results into pandas data frame. I was able to get cosine and jacard similarities, but need to be sure that I get the right measures. As arguments I use file names that are located at the given folder. For the cosine_sim I use the following code: import re, math from collections import Counter WORD = re.compile(r'\w+') def text_to_vector(text): words = WORD.findall(text) return Counter(words) def get_cosine(file1, file2): t1 = file(Input_path+'/'+file1).read().replace('\n',' ') t2 = file(Input_path+'/'+file2).read().replace('\n',' ') vec1 = text_to_vector(t1) vec2 = text_to_vector(t2) intersection = set(vec1.keys()) &amp; set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in intersection]) sum1 = sum([vec1[x]**2 for x in vec1.keys()]) sum2 = sum([vec2[x]**2 for x in vec2.keys()]) denominator = math.sqrt(sum1) * math.sqrt(sum2) if not denominator: return 0.0 else: return float(numerator) / denominator For Jaccard I got the following: def get_jaccard(file1, file2): t1 = file(Input_path+'/'+file1).read().replace('\n',' ') t2 = file(Input_path+'/'+file2).read().replace('\n',' ') vec1 = text_to_vector(t1) vec2 = text_to_vector(t2) numerator = len(set(vec1.keys()).intersection(set(vec2.keys()))) denominator = float(len(set(vec1.keys())) + len(set(vec2.keys())) -numerator) if not denominator: return 0.0 else: return float(numerator) / denominator The results work fine on small string examples, but I'm not sure if they are correct on big test files, especially Jaccard as my results are a bit different from distance.jaccard (I use lists to feed it, not dictionaries) Regarding the other metrics, please confirm that sim_simple can be calculated by using the following: from difflib import SequenceMatcher def similar(file1, file2): s1 = file(Input_path+'/'+file1).read().replace('\n',' ') s2 = file(Input_path+'/'+file2).read().replace('\n',' ') list1 = list(set(text_to_list(s1)))…
has comment: http://stackoverflow.com/comment/85325652
answer count: 1
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/49160357
accepted answer: http://stackoverflow.com/a/49160357
tagged with: python
tagged with: nlp
has title: How to compare metrics between two large texts - cosine, Jaccard similarities, Sim_MinEdit (Sim_String) and Sim_Simple in Python
downvote count: 0
has comment: http://stackoverflow.com/comment/85274897
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85243543

http://stackoverflow.com/a/48981212
has comment: http://stackoverflow.com/comment/84967516
upvote count: 2
has comment: http://stackoverflow.com/comment/84967539
downvote count: 1
has body: Use audit_items_list.items() if you are using Python 3 or audit_items_list.iteritems() if you are using Python 2.
answers question: http://stackoverflow.com/q/48981183
type: Answer
score: 1

http://stackoverflow.com/q/49036546
tagged with: python
has comment: http://stackoverflow.com/comment/85144482
answer count: 0
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/85139859
tagged with: gridster
has body: In my app which uses django I am displaying gridster widgets.When I run the HTML/Javascript page directly the widgets are arranged as written in HTML code.But when I use same webpage in my django app by placing it in template and keeping static files(gridster.js and some css) in corresponding folders all the widgets just load in a single line Following is my HTML Code &lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Demo &amp;raquo; Add Delete Widget &amp;raquo; gridster.js&lt;/title&gt; {% load static %} &lt;link rel="stylesheet" type="text/css" href="{% static 'css/demo.css' %}"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'js/jquery.gridster.min.css' %}"&gt; &lt;script src="{% static 'js/jquery.min.js' %}"&gt;&lt;/script&gt; &lt;script src="{% static 'js/jquery.gridster.min.js' %}" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Add and Remove Widget Dynamically&lt;/h1&gt; &lt;p&gt;When you remove a widget,the widget below it will always remain in the same column.Widget from next column wont come in place of widget removed.Gridster is designed that way&lt;/p&gt; &lt;a href="https://github.com/ducksboard/gridster.js/issues/338" target="_blank"&gt; Click to know more&lt;/a&gt; &lt;div class="gridster"&gt; &lt;ul&gt; &lt;li data-row="1" data-col="1" data-sizex="1" data-sizey="1"&gt;&lt;button class="delete-button" style="float: right;"&gt;-&lt;/button&gt;&lt;h3&gt;1&lt;/h3&gt;&lt;/li&gt; &lt;li data-row="1" data-col="2" data-sizex="1" data-sizey="1"&gt;&lt;button class="delete-button" style="float: right;"&gt;-&lt;/button&gt;&lt;h3&gt;2&lt;/h3&gt;&lt;/li&gt; &lt;li data-row="1" data-col="3" data-sizex="1" data-sizey="1"&gt;&lt;button class="delete-button" style="float: right;"&gt;-&lt;/button&gt;&lt;h3&gt;3&lt;/h3&gt;&lt;/li&gt; &lt;li data-row="1" data-col="4" data-sizex="1" data-sizey="1"&gt;&lt;button class="delete-button" style="float: right;"&gt;-&lt;/button&gt;&lt;h3&gt;4&lt;/h3&gt;&lt…
has title: Gridster widgets appearing vertically in django webpage
score: 0
tagged with: javascript
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/138922255
type: Comment
has text: ... no matter if aggregator or self-written code... I supposed, but am not stating it as fact - sorry if it sounds such... - it is not the essence of my answer
comment on: http://stackoverflow.com/a/78745826
type: AnswerComment
score: 0

http://stackoverflow.com/a/49189511
has body: Make sure to specify the python version you want when you create the virtualenv using the --python or -p option, as in: $ virtualenv -p /path/to/python2.7 cmle-env
answers question: http://stackoverflow.com/q/49076671
score: 0
accepted answer of: http://stackoverflow.com/q/49076671
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49109582
score: 1
tagged with: user-defined-types
favorite count: 0
has title: cx_Oracle - conversion between Oracle type 2010 and native type 3000 is not implemented
type: Question
accepted answer: http://stackoverflow.com/a/49111552
tagged with: python
linked to: http://stackoverflow.com/q/49094036
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49111552
type: AnsweredQuestion
tagged with: oracle-database
has body: I am trying to extract data from User defined type (UDT) using cx_Oracle. I am able extract data for some UDT without problems but for one specific UDT I am not able to extract the data. Structure of types in Oracle: CREATE OR REPLACE TYPE graphic_component AS OBJECT ( type NUMBER(6), source_type NUMBER(4), meta_type_id VARCHAR2(50 CHAR), name VARCHAR2(100 CHAR), extension_info VARCHAR2(500 CHAR), symbology_tokens VARCHAR2(2000 CHAR) ); CREATE OR REPLACE TYPE graphic_component_array AS VARRAY (10000) OF graphic_component; In Python using this code for extracting UDT (code from here): def ObjectRepr(obj): if obj.type.iscollection: returnValue = [] for value in obj.aslist(): if isinstance(value, cx_Oracle.Object): value = ObjectRepr(value) returnValue.append(value) else: returnValue = {} for attr in obj.type.attributes: value = getattr(obj, attr.name) if value is None: continue elif isinstance(value, cx_Oracle.Object): value = ObjectRepr(value) returnValue[attr.name] = value return returnValue Then if I try to extract data from UDT I am getting this error: &lt;cx_Oracle.Object GRAPHIC_COMPONENT_ARRAY at 0x26c9f10&gt; Traceback (most recent call last): File "C:/Users/petr.silhak/PycharmProjects/migration-to-postgresql/test_parsing.py", line 34, in &lt;module&gt; print(ObjectRepr(complex[0][0])) File "C:/Users/petr.silhak/PycharmProjects/migration-to-postgresql/test_parsing.py", line 9, in ObjectRepr value = ObjectRepr(value) File "C:/Users/petr.silhak/PycharmProjects/migration-to-postgresql/test_parsing.py", line 14, in ObjectRepr value = getattr(obj, attr.name) cx_Oracle.DatabaseError: DPI-1014: conversion between Oracle type 2010 and native type 3000 is not implemented It looks like a problem with Oracle odpi conversion of datatypes. In this specific example data looks something like this (from SQL developer): GRAPHIC_COMPONENT(1007,17,'gtda_5012101_1',NULL,NULL,NULL,NULL)
tagged with: cx-oracle
downvote count: 0

http://stackoverflow.com/q/48965309
score: 6
has comment: http://stackoverflow.com/comment/84936789
has comment: http://stackoverflow.com/comment/84936842
type: Question
tagged with: raspbian
linked to: http://stackoverflow.com/q/53347759
upvote count: 6
has body: I have installed raspbian os on raspberry pi 3 model b. I have to perform a project which involves use of h5py. The os already came preinstalled with python 2.7 and 3.5 With the help of pip, I installed h5py and it was successful, for python 3.5. ImportError: libhdf5_serial.so.100: cannot open shared object file: No such file or directory I don't know how to proceed with this error, can somebody please point out an appropriate way to handle this error?
answer count: 2
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/49707904
favorite count: 0
tagged with: h5py
type: UnansweredQuestion
has title: h5py import error on libhdf5_serial.so.100
tagged with: python
has answer: http://stackoverflow.com/a/55821255
downvote count: 0

http://stackoverflow.com/comment/92629457
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49105761
type: AnswerComment
has text: I had this problem when behind a corporate proxy, and was able to install the package by connecting to a different (approved !) network.

http://stackoverflow.com/comment/84952414
score: 7
has text: Hope you have __init__ file in all your modules.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48973742

http://stackoverflow.com/q/49070041
has comment: http://stackoverflow.com/comment/85145989
has comment: http://stackoverflow.com/comment/85145363
has title: Less clunky way to generate properties?
tagged with: getter-setter
has body: TLDR: What is the best way to build a class with generic property attributes and one can specify the getter and setter upon building those attributes? Background: I'm trying to make an object oriented representation of a SCPI command structure with Python. After parsing, the command layers are (sub-)objects and setting/getting the lowest command-object will actually communicate with a device to set/get its parameter. The problem I encounter is the assignment of generic getter/setter functions to the command-object, acting like a property. I had a rough time with __setattr__ / __getattr__ as I always ran into the recursive problem. It would be cool if there was a distinction wether an attribute is set/get during class building and in its instantiated/runtime version. Or even better: is it possible to make an attribute a property "object"? Something like: foo = property() foo.__getter__ = lambda paramName : devcontroller.request(paramName) foo.__setter__ = lambda paramName, paramValue : devcontroller.demand(paramName, paramValue) setattr(self, paramName, foo) but apparently this is not possible (read-only). The best solution for now is the one below, but it feels very clunky. One cannot tab-complete the command-object for instance. class SCPITree(object): def __init__(self, cmd, branch): self.__dict__['building'] = True self.__dict__['params'] = {} # parse tree for k, v in branch.items(): catCmd = '{}:{}'.format(cmd, k[1]) param = k[0] if isinstance(v, dict): # still a dictionary, so unpack #setattr(self, param, SCPITree(catCmd, v)) self.__dict__[param] = SCPITree(catCmd, v) else: # have the value type, so this is a leaf print('{} of {}'.format(catCmd, v)) self.__dict__['params'][param] = {'cmd': catCmd, 'type': v} #setattr(self, param, v()) del self.__dict__['building'] def __getattr__(self, name): '''Requests the device for parameter''' param = self.__dict__['params'].get(name) if param: request = param['cmd']+'?' print('Requesting device with: {}'.format(request)) …
tagged with: generics
has comment: http://stackoverflow.com/comment/85225772
type: UnansweredQuestion
tagged with: python
tagged with: properties
answer count: 0
score: 0
type: Question

http://stackoverflow.com/a/48966322
upvote count: 3
has comment: http://stackoverflow.com/comment/84938431
downvote count: 1
has comment: http://stackoverflow.com/comment/84938501
has body: No, asyncio is not thread safe. Generally only one thread should have control over an event loop and/or a resource associated to the event loop. If some other thread wants to access it, it should do it via special methods, like call_soon_threadsafe.
answers question: http://stackoverflow.com/q/48966277
type: Answer
has comment: http://stackoverflow.com/comment/84939243
score: 2

http://stackoverflow.com/a/56345908
answers question: http://stackoverflow.com/q/48994440
has comment: http://stackoverflow.com/comment/117213665
has body: Middleware Solution for Flask Blueprints This is the same solution proposed by Matthew Story (which is the perfect solution IMHO - thanks Matthew), adapted for Flask Blueprints. The secret sauce here is to get hold of the app context using the current_app proxy. Read up here for more information (http://flask.pocoo.org/docs/1.0/appcontext/) Let's assume the AfterThisResponse &amp; AfterThisResponseMiddleware classes are placed in a module at .utils.after_this_response.py Then where the Flask object creation occurs, you might have, eg... __init__.py from api.routes import my_blueprint from .utils.after_this_response import AfterThisResponse app = Flask( __name__ ) AfterThisResponse( app ) app.register_blueprint( my_blueprint.mod ) And then in your blueprint module... a_blueprint.py from flask import Blueprint, current_app mod = Blueprint( 'a_blueprint', __name__, url_prefix=URL_PREFIX ) @mod.route( "/some_resource", methods=['GET', 'POST'] ) def some_resource(): # do some stuff here if you want @current_app.after_this_response def post_process(): # this will occur after you finish processing the route &amp; return (below): time.sleep(2) print("after_response") # do more stuff here if you like &amp; then return like so: return "Success!\n"
downvote count: 0
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/119713369
score: 8

pyqt5
tags question: http://stackoverflow.com/q/49078973
tags question: http://stackoverflow.com/q/49102849
type: Tag
tags question: http://stackoverflow.com/q/49106763
tags question: http://stackoverflow.com/q/49109428
tags question: http://stackoverflow.com/q/49118384
tags question: http://stackoverflow.com/q/49119611
tags question: http://stackoverflow.com/q/49048136
tags question: http://stackoverflow.com/q/49034697
tags question: http://stackoverflow.com/q/48998470
tags question: http://stackoverflow.com/q/49087539
tags question: http://stackoverflow.com/q/48988871
tags question: http://stackoverflow.com/q/49085620
tags question: http://stackoverflow.com/q/49007811
tags question: http://stackoverflow.com/q/49104588
tags question: http://stackoverflow.com/q/49077083
tags question: http://stackoverflow.com/q/49043570
tags question: http://stackoverflow.com/q/49100091
tags question: http://stackoverflow.com/q/49100389
tags question: http://stackoverflow.com/q/49109326
tags question: http://stackoverflow.com/q/49081417
tags question: http://stackoverflow.com/q/49022442
tags question: http://stackoverflow.com/q/49068100
tags question: http://stackoverflow.com/q/49055790
tags question: http://stackoverflow.com/q/49069305
tags question: http://stackoverflow.com/q/49005963
tags question: http://stackoverflow.com/q/48978661
tags question: http://stackoverflow.com/q/49081841
tags question: http://stackoverflow.com/q/49048294
tag name: pyqt5
tags question: http://stackoverflow.com/q/48978106
tags question: http://stackoverflow.com/q/49053370
tags question: http://stackoverflow.com/q/49024118
tags question: http://stackoverflow.com/q/48986753
tags question: http://stackoverflow.com/q/49060506

http://stackoverflow.com/comment/135160453
has text: This doesn't work if the log call internally has interpolation in it on subsequent lines
comment on: http://stackoverflow.com/a/49106363
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48968770
accepted answer of: http://stackoverflow.com/q/48966963
type: AcceptedAnswer
downvote count: 0
has body: &gt;&gt;&gt; lst = [-2.22,1.4,2,3,4,5,6,0,-2,-3,-4,-5,7,8,9] &gt;&gt;&gt; correct = [[-2.22],[1.4,2,3,4,5,6,0],[-2,-3,-4,-5],[7,8,9]] &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; result = [list(g) for _, g in groupby(lst, key=lambda a: a &lt; 0)] &gt;&gt;&gt; correct == result True
has comment: http://stackoverflow.com/comment/84955521
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48966963

http://stackoverflow.com/q/48968836
has body: I was running some Python code and realized when I instantiate Pool with only one process, for instance: from multiprocessing.pool import Pool from time import sleep def f(i): print(i) sleep(10) with Pool(1) as p: p.map(f, [i for i in range(100)]) Actually five processes are currently running. I've also noticed a pattern going on: if I instantiate Pool with 1, 2,3,... processes the number of processes launched by Python are 5,6,7,... I'm curious: Does Pool use three process for management?
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/84943275
score: 0
accepted answer: http://stackoverflow.com/a/49000972
answer count: 1
has comment: http://stackoverflow.com/comment/84943454
has answer: http://stackoverflow.com/a/49000972
tagged with: python
has title: Python pool process management
has comment: http://stackoverflow.com/comment/84943313
type: AnsweredQuestion

string
tags question: http://stackoverflow.com/q/49064817
tags question: http://stackoverflow.com/q/49100943
tags question: http://stackoverflow.com/q/48995995
tags question: http://stackoverflow.com/q/48997401
tags question: http://stackoverflow.com/q/49078472
tags question: http://stackoverflow.com/q/48969595
tags question: http://stackoverflow.com/q/48994571
tags question: http://stackoverflow.com/q/49049852
tags question: http://stackoverflow.com/q/48977541
tags question: http://stackoverflow.com/q/49084255
tags question: http://stackoverflow.com/q/49073252
tags question: http://stackoverflow.com/q/48985875
tags question: http://stackoverflow.com/q/49088926
tags question: http://stackoverflow.com/q/49084842
tags question: http://stackoverflow.com/q/49097760
tags question: http://stackoverflow.com/q/49016246
tags question: http://stackoverflow.com/q/48978459
tags question: http://stackoverflow.com/q/49008237
tags question: http://stackoverflow.com/q/48978771
tags question: http://stackoverflow.com/q/48993565
tags question: http://stackoverflow.com/q/49039920
tags question: http://stackoverflow.com/q/48977945
tags question: http://stackoverflow.com/q/48995958
tags question: http://stackoverflow.com/q/49034325
tags question: http://stackoverflow.com/q/48990106
tags question: http://stackoverflow.com/q/49020711
tags question: http://stackoverflow.com/q/48997007
tags question: http://stackoverflow.com/q/49077374
tags question: http://stackoverflow.com/q/49061385
tags question: http://stackoverflow.com/q/49054468
tag name: string
tags question: http://stackoverflow.com/q/48992197
tags question: http://stackoverflow.com/q/49078921
tags question: http://stackoverflow.com/q/49091514
tags question: http://stackoverflow.com/q/49010207
tags question: http://stackoverflow.com/q/49038928
tags question: http://stackoverflow.com/q/49040364
tags question: http://stackoverflow.com/q/48975614
tags question: http://stackoverflow.com/q/49035791
tags question: http://stackoverflow.com/q/48996679
tags question: http://stackoverflow.com/q/49091846
tags question: http://stackoverflow.com/q/48996879
tags question: http://stackoverflow.com/q/49062059
tags question: http://stackoverflow.com/q/49085712
tags question: http://stackoverflow.com/q/48989472
type: Tag
tags question: http://stackoverflow.com/q/49101659
tags question: http://stackoverflow.com/q/49060841
tags question: http://stackoverflow.com/q/49051468
tags question: http://stackoverflow.com/q/49084484
tags question: http://stackoverflow.com/q/49094294
tags question: http://stackoverflow.com/q/49117653
tags question: http://stackoverflow.com/q/49016940
tags question: http://stackoverflow.com/q/48975344
tags question: http://stackoverflow.com/q/49087139
tags question: http://stackoverflow.com/q/49109400
tags question: http://stackoverflow.com/q/49012114
tags question: http://stackoverflow.com/q/49095635
tags question: http://stackoverflow.com/q/49018080
tags question: http://stackoverflow.com/q/49100629
tags question: http://stackoverflow.com/q/48983025
tags question: http://stackoverflow.com/q/49044235
tags question: http://stackoverflow.com/q/49070653
tags question: http://stackoverflow.com/q/49074623
tags question: http://stackoverflow.com/q/49091132
tags question: http://stackoverflow.com/q/49087282
tags question: http://stackoverflow.com/q/49088385
tags question: http://stackoverflow.com/q/48973202
tags question: http://stackoverflow.com/q/49023123
tags question: http://stackoverflow.com/q/49036807
tags question: http://stackoverflow.com/q/49068634
tags question: http://stackoverflow.com/q/49116356
tags question: http://stackoverflow.com/q/49077866
tags question: http://stackoverflow.com/q/48966912
tags question: http://stackoverflow.com/q/48969483
tags question: http://stackoverflow.com/q/49007346
tags question: http://stackoverflow.com/q/48978412
tags question: http://stackoverflow.com/q/49085756

http://stackoverflow.com/comment/85077509
score: 1
type: Comment
has text: add example df in code please
type: QuestionComment
comment on: http://stackoverflow.com/q/49036237

http://stackoverflow.com/q/49042221
tagged with: algorithm
has answer: http://stackoverflow.com/a/49042271
has title: Converting a column of String to integers?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49042251
type: UnansweredQuestion
tagged with: python
has body: `# Convert string column to integer def str_column_to_int(dataset, column): class_values = [row[column] for row in dataset] unique = set(class_values) lookup = dict() for i, value in enumerate(unique): lookup[value] = i for row in dataset: row[column] = lookup[row[column]] return lookup` The above code is the most basic machine learning snippet to convert a column of string to integers(or one hot encoding).However I am having difficulty understanding the code esp. class_values = [row[column] for row in dataset] unique = set(class_values) what does these two lines do that makes it to do one hot encoding?
tagged with: machine-learning
type: Question

http://stackoverflow.com/a/49093459
has body: a couple of nested zips &amp; slices do the trick to build dicts in a list comprehension, as value of the outer dict: Name = ['John','Mary','Serena','Felicia'] Data = ['26','179','25','164','29','149','29','167'] result = {'people':[{'Name' : name, 'Age' : age, 'Height' : height} for name,(age,height) in zip(Name,zip(Data[::2],Data[1::2]))]} print(result) prints: {'people': [{'Name': 'John', 'Height': '179', 'Age': '26'}, {'Name': 'Mary', 'Height': '164', 'Age': '25'}, {'Name': 'Serena', 'Height': '149', 'Age': '29'}, {'Name': 'Felicia', 'Height': '167', 'Age': '29'}]} if you don't want to create "hard" slices, use itertools.islice, also would be interesting to convert integer values as integer, which avoids the easy trap of lexicographical compare of integers as strings later on: from itertools import islice result = {'people':[{'Name' : name, 'Age' : int(age), 'Height' : int(height)} for name,age,height in zip(Name,islice(Data,None,None,2),islice(Data,1,None,2))]} (and also thanks to comments, no need to nest zip statements) result: {'people': [{'Height': 179, 'Age': 26, 'Name': 'John'}, {'Height': 164, 'Age': 25, 'Name': 'Mary'}, {'Height': 149, 'Age': 29, 'Name': 'Serena'}, {'Height': 167, 'Age': 29, 'Name': 'Felicia'}]}
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49093428
answers question: http://stackoverflow.com/q/49093428
type: Answer
upvote count: 5
downvote count: 0

http://stackoverflow.com/q/49116570
has comment: http://stackoverflow.com/comment/85242275
tagged with: python
has comment: http://stackoverflow.com/comment/85242176
score: 0
has comment: http://stackoverflow.com/comment/85239546
has comment: http://stackoverflow.com/comment/85242149
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85242304
has comment: http://stackoverflow.com/comment/85246539
has comment: http://stackoverflow.com/comment/85243158
has comment: http://stackoverflow.com/comment/85245044
has title: Tensorflow memory issue using add
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/85242766
has comment: http://stackoverflow.com/comment/85259005
has body: I am basically trying to recursively update a tensor object of dimension (1,batch_size) in a for loop in my tensorflow script. For example: def __cost( self, trueX, trueY, reuse ): x = tf.expand_dims( trueX, 0 ) X = tf.tile( x, [self.config['L'],1,1] ) # X -&gt; A A, mu_phi1, ls_phi1 = self.build_nn_gauss( x, self.config['sizeq_x2a'], self.config['dim_a'], self.config['L'], 'phi1', reuse ) _cost = -tf.reduce_sum( ls_phi1, -1 ) # AX -&gt; G (this is the semiclassifier) AX = tf.concat( [ A, X ], -1 ) pre_G = self.build_nn( AX, self.config['sizeq_ax2g'], '0phig2', reuse ) log_pred_G = tf.layers.dense( pre_G, self.config['dim_g'], name='0phi2g', reuse=reuse ) log_pred_G = log_pred_G - tf.reduce_logsumexp( log_pred_G, -1, keep_dims=True ) pred_G = tf.exp( log_pred_G ) if trueY is not None: # y = tf.expand_dims( trueY, 0 ) # Y = tf.tile( y, [self.config['L'],1,1] ) g = tf.expand_dims( trueG, 0 ) G = tf.tile( g, [self.config['L'],1,1] ) depth = 2 _cost_supervised_bi_label = 0 _cost_supervised_multi_label = tf.reduce_sum( tf.nn.sigmoid_cross_entropy_with_logits( logits=log_pred_G, labels= G), -1 ) for i in range(self.config['dim_y']): y = tf.expand_dims( tf.one_hot(tf.to_int32(trueY[:,i], name='ToInt32'), depth, dtype=self.dtype ), 0 ) Y = tf.tile( y, [self.config['L'],1,1] ) # AGX -&gt; Y (this is the classifier) AGX = tf.concat( [ A, G, X ], -1 ) pre_Y = self.build_nn( AGX, self.config['sizeq_agx2y'], '{}phi2'.format(i), reuse ) log_pred_Y = tf.layers.dense( pre_Y, 2, name='{}phi2y'.format(i), reuse=reuse ) log_pred_Y = log_pred_Y - tf.reduce_logsumexp( log_pred_Y, -1, keep_dims=True ) pred_Y = tf.exp( log_pred_Y ) # reuse layers if created or else create a new layer try: _cost += self.__add(_cost, self.__eval_cost_given_axgy( A, X, Y, G, True )) except: _cost += self.__add(_cost, self.__eval_cost_given_axgy( A, X, Y, G, False )) b = _cost _cost_supervised_bi_label += -tf.reduce_sum( tf.multiply( Y, log_pred_Y ), -1 ) Running it like this, consumes a lot of gpu memory. I …
has comment: http://stackoverflow.com/comment/85240717
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84958615
comment on: http://stackoverflow.com/q/48975805
score: 0
has text: Django, python cannot change the client side at input to the webpage without a request, meaning without a refresh. Which means you'd want to use javascript for that action. However if you are okay with page refreshing you can simply make a button that goes to `www.ws.com/?waist=x` and when user goes to that link it simply changes the `waist` to `x` on the server side
type: Comment
type: QuestionComment

datetime
tags question: http://stackoverflow.com/q/49039328
tags question: http://stackoverflow.com/q/49028239
tags question: http://stackoverflow.com/q/49118032
tags question: http://stackoverflow.com/q/49068219
tags question: http://stackoverflow.com/q/49069020
tags question: http://stackoverflow.com/q/48988322
tags question: http://stackoverflow.com/q/49026570
tags question: http://stackoverflow.com/q/48978803
tags question: http://stackoverflow.com/q/49084285
tags question: http://stackoverflow.com/q/49035978
tags question: http://stackoverflow.com/q/49098309
tags question: http://stackoverflow.com/q/49026487
tags question: http://stackoverflow.com/q/48992794
tags question: http://stackoverflow.com/q/49114528
tags question: http://stackoverflow.com/q/49078417
tags question: http://stackoverflow.com/q/49048853
tags question: http://stackoverflow.com/q/49054893
tags question: http://stackoverflow.com/q/49100283
tags question: http://stackoverflow.com/q/49071561
tag name: datetime
tags question: http://stackoverflow.com/q/49004771
tags question: http://stackoverflow.com/q/49036206
tags question: http://stackoverflow.com/q/48993174
tags question: http://stackoverflow.com/q/49078478
tags question: http://stackoverflow.com/q/49105693
type: Tag
tags question: http://stackoverflow.com/q/48967207
tags question: http://stackoverflow.com/q/48975419
tags question: http://stackoverflow.com/q/48998640
tags question: http://stackoverflow.com/q/48991892
tags question: http://stackoverflow.com/q/49044984
tags question: http://stackoverflow.com/q/49052264
tags question: http://stackoverflow.com/q/49107868
tags question: http://stackoverflow.com/q/49048143
tags question: http://stackoverflow.com/q/48973005
tags question: http://stackoverflow.com/q/49018080
tags question: http://stackoverflow.com/q/49110185
tags question: http://stackoverflow.com/q/49100622
tags question: http://stackoverflow.com/q/49059954

http://stackoverflow.com/a/49020538
answers question: http://stackoverflow.com/q/49019371
has body: One way or other you need to add the extra dimension to the arrays. In [2]: a = np.zeros(2) ...: b = np.ones(2) ...: stack lets you choose the new dimension: In [3]: np.stack((a,b),axis=1) Out[3]: array([[0., 1.], [0., 1.]]) In [4]: np.stack((a,b),axis=0) Out[4]: array([[0., 0.], [1., 1.]]) np.array also does it, like stack with axis 0 - transpose to get the columns: In [5]: np.array((a,b)).T Out[5]: array([[0., 1.], [0., 1.]]) column_stack is an older stack that add the right dimensions for this case as well. In [6]: np.column_stack((a,b)) Out[6]: array([[0., 1.], [0., 1.]]) It's a good a idea to learn to do this with concatenate and your own addition of dimensions. And look at the code for the various stack functions to see how they do the same task.
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/49089158
tagged with: string-formatting
tagged with: django
tagged with: python
has title: How to display database timestamp in django, sqlite and python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85208091
has comment: http://stackoverflow.com/comment/85208177
has body: I'm running Django with SQLite, and creating a log. I save the results of timezone.now() in the database in Django, and when I retrieve it for a report outside of Django, it looks like this example: 2018-03-02 17:44:17.868267 All very well, but 1) this does not say the timezone, and I don't think it's UTC. I was there for the events, and think it's in America/Los Angeles time. 2) I want to pretty-print the timestamp, and I'm getting lost in all the documentation that's about naive and aware and pytz and what seems like a bunch of things even further from my needs. So: presuming all the action remains in the same time zone, what functions are usable for formatting this time. For instance with day of the week, Month names, AM/PM and so on. How would I change the times to print in, for instance, America/New York time?
has comment: http://stackoverflow.com/comment/85184516
has comment: http://stackoverflow.com/comment/85184142
has comment: http://stackoverflow.com/comment/85208119
score: 0
tagged with: sqlite
has comment: http://stackoverflow.com/comment/85185377
type: UnansweredQuestion
tagged with: time

http://stackoverflow.com/comment/89451383
comment on: http://stackoverflow.com/a/49039412
score: 4
type: AnswerComment
type: Comment
has text: See below for the correct answer. The above is incorrect @Steven

http://stackoverflow.com/a/48997926
has comment: http://stackoverflow.com/comment/85002132
has body: This should work [X[i]y for i, y in enumerate(ixs)] EDIT: I just noticed you wanted no loop solution.
answers question: http://stackoverflow.com/q/48997698
score: 0
upvote count: 1
downvote count: 1
type: Answer

list
tags question: http://stackoverflow.com/q/49037829
type: Tag
tags question: http://stackoverflow.com/q/48999291
tags question: http://stackoverflow.com/q/49098605
tags question: http://stackoverflow.com/q/48991127
tags question: http://stackoverflow.com/q/49118619
tags question: http://stackoverflow.com/q/48978404
tags question: http://stackoverflow.com/q/49102807
tags question: http://stackoverflow.com/q/49099838
tags question: http://stackoverflow.com/q/49002409
tags question: http://stackoverflow.com/q/48972764
tags question: http://stackoverflow.com/q/48988580
tags question: http://stackoverflow.com/q/49027866
tags question: http://stackoverflow.com/q/49010129
tags question: http://stackoverflow.com/q/48984319
tags question: http://stackoverflow.com/q/49036317
tags question: http://stackoverflow.com/q/49030181
tags question: http://stackoverflow.com/q/49039340
tags question: http://stackoverflow.com/q/49008508
tags question: http://stackoverflow.com/q/49107405
tags question: http://stackoverflow.com/q/48978153
tags question: http://stackoverflow.com/q/49095374
tags question: http://stackoverflow.com/q/49027108
tags question: http://stackoverflow.com/q/49099798
tags question: http://stackoverflow.com/q/49068539
tags question: http://stackoverflow.com/q/49000790
tags question: http://stackoverflow.com/q/49020187
tags question: http://stackoverflow.com/q/49000834
tags question: http://stackoverflow.com/q/49104670
tags question: http://stackoverflow.com/q/48987179
tags question: http://stackoverflow.com/q/49032032
tags question: http://stackoverflow.com/q/48981294
tags question: http://stackoverflow.com/q/48996679
tags question: http://stackoverflow.com/q/48980908
tags question: http://stackoverflow.com/q/49118267
tags question: http://stackoverflow.com/q/49080517
tags question: http://stackoverflow.com/q/49103672
tags question: http://stackoverflow.com/q/49095885
tags question: http://stackoverflow.com/q/49001710
tags question: http://stackoverflow.com/q/48973570
tags question: http://stackoverflow.com/q/48970707
tags question: http://stackoverflow.com/q/49100629
tags question: http://stackoverflow.com/q/49109485
tags question: http://stackoverflow.com/q/49102211
tags question: http://stackoverflow.com/q/49061721
tags question: http://stackoverflow.com/q/49049291
tags question: http://stackoverflow.com/q/49015592
tags question: http://stackoverflow.com/q/48972948
tags question: http://stackoverflow.com/q/49003983
tags question: http://stackoverflow.com/q/49004682
tags question: http://stackoverflow.com/q/49112788
tags question: http://stackoverflow.com/q/48973826
tags question: http://stackoverflow.com/q/49093428
tags question: http://stackoverflow.com/q/49119536
tags question: http://stackoverflow.com/q/49008020
tags question: http://stackoverflow.com/q/49043989
tags question: http://stackoverflow.com/q/49017958
tags question: http://stackoverflow.com/q/49051468
tag name: list
tags question: http://stackoverflow.com/q/48974122
tags question: http://stackoverflow.com/q/49029078
tags question: http://stackoverflow.com/q/49095192
tags question: http://stackoverflow.com/q/49068153
tags question: http://stackoverflow.com/q/49114267
tags question: http://stackoverflow.com/q/49093916
tags question: http://stackoverflow.com/q/49103873
tags question: http://stackoverflow.com/q/49016940
tags question: http://stackoverflow.com/q/48983557
tags question: http://stackoverflow.com/q/49074599
tags question: http://stackoverflow.com/q/48986755
tags question: http://stackoverflow.com/q/48991252
tags question: http://stackoverflow.com/q/49039093
tags question: http://stackoverflow.com/q/49084393
tags question: http://stackoverflow.com/q/48968962
tags question: http://stackoverflow.com/q/49036075
tags question: http://stackoverflow.com/q/49116839
tags question: http://stackoverflow.com/q/49001986
tags question: http://stackoverflow.com/q/49019281
tags question: http://stackoverflow.com/q/49002726
tags question: http://stackoverflow.com/q/49078547

http://stackoverflow.com/q/49013318
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49013974
has answer: http://stackoverflow.com/a/63596265
tagged with: python
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49013470
linked to: http://stackoverflow.com/q/32967201
type: Question
has answer: http://stackoverflow.com/a/49013974
has answer: http://stackoverflow.com/a/49013470
tagged with: dataframe
score: 4
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/102421388
downvote count: 0
has title: How to aggregate columns of sets?
has body: I have a pandas datafame where the rows in a particular column are sets of id's. I would like to aggregate across a 15min period and find all such unique id's. timestamp | ids | some_int 00:03:00 {id1, id2, id3} 5 00:10:00 {id2, id4, id7, id10} 9 00:25:00 {id7, id22, id24} 10 00:45:00 {id23, id30} 24 df.resample('15min').agg({'ids': ??, 'some_int': sum) I've tried sum and a few other transformations on the ids column but I don't quite have it yet.
favorite count: 0

http://stackoverflow.com/q/49000463
score: 0
has comment: http://stackoverflow.com/comment/85049986
tagged with: pygtk
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
tagged with: gtk
has body: Considering this code: import pygtk import gtk class TheBoard: def delete_event(self, widget, event, data=None): return False # confirms delete events def destroy(self, widget, data=None): gtk.main_quit() def __init__(self, grid=4): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Game Board") self.window.connect("delete_event", self.delete_event) self.window.connect("destroy", self.destroy) self.window.set_border_width(10) self.table = gtk.Table(grid, grid, True) self.spots = [gtk.Label('unk')] * (grid*grid) for index, spot in enumerate(self.spots): spot.set_text("%d" % index) x = index / grid y = index % grid spot.show() self.table.attach(spot, x, x+1, y, y+1, xoptions=gtk.FILL, yoptions=gtk.FILL, xpadding=0, ypadding=0) print "(%d, %d)" % (x, y) print "Attaching %s as (%d, %d, %d, %d)" % (spot.get_text(), x, x+1, y, y+1) self.window.add(self.table) self.table.show() self.window.show() def main(self): gtk.main() if __name__ == '__main__': gb = TheBoard() gb.main() And this output: main.py:30: GtkWarning: IA__gtk_table_attach: assertion 'child-&gt;parent == NULL' failed self.table.attach(spot, x, x+1, y, y+1, xoptions=gtk.FILL, yoptions=gtk.FILL, xpadding=0, ypadding=0) (0, 0) Attaching 0 as (0, 1, 0, 1) (0, 1) Attaching 1 as (0, 1, 1, 2) (0, 2) Attaching 2 as (0, 1, 2, 3) (0, 3) Attaching 3 as (0, 1, 3, 4) (1, 0) Attaching 4 as (1, 2, 0, 1) (1, 1) Attaching 5 as (1, 2, 1, 2) (1, 2) Attaching 6 as (1, 2, 2, 3) (1, 3) Attaching 7 as (1, 2, 3, 4) (2, 0) Attaching 8 as (2, 3, 0, 1) (2, 1) Attaching 9 as (2, 3, 1, 2) (2, 2) Attaching 10 as (2, 3, 2, 3) (2, 3) Attaching 11 as (2, 3, 3, 4) (3, 0) Attaching 12 as (3, 4, 0, 1) (3, 1) Attaching 13 as (3, 4, 1, 2) (3, 2) Attaching 14 as (3, 4, 2, 3) (3, 3) Attaching 15 as (3, 4, 3, 4) And the rendered board: The Game Board What am I doing wrong with either creating the gtk.Label or gtk.Table objects? I think I am messing up the gtk.Table.attach() function. Maybe I'm a bit dense at the moment, but I was ha…
has title: Python: Can't attach gtk.Label to spots in gtk.Table
answer count: 0
has comment: http://stackoverflow.com/comment/85049983
has comment: http://stackoverflow.com/comment/85020845
type: Question

http://stackoverflow.com/comment/85086483
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49040518
has text: Because all your objects are sharing `items`... that is a *class variable*, i.e. "static"

http://stackoverflow.com/q/49010636
has body: This code worked on Friday without problems and still running on a colleagues laptop, but I cannot run it anymore. As you can see in the screenshot, my editor doesnt find some moduls anymore and the pylint Error "E0401: Unable to import" occurs. The missing file exists in the folder Settings, as you can see in the Explorer on the left side. Today I deactivated/activated pylint, reinstalled vs code and python, added the init.py to Settings folder, tried the same code in eclipse, modified the Path enviroment variable and created the PYTHONPATH enviroment variable. All this with no success:/ I am greatful for each hint, which provide me to solve this problem. The error output as text: Windows PowerShell Copyright (C) Microsoft Corporation. Alle Rechte vorbehalten. PS C:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev&gt; &amp; C:/Python27/python.exe c:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev\Code\__TC__Template.py Traceback (most recent call last): File "c:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev\Code\__TC__Template.py", line 36, in &lt;module&gt; from Lib.IHR_EthApi import EthApi as ETH File "c:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev\Code\Lib\IHR_EthApi.py", line 6, in &lt;module&gt; from IHR_GeneralApi import GeneralApi as SYS File "c:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev\Code\Lib\IHR_GeneralApi.py", line 4, in &lt;module&gt; import IHR_TestSuiteConfig.py ImportError: No module named IHR_TestSuiteConfig.py PS C:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev&gt;
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85055728
accepted answer: http://stackoverflow.com/a/49059114
type: Question
has title: Import errors between some python moduls/functions/variables
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/85026067
tagged with: importerror
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49059114
tagged with: pylint
tagged with: python

http://stackoverflow.com/a/49088724
type: Answer
answers question: http://stackoverflow.com/q/49088443
has body: You are always better off using standard system facilities where they exist. Knowing that some locales use commas and decimal points differently I could not believe that Pandas would not use the formats of the locale. Sure enough a quick search revealed this gist, which explains how to make use of locales to convert strings to numbers. In essence you need to import locale and after you've built the dataframe call locale.setlocale to establish a locale that uses commas as decimal points and periods for separators, then apply the dataframe's applymapp method.
score: 0

http://stackoverflow.com/comment/85199271
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49096878
score: 1
has text: @Ajax1234 You don't really do much testing do you? Using `a` for the mode appends to the same file over and over. I just copy/paste your code and run it each time. Instead of creating a new file with `w`, you append to the previous file each time with `a`.

http://stackoverflow.com/comment/85161525
type: QuestionComment
has text: In addition, please read how to produce a [mcve]. It's a help us help you scenario.
comment on: http://stackoverflow.com/q/49077702
type: Comment
score: 1

http://stackoverflow.com/q/48972271
has comment: http://stackoverflow.com/comment/84950008
has comment: http://stackoverflow.com/comment/84949932
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84949787
tagged with: database
has body: I want to average of 10000 records but every 10 values(10 chunks out of 10000 chunks) I want to average and store that 10 values average and then move to next 10 in the value in documents in MongoDb, { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") } { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") } { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-03-15T09:00:00Z") } { "_id" : 4, "item" : "xyz", "price" : 5, "quantity" : 20, "date" : ISODate("2014-04-04T11:21:39.736Z") } { "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") } In following documents I want to take average of price every 2 documents like 10+20/2 = 15 and 5+5/2= 5. So I like to know how to make this in Python.
type: Question
has comment: http://stackoverflow.com/comment/84950062
tagged with: mongodb
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/48972623
has title: How to average with MongoDB taking 10 chunks and so on in Python?
tagged with: aggregation-framework
tagged with: python
tagged with: aggregation
has answer: http://stackoverflow.com/a/48972623

http://stackoverflow.com/comment/84962345
score: 0
has text: File "KOAPvECalculator.py", line 1 from __future__ import print_statement SyntaxError: future feature print_statement is not defined
type: Comment
comment on: http://stackoverflow.com/a/48978641
type: AnswerComment

http://stackoverflow.com/a/48980239
has comment: http://stackoverflow.com/comment/84966816
has comment: http://stackoverflow.com/comment/84966724
type: Answer
has comment: http://stackoverflow.com/comment/84966769
accepted answer of: http://stackoverflow.com/q/48980187
has comment: http://stackoverflow.com/comment/84967004
answers question: http://stackoverflow.com/q/48980187
score: 0
has body: Your move to the next node statement: p.edge_next = p.edge_next.edge_next Should be: p = p.edge_next Test Code: class edge_model: def __init__(self, dx): self.ymax = None self.xmin = None self.dx = dx self.edge_next = None if __name__ == '__main__': e1 = edge_model(1) e2 = edge_model(2) e3 = edge_model(3) e_in = edge_model(2.5) e1.edge_next = e2 e2.edge_next = e3 p = e1 while p.edge_next: if e_in.dx &lt; p.edge_next.dx: e_in.edge_next = p.edge_next p.edge_next = e_in break else: p = p.edge_next print("===") print(e1.dx) print(e1.edge_next.dx) print(e1.edge_next.edge_next.dx) Results: === 1 2 2.5
type: AcceptedAnswer

http://stackoverflow.com/q/49022851
upvote count: 1
has title: how to map two rows of different dataframe based on a condition in pandas
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/49023056
has body: I have two dataframes, df1, Names one two three Sri is a good player Ravi is a mentor Kumar is a cricketer player df2, values sri NaN sri, is kumar,cricketer player I am trying to get the row in df1 which contains the all the items in df2 My expected output is, values Names sri Sri is a good player NaN sri, is Sri is a good player kumar,cricketer player Kumar is a cricketer player i tried, df1["Names"].str.contains("|".join(df2["values"].values.tolist())) I also tried, but I cannot achieve my expected output as it has (","). Please help
answer count: 2
has answer: http://stackoverflow.com/a/49023293
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: data-analysis
tagged with: python
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/85140480
type: Comment
type: QuestionComment
has text: `is` tests object identity. It doesn't check if a variable has a special type. BTW, `x` will always be a string.
score: 0
comment on: http://stackoverflow.com/q/49067712

http://stackoverflow.com/a/49008226
has comment: http://stackoverflow.com/comment/85024907
type: Answer
answers question: http://stackoverflow.com/q/49007454
score: 0
has body: First thing is, why would you use imread from matplotlib when you're already importing skimage? Use skimage.io.imread Second, I don't quite get what you're trying to do with the whole numpy.append thing. That's both flattening your image and appending the target value to the end of it, but there are better ways of doing it. Here's a simple code to do exactly what you want: import numpy as np import pandas as pd from skimage.transform import resize from skimage.io import imread import os def load_pre_images(fname_csv, path, num_px): """ Parameters ---------- path : str Path to images folder fname_csv : str Name of the CSV file that contains [Images_names, description, target] num_px : int Images new size (num_px x num_px) Returns ------- np.array(img_dataset) : numpy array Complete data (m x nx) m is the number of pictures nx is the dimensionality (num_px x num_px x 3) for rbg images count : int Count of the undetected images """ mydata = pd.read_csv(os.path.join(path, fname_csv)).values count = 0 x = [] y = [] for row in mydata: try: img_path = os.path.join(path, row[0] + '.jpg') # Images names lies in the first column image = imread(img_path) my_image = resize(image, (num_px, num_px)) my_image = my_image / 255 # Normalize images my_image = my_image.reshape((-1, 1)) # Flatten image x.append(my_image) y.append(row[2]) except FileNotFoundError: count += 1 continue return np.asarray(x), np.asarray(y), count path_images = 'your path to the images folder/' imgs, labels, c = load_pre_images('name_of_your_csv_file.csv', path_images, 100) See that I have: Removed the unnecessary matplotlib dependency Separated images and labels into different arrays Changed the except Exception to except FileNotFoundError, cause that's probably what you want. Don't go catching all exceptions in a single clause. That's bad Used numpy.reshape to flatten your image, instead of the numpy.append which is not made for that

http://stackoverflow.com/a/48969505
answers question: http://stackoverflow.com/q/48969460
has body: One way to do this is class Player(object): actions = { 'QUIT': 'quit' } And then def roomactivity(self): while True: [...] elif choice in player.actions: getattr(player, player.actions[choice])()
score: 0
type: Answer

http://stackoverflow.com/q/49006013
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85016535
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: machine-learning
downvote count: 1
has body: I have a dataset with m observations and p categorical variables (nominal), each variable X1,X2...Xp has several different classes (possible values). Ultimately I am looking for a way to find anomalies i.e to identify rows for which the combination of values seems incorrect with respect to the data I saw so far. So far I was thinking about building a model to predict the value for each column and then build some metric to evaluate how different the actual row is from the predicted row. I would greatly appreciate any help!
has comment: http://stackoverflow.com/comment/85016922
type: Question
has title: find anomalies in records of categorical data
answer count: 1
has comment: http://stackoverflow.com/comment/85016730
tagged with: data-science
has answer: http://stackoverflow.com/a/49021501
tagged with: statistics

http://stackoverflow.com/q/49088430
has title: Choice vs. Shuffle, Python
linked to: http://stackoverflow.com/q/40143157
tagged with: random
answer count: 2
tagged with: time-complexity
favorite count: 0
has comment: http://stackoverflow.com/comment/85182437
has comment: http://stackoverflow.com/comment/85182519
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49088611
upvote count: 2
has comment: http://stackoverflow.com/comment/85182451
has body: I was wondering which of shuffle() and choice() was more efficient. For example, I have a N element list long_list and need a random item from the list, is it quicker to do: shuffle(long_list) return long_list[0] or return choice(long_list)
tagged with: python
has comment: http://stackoverflow.com/comment/85182599
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/85182531
score: 1
possible better answer: http://stackoverflow.com/a/49088622
accepted answer: http://stackoverflow.com/a/49088611
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49088622

http://stackoverflow.com/comment/84957888
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48974903
has text: You may want to [check this](https://stackoverflow.com/questions/2790828/python-cant-pickle-module-objects-error) once.
type: Comment

http://stackoverflow.com/comment/85244390
score: 0
type: Comment
type: QuestionComment
has text: @WarrenWeckesser yes, that also works, thanks. But flatten should accomplish same ?
comment on: http://stackoverflow.com/q/49119392

http://stackoverflow.com/comment/88849479
has text: @PeterWood As I mentioned I was just playing with it then I encountered that odd behavior
comment on: http://stackoverflow.com/q/49006750
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84987138
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48991009
type: AnswerComment
has text: The picture is not that "beautiful". I wonder if I can make the discrete variables have a density of 1 so that their area will be larger and the "kde curve" will be as high as the bars.

http://stackoverflow.com/comment/84943410
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48967673
has text: i added please check it
type: AnswerComment

http://stackoverflow.com/q/49015129
type: Question
has comment: http://stackoverflow.com/comment/85035217
answer count: 1
has body: I am very new to python. I tried to make a plot by loading a .txt file that contains two arrays of numbers. The plot looks fine, but there is an additional line which I am unable to get rid of. I have attached my code here. Please help! Thanks. import numpy as np import matplotlib.pyplot as plt from numpy import genfromtxt data= genfromtxt ('PVC_Cs137.txt') plt.plot(data) plt.xlim(0,2500) plt.ylim(0,30000) plt.xlabel("Channel number") plt.ylabel("Counts") plt.show() Link to the data
downvote count: 0
favorite count: 0
has title: error in python plot: unwanted line in the plot
has comment: http://stackoverflow.com/comment/85035111
tagged with: python
has answer: http://stackoverflow.com/a/49015266
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/49015266
upvote count: 1
tagged with: plot

http://stackoverflow.com/q/48968688
tagged with: tensorflow
has title: TensorBoard UncaughtTypeError: Cannot read property 'length' of undefined
type: Question
has answer: http://stackoverflow.com/a/49328962
has body: I have trained a gensim Doc2Vec model on five million documents, and those documents are tagged with a unique ID (IDNO). Now I am loading the model, and accessing a specific subset of the vectors based on IDNO. First, I load a pandas df from a database and it looks like this: IDNO author document 123XYZ john the cat sat 234FGH jane the dog ran 345RTY jane the hippo ate Then I load the model: model = Doc2Vec.load('documents_doc2vec_vectorsize100_mincount2_epochs50.model') Then I access the three vectors that are in my df: row_id_list = list(df.row_id) vectors_tuple = itemgetter(*row_id_list)(model.docvecs) embedding = np.asarray(vectors_tuple) Then I create all the necessary TensorBoard files: tf.reset_default_graph() sess = tf.InteractiveSession() X = tf.Variable([0.0], name='embedding') place = tf.placeholder(tf.float32, shape=embedding.shape) set_x = tf.assign(X, place, validate_shape=False) sess.run(tf.global_variables_initializer()) sess.run(set_x, feed_dict={place: embedding}) summary_writer = tf.summary.FileWriter('log', sess.graph) config = projector.ProjectorConfig() embedding_conf = config.embeddings.add() embedding_conf.tensor_name = 'embedding:0' embedding_conf.metadata_path = os.path.join('metadata','metadata.tsv') projector.visualize_embeddings(summary_writer, config) saver = tf.train.Saver([X]) saver.save(sess, os.path.join('log', 'model1.ckpt'), 1) When I run tensorboard --logdir=log, TensorBoard loads, but it says points and dimensions are loading. When I enter Chrome Developer Tools, I get this error: Uncaught TypeError: Cannot read property 'length' of undefined at (index):147401 at Array.filter (&lt;anonymous&gt;) at (index):147399 at XMLHttpRequest.xhr.onload ((index):143698) I had TensorBoard working before, but that was when I set embedding to model.docvecs.vectors_docs rather than accessing specific vectors and pushing them into a numpy array. Why is this happening?
answer count: 1
score: 0
tagged with: tensorboard
tagged with: python
tagged with: gensim
type: UnansweredQuestion

http://stackoverflow.com/comment/85206692
comment on: http://stackoverflow.com/q/49100697
has text: Why can't you just regex for the terms: 'title=', 'author=', etc and then strip away the {} or regex directly for title={xxxx}. This should work. Can you post your regex attempt?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85054400
comment on: http://stackoverflow.com/a/48984966
type: Comment
type: AnswerComment
has text: This should be nginx config related. You have to create one `proxy_pass` rule for each service that you want to communicate with. Docker allows you to communicate with ache container already connected to the same network using just the service's name. This [link](https://www.quora.com/Is-it-possible-to-setup-NGINX-to-proxy-different-paths-on-the-the-same-domain-to-different-back-end-apps-or-services) may help you to achieve that.
score: 0

http://stackoverflow.com/q/49078921
has comment: http://stackoverflow.com/comment/85163864
tagged with: string
favorite count: 0
tagged with: hex
has comment: http://stackoverflow.com/comment/85164683
has comment: http://stackoverflow.com/comment/85164114
type: UnansweredQuestion
has body: I am making a hexadecimal convertor class that requires a string operator over loader. When I run the tester program against my actual program, the str() crashes the program. I tried printing out the actual string to see where I went wrong, but all that was printed was blank lines. The tester program gives me a 90.0/100.0 because the string over loader isn't working. Python code for hex convertor. Updated Code: class Hexadecimal: def __init__(self, decimal = "1128"): if type(decimal) is int: if decimal &gt;= 0: self.__decimal = decimal else: raise ValueError ("Must be greater than zero.") elif type(decimal) is list: raise ValueError ("Cannot enter lists.") elif type(decimal) is float: decimal = int(decimal) if decimal &gt;= 0: self.__decimal = decimal else: raise ValueError ("Cannot have negative floats.") elif type(decimal) is str: if decimal not in ["A", "B", "C", "D", "E", "F"]: decimal = float(decimal) else: raise ValueError ("Cannot convert string to float.") else: self.__decimal = int(decimal) #Overloaded string function def __str__(self): h_string = "" number = self.__decimal while number &gt; 0: digit = number % 16 number //= 16 if digit &lt; 10 and digit &gt; 0: h_string += str(digit) elif digit == 10: h_string += "A" elif digit == 11: h_string += "B" elif digit == 12: h_string += "C" elif digit == 13: h_string += "D" elif digit == 14: h_string += "E" elif digit == 15: h_string += "F" print(h_string[::-1]) return h_string[::-1] Result: Crashed when testing str(). A A F F A A 2 32 2 32 A A 9 19 9 19 3 3 1 1 4 4 2 2 4 4 1 1 90.0
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85164067
type: Question
tagged with: operator-overloading
has comment: http://stackoverflow.com/comment/85171351
has title: Hexadecimal Convertor for Python String Overloader
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85230807
score: 0
type: Comment
type: QuestionComment
has text: Sure this can be done, but SO isn't really a place to get general help or guidance. You'll have better luck if you start coding and come here for help with more specific programming problems.
comment on: http://stackoverflow.com/q/49112170

http://stackoverflow.com/q/49088752
downvote count: 0
tagged with: neural-network
has title: neural network performs badly at simple linear interpolation task
tagged with: optimization
has body: FYI: I uploaded all you need to test it yourself (data + a simplified script). This is my problem: I tried to train a very simple model that uses four input values x(0), x(1), x(2), x(3) to predict value x(4), i.e. y = x(4). However, I modified the data such that y = x(4) is a perfect linear extrapolation: y = x(3) + (x(3)-x(2)) The model I used is a single dense layer with four neurons. The weights "0 0 -1 2" would be a perfect solution (loss of "0"). However, I can't make it reach these values. Can you help or tell me, why? files are here: https://ufile.io/5d2t4 main script (with artificial data): import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Flatten, Dense from keras.optimizers import Adadelta, Adam import keras.backend as K def root_mean_squared_error(y_true, y_pred): return K.sqrt( K.mean( K.square( y_pred - y_true ) ) ) X_train = np.random.random(240000*4) X_train = np.reshape( X_train, ( 240000, 1, 4 ) ) # predict the gradient of the y_train = X_train[:,0,3] - X_train[:,0,2] inputShape = ( X_train.shape[1], X_train.shape[2] ) # create model model = Sequential() model.add( Flatten( input_shape=inputShape ) ) model.add( Dense( 1 ) ) model.compile( loss=root_mean_squared_error, optimizer=Adam( decay = 0.1 ) ) # train model batchSize = 8 model.fit( X_train, y_train, nb_epoch=10, batch_size=batchSize, shuffle=True ) y_train_predicted = model.predict( X_train) y_train_predicted = np.asarray(y_train_predicted).ravel() y_train_predicted_rmse = np.sqrt( np.mean( np.square( y_train_predicted - y_train ) ) ) print( "y_train RMSE = " + str( y_train_predicted_rmse ) )
has comment: http://stackoverflow.com/comment/85183259
tagged with: python
favorite count: 0
tagged with: interpolation
has comment: http://stackoverflow.com/comment/85183643
upvote count: 2
has answer: http://stackoverflow.com/a/49104121
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85204225
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85204315
type: Question
has comment: http://stackoverflow.com/comment/85213339
accepted answer: http://stackoverflow.com/a/49104121
answer count: 1

http://stackoverflow.com/comment/84950293
comment on: http://stackoverflow.com/a/48972020
score: 0
type: AnswerComment
type: Comment
has text: I am not talking about the action attribute. In fact I didn't set the action attribute at all. I am talking about the link for your deleteview. I will add the codes I used to create the DeleteView for my demo project. Maybe that will help.

packet
tags question: http://stackoverflow.com/q/49071959
tag name: packet
type: Tag

http://stackoverflow.com/q/49100921
has body: couple issues with my code I need help working out. how do I get the header to only print once above the results, and not at all if nothing meetings the criteria? the else component of my code is no longer working, it used to just print if none of the other scenarios were true but I updated it and now it keeps printing every time. Can anyone spot the issue? Code: import Hotels htl_1= Hotels.Hotels(111,100,1,1) htl_2= Hotels.Hotels(112,200,2,1) htl_3= Hotels.Hotels(113,250,2,2) htl_4= Hotels.Hotels(114,300,3,2) htl_5= Hotels.Hotels(115,350,3,3) feeInput=input('Enter maximum per night fee: ') roomInput=input('Enter minimum number of bedrooms: ') bathInput=input('Enter minimum number of baths: ') header='{:10} {:10} {:10} {:10}'.format('Room#','Cost','Rooms','Bathrooms') print(header) if int(feeInput)&gt;= htl_1.fee and int(roomInput)&lt;= htl_1.rooms and int(bathInput)&lt;= htl_1.bath: print(htl_1.gethtl()) if int(feeInput)&gt;= htl_2.fee and int(roomInput)&lt;= htl_2.rooms and int(bathInput)&lt;= htl_2.bath: print(htl_2.gethtl()) if int(feeInput)&gt;= htl_3.fee and int(roomInput)&lt;= htl_3.rooms and int(bathInput)&lt;= htl_3.bath: print(htl_3.gethtl()) if int(feeInput)&gt;= htl_4.fee and int(roomInput)&lt;= htl_4.rooms and int(bathInput)&lt;= htl_4.bath: print(htl_4.gethtl()) if int(feeInput)&gt;= htl_5.fee and int(roomInput)&lt;= htl_5.rooms and int(bathInput)&lt;= htl_5.bath: print(htl_5.gethtl()) else: print('Sorry, no rooms available that meet that criteria')
tagged with: python
possible better answer: http://stackoverflow.com/a/49100967
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85207106
has comment: http://stackoverflow.com/comment/85207095
has title: Can anyone see the flaw in my code?
has answer: http://stackoverflow.com/a/49100967
score: 1
has comment: http://stackoverflow.com/comment/85207116
upvote count: 1
has answer: http://stackoverflow.com/a/49100983
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49100983
downvote count: 0
has comment: http://stackoverflow.com/comment/85207373
favorite count: 0
has comment: http://stackoverflow.com/comment/85207331
has comment: http://stackoverflow.com/comment/85207081

http://stackoverflow.com/a/49059794
has comment: http://stackoverflow.com/comment/85129220
has comment: http://stackoverflow.com/comment/85126866
has body: Here is one way using your suggestion of wrapping in a try / except clause. from datetime import datetime def dater(x): try: return datetime(year=x['year'], month=x['month'], day=x['day']) except ValueError: return None df['date'] = df.apply(dater, axis=1) # year month day date # 0 1890 2 29 NaT # 1 1891 2 29 NaT # 2 1892 2 29 1892-02-29 # 3 1893 2 29 NaT # 4 1894 2 29 NaT # 5 1895 2 29 NaT # 6 1896 2 29 1896-02-29 # 7 1897 2 29 NaT # 8 1898 2 29 NaT df = df.dropna(subset=['date']) # year month day date # 2 1892 2 29 1892-02-29 # 6 1896 2 29 1896-02-29
has comment: http://stackoverflow.com/comment/85126074
downvote count: 0
has comment: http://stackoverflow.com/comment/85127096
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85242132
answers question: http://stackoverflow.com/q/49059717
has comment: http://stackoverflow.com/comment/85127050
has comment: http://stackoverflow.com/comment/85129164
upvote count: 3
has comment: http://stackoverflow.com/comment/85126165
has comment: http://stackoverflow.com/comment/85130254

http://stackoverflow.com/comment/85149131
type: Comment
comment on: http://stackoverflow.com/a/49071402
type: AnswerComment
score: 0
has text: You are setting the index to `IDs`. Do not run `set_index()` after import for this solution.

http://stackoverflow.com/a/48981224
answers question: http://stackoverflow.com/q/48981183
upvote count: 2
has body: The outer item is a list, and the inner items are dictionaries. You just need to go one level deeper. for audit_item in audit_items_list: for k, v in audit_item.items(): # iterate over key value pairs. # Or get the entire list of each by doing item.keys() or item.values()
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/85043527
type: QuestionComment
comment on: http://stackoverflow.com/q/49019073
has text: Are you sure to be using the **exact** same code from the example? What versions of libraries, system etc are you using?
score: 1
type: Comment

http://stackoverflow.com/q/49094361
has body: I am trying to build a simple program using tkinter and python 3.6. I am stuck when I try to plot a donut chart in my tkinter window using the matplotlib Figure and canvas. I know how to make a donut chart using the matplotlib pyplot, using a very simple code I found on: https://python-graph-gallery.com/160-basic-donut-plot/ # library import matplotlib.pyplot as plt # create data size_of_groups=[12,11,3,30] # Create a pieplot plt.pie(size_of_groups) #plt.show() # add a circle at the center my_circle=plt.Circle( (0,0), 0.7, color='white') p=plt.gcf() p.gca().add_artist(my_circle) plt.show() I have read that the plots in tkinter should be made using the matplotlib.figure: Placing plot on Tkinter main window in Python Can someone help me how to adjust the code above to be able to plot it inside a Figure that I can place in tkinter canvas? So far I have only been able to make the pie plot fig = plt.figure.Figure(figsize=(5,5)) a = fig.add_subplot(111) a.pie([20,30,50]) #an example data a.legend(["20","30","50") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk window= tk.Tk() canvas = FigureCanvasTkAgg(fig, master=window) canvas.get_tk_widget().pack() canvas.draw() window.mainloop() But I am unable to add a circle in the center that would hide that part of the pie. Any ideas on how to do that? Thanks
favorite count: 0
tagged with: tkinter
tagged with: python
linked to: http://stackoverflow.com/q/31440167
score: 2
type: AnsweredQuestion
tagged with: donut-chart
downvote count: 0
tagged with: matplotlib
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49096376
has title: How to make a donut chart in tkinter using matplotlib Figure
has answer: http://stackoverflow.com/a/49096376
answer count: 1

http://stackoverflow.com/q/49041968
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
answer count: 0
score: 1
upvote count: 1
type: Question
has body: For context, my use-case is the determine a "precision" score of a regex as it relates to an input string, for the purposes of ranking. While I realize that regex precision can be a nebulous concept, I am defining it for my use-case as the number of matching literals. Here is an example of inputs &amp; expected results from this mythical function: &gt;&gt;&gt; get_literal_count(regex=r'foo(bizz|b[a-z]+)*', string='foobarbar') &gt;&gt;&gt; 5 The way that example breaks down to get a result of 5: foo [3 literals] (bizz| [Not matching = 0 literals] b[a-z]+)* [1 literal (the "b") matched 2 times = 2 literals] My investigation and playing around with re &amp; sre_parse modules have lead me to the conclusion that the only way to achieve what I am after is to essentially re-write a home-brew re.match function using sre_parse that tracks the number of matching literals as it goes. Going down that path, I would need to re-implement all (or at least a large sub-set) of the sre symbols used in matching, just to end up with what is essentially a really slow re.match function (the standard lib re.match is written in C, but my implementation would be in Python), I pose my question here. Does anyone have any insight into this problem? Is there a better way? EDIT: To clarify, the regex being used in my example is arbitrary, the method must operate on any regex.
tagged with: python-2.7
downvote count: 0
has title: How do I get a count of matching literals when matching regex's in Python?

http://stackoverflow.com/comment/85028083
type: Comment
type: QuestionComment
has text: Please post a few rows of all dataframes. Also, why not `merge` subset cols by ID?
score: 0
comment on: http://stackoverflow.com/q/49011261

http://stackoverflow.com/q/48970272
score: -1
has comment: http://stackoverflow.com/comment/84946040
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84946380
has comment: http://stackoverflow.com/comment/84946198
tagged with: python-2.7
has title: Calling python function across network
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48970525
downvote count: 1
has body: I am doing some image processing (stereo vision) using OpenCV 3.4.0 on Python 2.7. The targeted end device is a single board computer such as a Raspberry Pi. The problem I am currently facing is the SBC takes too long to process the images and really lowers the fps (maximum I get now is 8 fps). I need a real time system with atleast 20 fps. So, I was thinking if it is possible to run another system with higher capability in the network and pass the image matrices to it from the SBC. The return value is another matrix. Is there a way to call a function over a network?. Any help is appreciated.
tagged with: opencv
has comment: http://stackoverflow.com/comment/84946229

http://stackoverflow.com/q/49075557
type: UnansweredQuestion
has body: I have a All Fields Data frame with all the columns(headers) in it. I have to read a excel workbook which have 25 sheets but i only have to read 10 sheets out of it. So i am passing the list of the files in a nested for loop to read the sheets and name of the sheets are like "Labour M1","Travel M1","Equip M1"..... "Labour M2","Travel M2"etc. I have one main loop which defines the variable for the number at the end of the sheet name. So i am reading all the sheets with 1 at the last and saving it in a list and then appending to Dataframe1, then adding a column with name "Milestone" which will have the value of "i" in main for loop and then it loop again and read the the sheets which have 2 number at the last and then same process. So finally i am appending "Dataframe1" to "Allfields" dataframe and then i am saving that "Allfields" dataframe to excel file after finishing the loop. So when i open the excel file it appended the data correctly but problem is the column which i am adding it takes always takes the last value of "i" in a for loop but it should take the value of number which i am reading. Here is my code for i in range(1, 3): list_sheets = ['Labour M' + str(i), 'Travel M' + str(i), 'Equip M' + str(i), 'Consult-SubC M' + str(i), 'Other M' + str(i)] Empty_List = [] All_Milestone = pd.DataFrame() for p in list_sheets: print(p) book_open = open_workbook(getpath()) sheet_open = book_open.sheet_by_name(p) print("Successfully found the sheet") for rowidx in range(sheet_open.nrows): row = sheet_open.row(rowidx) for colidx, cell in enumerate(row): if cell.value == "Consortium Member": print("Sheet Name:", sheet_open.name) print("Row Number:", rowidx) value = int(rowidx) else: print("Sheet ", sheet_open, "not found.") reading_book = pd.read_excel(getpath(), sheet_name=p, skiprows=value) sheet = reading_book.dropna(axis=0, how='any', subset=['Consortium Member']) sheet.drop([col for col in sheet.columns if "Unnamed" in col], axis=1, inplace=True) print("Successfully re…
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
has title: Python: Read multiple excel sheets, add column and append it to one dataframe
downvote count: 0
tagged with: pandas
favorite count: 0

http://stackoverflow.com/q/49033540
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49034260
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49033665
score: 2
tagged with: xpath
type: AnsweredQuestion
upvote count: 2
tagged with: siblings
accepted answer: http://stackoverflow.com/a/49034260
has title: scrapy list return: how to process / extract each element of a list?
tagged with: scrapy
possible better answer: http://stackoverflow.com/a/49033665
has body: I wanted to ask how it is possible to deal with lists of extracted data within one variable. As the (xpath) selector only extracts the first .extract_first() or all of the content .extract (), I wondered, how I can iterate and extract only one element...like .extract()[i] and i=i+1... How does that have to be put? It seems so obvious but at this point I don't understand how to make use of itemloaders, pipelines or whatever scrapy documentations provides to get this problem solved. item ['author'] = sel.xpath('.//a[contains(@data-hook, "review-author")]/text()').extract_first() item ['author'] = sel.xpath('.//a[contains(@data-hook, "review-author")]/text()').extract()[0] item ['author'] = sel.xpath('.//a[contains(@data-hook, "review-author")]/text()').extract()[i] ... i=i+1??? Also if you could just point me to the correct direction, I would be so grateful!

http://stackoverflow.com/comment/85202939
comment on: http://stackoverflow.com/a/49098744
has text: @BorealCoder Do not getting sacred by for loop , sometime they are faster than vectorize function when your df size is increase
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85233456
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49114152
has text: So what have you tried so far and why doesn't it work?
score: 0

http://stackoverflow.com/a/48992043
downvote count: 0
has body: First, your syntax is not correct for inner functions: you must use def keyword as below: def exemple(): def dostuff1(): print:('Stuff 1') def dostuff2(): print:('Stuff 2') def dostuff3(): print:('Stuff 3') Secondly, this question has been already answered here: How to access a function inside a function? in simple words, you can't call an inner function directly from outside, but you can do something like suggested by the answer from @gautamaggarwal.
answers question: http://stackoverflow.com/q/48991909
type: Answer
has comment: http://stackoverflow.com/comment/84992966
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84989247

http://stackoverflow.com/comment/85053655
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49024226
has text: I will keep that in mind evert.
score: 0

http://stackoverflow.com/comment/98587802
comment on: http://stackoverflow.com/a/48996898
score: 1
type: AnswerComment
type: Comment
has text: Set `-s` how? It isn't clear in this context. Thanks!

http://stackoverflow.com/comment/85168223
type: QuestionComment
type: Comment
has text: Yes. I just corrected it. Thanks.
comment on: http://stackoverflow.com/q/49081369
score: 0

http://stackoverflow.com/a/50030705
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87296149
answers question: http://stackoverflow.com/q/49074101
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/87112949
has body: So you can do this used apply and nested functions import pandas as pd ID = [2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2002222,2002222,2002222,2002222,2002222,2002222,2002222,2002222,] Date = ["10/30/2017","10/29/2017","10/28/2017","10/27/2017","10/26/2017","10/25/2017","10/24/2017","10/23/2017","10/22/2017","10/21/2017","10/21/2017","10/20/2017","10/19/2017","10/18/2017","10/17/2017","10/16/2017","10/15/2017","10/14/2017",] current = [1 ,0 ,0 ,40,39,0 ,0 ,60,0 ,0 ,0 ,0 ,16,0 ,0 ,20,19,18,] df = pd.DataFrame({"ID": ID, "Date": Date, "current": current}) Then create the function to update the frame Python 3.X def update_frame(df): last_expected = None def apply_logic(row): nonlocal last_expected last_row_id = row.name - 1 if row.name == 0: last_expected = row["current"] return last_expected last_row = df.iloclast_row_id.iloc[0].to_dict() last_expected = max(last_expected-1,row['current']) if last_row['ID'] == row['ID'] else row['current'] return last_expected return apply_logic Python 2.X def update_frame(df): sd = {"last_expected": None} def apply_logic(row): last_row_id = row.name - 1 if row.name == 0: sd['last_expected'] = row["current"] return sd['last_expected'] last_row = df.iloclast_row_id.iloc[0].to_dict() sd['last_expected'] = max(sd['last_expected'] - 1,row['current']) if last_row['ID'] == row['ID'] else row['current'] return sd['last_expected'] return apply_logic And run the function like below df['expected'] = df.apply(update_frame(df), axis=1) The output is as expected
has comment: http://stackoverflow.com/comment/87112786
has comment: http://stackoverflow.com/comment/87113215
has comment: http://stackoverflow.com/comment/87300204
upvote count: 3
has comment: http://stackoverflow.com/comment/87115619
has comment: http://stackoverflow.com/comment/87116115
accepted answer of: http://stackoverflow.com/q/49074101

http://stackoverflow.com/q/49114087
has comment: http://stackoverflow.com/comment/85239693
has body: I have a simple XML element created with xml.etree.ElementTree in Python 3. import xml.etree.ElementTree as ElementTree person = ElementTree.Element("Person", Name="John", Age=18) I can use Element.get() to access individual attributes from my element without any issues. name = person.get("Name") age = person.get("Age") print(name + " is " + str(age) + " years old.") # output: "John is 18 years old" However, if I try to convert my element to a string with .tostring(), I get an error "TypeError: argument of type 'int' is not iterable". print(ElementTree.tostring(person)) # TypeError Why can't I use .tostring() on an xml.etree.ElementTree.Element with an integer attribute? Full code: import xml.etree.ElementTree as ElementTree person = ElementTree.Element("Person", Name="John", Age=18) print(ElementTree.tostring(person)) # TypeError Full traceback: Traceback (most recent call last): File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1079, in _escape_attrib if "&amp;" in text: TypeError: argument of type 'int' is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/svascellar/.PyCharmCE2017.3/config/scratches/scratch_13.py", line 3, in &lt;module&gt; print(ElementTree.tostring(person)) File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1135, in tostring short_empty_elements=short_empty_elements) File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 776, in write short_empty_elements=short_empty_elements) File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 933, in _serialize_xml v = _escape_attrib(v) File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1102, in _escape_attrib _raise_serialization_error(text) File "C:\Users\svascellar\AppDa…
tagged with: python
has title: Converting xml.etree.ElementTree to string raises "TypeError: argument of type 'int' is not iterable"
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85238819
accepted answer: http://stackoverflow.com/a/49114278
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/49114278
favorite count: 0
upvote count: 3
tagged with: typeerror
tagged with: elementtree
linked to: http://stackoverflow.com/q/19534288

http://stackoverflow.com/q/49041551
favorite count: 0
score: -1
type: Question
has comment: http://stackoverflow.com/comment/85088792
answer count: 2
has comment: http://stackoverflow.com/comment/85088624
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/85088458
has answer: http://stackoverflow.com/a/49041892
has comment: http://stackoverflow.com/comment/85088525
upvote count: 0
has body: Is there a way to do this? ex: I have a dict sounds = { 'sound1.mp3': 0, 'sound2.mp3': 0, 'sound3.mp3': 0 } when a keys value (sound1 in this ex) gets updated, the command prompt will go from sound1.mp3: 0 sound2.mp3: 0 sound3.mp3: 0 to sound1.mp3: 1 sound2.mp3: 0 sound3.mp3: 0
type: UnansweredQuestion
has title: live updating command prompt text
has answer: http://stackoverflow.com/a/49041774
linked to: http://stackoverflow.com/q/2084508
linked to: http://stackoverflow.com/q/4810537
has comment: http://stackoverflow.com/comment/85088663

http://stackoverflow.com/q/49077539
upvote count: 5
answer count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6523791
tagged with: python
linked to: http://stackoverflow.com/q/16981921
has answer: http://stackoverflow.com/a/49077636
type: Question
has answer: http://stackoverflow.com/a/49077890
has answer: http://stackoverflow.com/a/49077699
tagged with: python-import
score: 5
downvote count: 0
has body: I'm still trying to get a hang of python 3 and I'm running into an issue where I can either run a .py file as a script or import it as a module, but not both. Directory Structure test/ __init__.py test.py subwayclock/ __init__.py subwayclock.py build/ gen/ __init__.py gtfs_realtime_pb2.py nyct_subway_pb2.py __init__.py in this scenario test.py looks like this and works (rawFEED() is a function in subwayclock.subwayclock): from subwayclock.subwayclock import * print(rawFEED()) However, I cannot run the script directly i.e. python subwayclock/subwayclock.py because it gives the following error: Traceback (most recent call last): File "subwayclock.py", line 32, in &lt;module&gt; from .build.gen.gtfs_realtime_pb2 import FeedMessage SystemError: Parent module '' not loaded, cannot perform relative import HOWEVER, if I modify the import statement in subwayclock/subwayclock.py to state (i.e. with the leading '.' removed): from subwayclock.subwayclock import FeedMessage I can run the subwayclock.py script directly through the command line, calling the main function perfectly. BUT, when I run the original test.py file, the import statement no longer works, and I get the following error: Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; from subwayclock.subwayclock import * File "/var/www/test/subwayclock/subwayclock.py", line 32, in &lt;module&gt; from build.gen.gtfs_realtime_pb2 import FeedMessage ImportError: No module named 'build' Can I make this script independently runnable and importable?
favorite count: 0
has title: How can I make a python file runnable as a script and importable as a package?
duplicate of: http://stackoverflow.com/q/6523791
tagged with: python-3.x

http://stackoverflow.com/q/49095192
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49095802
type: AnsweredQuestion
tagged with: list
has title: Python. Check if index exists in a list of possible dictionaries
possible better answer: http://stackoverflow.com/a/49095230
has comment: http://stackoverflow.com/comment/85195408
has answer: http://stackoverflow.com/a/49095230
has body: I have this: list_name = [0, 1, 2, 3] list_name[0] = {} list_name[0]['test'] = 'any value' I want to know if a key of the list exists or not. Usually I use: if 3 not in list_name: print("this doesn't exist") else: print("exists") And testing this for example for number 3 is working. It says "exists". If I check for number 999 is working, it says "this doesn't exist". The problem is that it is not working for 0. As you can see, 0 value in the list has a dictionary. And I need to check if 0 exists or not in the list (doesn't matter if it has a dictionary or not). How to achieve this? Using python3, thank you.
type: Question
has comment: http://stackoverflow.com/comment/85195558
upvote count: 5
has answer: http://stackoverflow.com/a/49095802
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85195475
score: 5
has comment: http://stackoverflow.com/comment/85195496

http://stackoverflow.com/a/78117638
upvote count: 0
score: -1
has body: In the past few years, nice new tools have been added to SciPy to address this kind of problem. You can easily generate samples from custom continuous or discrete univariate distributions by just providing some information about the distribution, such as the density / pdf. Here is an example: import numpy as np from scipy.stats.sampling import NumericalInversePolynomial from matplotlib import pyplot as plt from scipy.integrate import quad class MyDist: def __init__(self, a): self.a = a def support(self): # distribution restricted to 0, 5, can be changed as needed return (0, 5) def pdf(self, x): # this is not a proper pdf, the normalizing # constant is missing (does not integrate to one) return x * (x + np.sin(5*x) + 2) * np.exp(-x**self.a) dist = MyDist(0.5) gen = NumericalInversePolynomial(dist) # compute the missing normalizing constant to plot the pdf const_pdf = quad(dist.pdf, *dist.support())[0] r = gen.rvs(size=50000) x = np.linspace(r.min(), r.max(), 500) # show histogram together with the pdf plt.plot(x, dist.pdf(x) / const_pdf) plt.hist(r, density=True, bins=100) plt.show() Overview of the different methods: https://docs.scipy.org/doc/scipy/reference/stats.sampling.html Tutorial: https://docs.scipy.org/doc/scipy/tutorial/stats/sampling.html In your particular case, if you want have the CDF, you can use the following method to invert it: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sampling.NumericalInverseHermite.html#scipy.stats.sampling.NumericalInverseHermite If you just have the pdf, you can use https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sampling.NumericalInversePolynomial.html#scipy.stats.sampling.NumericalInversePolynomial This is much faster and more robust than a root-finding method
answers question: http://stackoverflow.com/q/49109481
downvote count: 1
type: Answer

http://stackoverflow.com/a/48996334
answers question: http://stackoverflow.com/q/48984214
has comment: http://stackoverflow.com/comment/85013923
type: Answer
score: 2
downvote count: 0
has body: The -c and -m switches, ultimately(*) run the code supplied with the exec statement or the compile() function, both of which take Latin-1 source code: The first expression should evaluate to either a Unicode string, a Latin-1 encoded string, an open file object, a code object, or a tuple. This is not documented, it's an implementation detail, that may or may not be considered a bug. I don't think it is something that is worth fixing however, and Latin-1 is a superset of ASCII so little is lost. How code from -c and -m is handled has been cleaned up in Python 3 and is much more consistent there; code passed in with -c is decoded using the current locale, and modules loaded with the -m switch default to UTF-8, as usual. (*) If you want to know the exact implementations used, start at the Py_Main() function in Modules/main.c, which handles both -c and -m as: if (command) { sts = PyRun_SimpleStringFlags(command, &amp;cf) != 0; free(command); } else if (module) { sts = RunModule(module, 1); free(module); } -c is executed through the PyRun_SimpleStringFlags() function, which in turn calls PyRun_StringFlags(). When you use exec a bytestring object is passed to PyRun_StringFlags() too, and the source code is then assumed to contain Latin-1-encoded bytes. -m uses the RunModule() function to pass the module name to the private function _run_module_as_main() in the runpy module, which uses pkgutil.get_loader() to load the module metadata, and fetches the module code object with the loader.get_code() function on the PEP 302 loader; if no cached bytecode is available then the code object is produced by using the compile() function with the mode set to exec.
has comment: http://stackoverflow.com/comment/85013634
has comment: http://stackoverflow.com/comment/85011264
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48984214
type: AcceptedAnswer

http://stackoverflow.com/a/49059505
has comment: http://stackoverflow.com/comment/85124347
accepted answer of: http://stackoverflow.com/q/49059409
answers question: http://stackoverflow.com/q/49059409
upvote count: 2
has comment: http://stackoverflow.com/comment/85124482
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85148311
type: Answer
score: 2
has body: Here is one way, but I wish there was an in-built way to do this. import pandas as pd df = pd.DataFrame({'A': [11, 11, 22, 22, 33, 33], 'B': [3, 6, 1, 2, 4, 4]}) g = df.groupby('A', as_index=False).agg({'B': ['min', 'max']}) g.columns = ['_'.join(col).strip() if col[1] else col[0] for col in g.columns.values] # A B_min B_max # 0 11 3 6 # 1 22 1 2 # 2 33 4 4
has comment: http://stackoverflow.com/comment/124122473
downvote count: 0

http://stackoverflow.com/a/49031036
has body: You must declare a primary key for the association table. Flask-SQLALchemy is an ORM, and it needs a series of columns that uniquely identify a row. Take a look to this part of the documentation, a bit outdated, but still valid: http://docs.sqlalchemy.org/en/rel_1_1/faq/ormconfiguration.html#faq-mapper-primary-key Flask-SQLALchemy is using all the fields (left_id, right_id) to identify the rows, and all the rows have the same values (6, 3). So, all the rows are stored in the database (as there are not any declared constraint on it), but only one is retained in the context (memory).
has comment: http://stackoverflow.com/comment/85094386
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48979450
has comment: http://stackoverflow.com/comment/85080772
type: Answer
has comment: http://stackoverflow.com/comment/85103262

http://stackoverflow.com/comment/85234770
comment on: http://stackoverflow.com/a/49114680
type: AnswerComment
score: 0
type: Comment
has text: Thanks, why would my IDE ignore this and how could I fix that? Thank you

http://stackoverflow.com/a/49038354
has body: You could use a list comprehension: def factorCounts(n): a = factors(n) b = [howManyTimesDivides(n, i) for i in a] return b print(factorCounts(20)) Output: [2, 1, 3, 2, 1]
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49038122
type: Answer
accepted answer of: http://stackoverflow.com/q/49038122

http://stackoverflow.com/a/49035423
type: Answer
answers question: http://stackoverflow.com/q/49035274
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49035274
has comment: http://stackoverflow.com/comment/85075762
has body: you are missing a / after the city and a e in forecast. It should be url = 'http://www.weather-forecast.com/locations/'+city+'/forecasts/latest'
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84951229
comment on: http://stackoverflow.com/a/48973023
score: 0
type: Comment
has text: Thanks a ton Jean! Your help was really valuable! it saved me tones and tones of trouble! But now I am running into some other problem. I will probably open another thread for that. But thanks for this one.
type: AnswerComment

http://stackoverflow.com/comment/85200650
comment on: http://stackoverflow.com/q/49097561
type: Comment
type: QuestionComment
score: 0
has text: I don't see any class called `price`, I think you should be [searching for `product-tile-price`](https://i.imgur.com/b0m0SoH.png)

http://stackoverflow.com/comment/85184794
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/49089619
has text: Take a look at [collections.Counter](https://docs.python.org/2/library/collections.html#collections.Counter). It will do the counting for you ;)

http://stackoverflow.com/q/49089539
score: 0
has comment: http://stackoverflow.com/comment/85186321
answer count: 1
has body: I am doing a project about analysing the green trend of the trees. In term of initial processing, I've got intensity value for the whole 500 images and decided the threshold for selecting good images from the datasets. It's around from 60 to 122, and I named the range as good images.I also have detected some fog/haze images from the datasets with @ Andriy Makukha's help. However, when I was trying to use the same method to distinguish good pictures and bad pictures in the different sense, it did not work at all. As you can see from the picuures below: This is my code for the average of intensity and threshold: im = Image.open('IMAG0170.JPG') im_grey = im.convert('LA') width,height = im.size total=0 for i in range(0,width): for j in range(0,height): total += im.getpixel((i,j))[0] mean = total / (width * height) print mean import cv2 import numpy as np from matplotlib import pyplot as plt results = [] for dirpath, dirnames, filenames in os.walk("/Users/Terrynightbleach/Desktop/Dataset-Tree/No1_Leith Valley/"): for filename in [f for f in filenames if f.endswith('.JPG')]: img = cv2.imread(filename) avg_color_per_row = numpy.average(img, axis=0) avg_color = numpy.average(avg_color_per_row, axis=0) results.append(sum(avg_color/3)) np_results = np.array(results) plt.hist(np_results,bins=100) plt.show() In term of this site, it was really hard to decide the threshold.Are there any methods that I can use to distinguish the dark pictures with high intensity from the datasets? If I was planing to focus on local variance and run a window approach, could some experts give me a hint on it. Thank you so much...
has comment: http://stackoverflow.com/comment/85184895
has title: Bright dark images detection
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85193735
tagged with: python
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/85184713
has answer: http://stackoverflow.com/a/49103801

http://stackoverflow.com/comment/84964893
comment on: http://stackoverflow.com/q/48979859
type: QuestionComment
has text: Why are these similarly structured data frames not contained in a list or dict? Please back up and explain how they are created.
score: 1
type: Comment

http://stackoverflow.com/q/49021968
has answer: http://stackoverflow.com/a/49022480
has comment: http://stackoverflow.com/comment/85049191
has comment: http://stackoverflow.com/comment/85049083
type: Question
has answer: http://stackoverflow.com/a/49022429
tagged with: python
has comment: http://stackoverflow.com/comment/85049232
has title: Python/Itertools: Get latest file by name
has comment: http://stackoverflow.com/comment/85049121
score: 0
tagged with: iterator
answer count: 2
tagged with: python-itertools
type: UnansweredQuestion
has body: I have a list of filenames in a directory and I'd like to keep only the latest versions. The list looks like: ['file1-v1.csv', 'file1-v2.csv', 'file2-v1.txt', ...]. I'd like to only keep the newest csv files as per the version (part after - in the filename) and the txt files. The output would be [''file1-v2.csv', 'file2-v1.txt', ...] I have a solution that requires the use of sets but I'm looking for a easy pythonic way to do this. Potentially using itertools and groupby Update: Solution so far I've been able to do some preliminary work to get a list like lst = [('file1', 'csv', 'v1','&lt;some data&gt;'), ('file2', 'csv', 'v2','&lt;some data&gt;'), ...] I'd like to group by elements at index 0 and 1 but provide only the tuple with the maximum index 2. It may be something like the below: files = list(item for key, group in itertools.groupby(files, lambda x: x[0:2]) for item in group) # Maximum over 3rd index element in each tuple does not work files = max(files, key=operator.itemgetter(2)) Also, I feel like the below should work but it does not select the maximum properly [max(items, key=operator.itemgetter(2)) for key, items in itertools.groupby(files, key=operator.itemgetter(0, 1))]
has comment: http://stackoverflow.com/comment/85049039

http://stackoverflow.com/q/49036579
has title: calculating average values in a file using awk from multiple files
answer count: 2
tagged with: bash
tagged with: matrix
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/49037227
has comment: http://stackoverflow.com/comment/85078674
downvote count: 1
tagged with: average
type: Question
has answer: http://stackoverflow.com/a/49038403
has comment: http://stackoverflow.com/comment/85078898
has body: I have 100 files with name file.1.netcc, file.2.netcc ... file.100.netcc. Each file contains the following contents: # 4 # Number of network ROIs # 2 # Number of netcc matrices # WITH_ROI_LABELS LFovea_LO LLO LMT RV3A 1 2 3 4 # CC 1.0000 0.2271 -0.1172 -0.2258 0.2271 1.0000 0.3991 0.1092 -0.1172 0.3991 1.0000 0.3055 -0.2258 0.1092 0.3055 1.0000 # FZ 4.0000 0.2312 -0.1177 -0.2297 0.2312 4.0000 0.4226 0.1096 -0.1177 0.4226 4.0000 0.3156 -0.2297 0.1096 0.3156 4.0000 Now, what I want to happen is to average all the 'cc' values for example. Each value will be averaged from all files. For instance, we take the first value from first column, first row (1.0000) to be averaged from all the files and outputted to be the average value... and so on until the last digit, which is the 4column, 4th row value (1.0000) to be averaged for all files. So what I want returned, is to have a 4x4 table with the values averaged out for all files. I also want this done for the 'FZ' category below it. How can I do this? I tried using this command: awk '{a[FNR]+=" "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8;b[FNR]++;}END{for(i=1;i&lt;=FNR;i++)print i,a[i]/b[i];}' /Users/3dnetcorr/file*.netcc &gt; outputs_averaged.file but what this command did (i think) was average out the entire column to give me one value per column.. and this is not what I want it to do. I guess what I'm asking is how can i average out files that contain a matrix? How can I do this with python coding? numpy maybe?

http://stackoverflow.com/q/48983144
type: UnansweredQuestion
tagged with: templating
favorite count: 0
has comment: http://stackoverflow.com/comment/84971738
type: Question
downvote count: 2
tagged with: django
tagged with: python
score: -2
answer count: 1
has body: class Client(models.Model): Name = models.CharField(max_length=100,blank=False,null=False) class Expense(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) title = models.CharField(max_length=100,blank=False,null=False) amount= models.DecimalField(max_digits=8,decimal_places=2) #currency = models.CharField(max_length = 5) from_date = models.DateField(auto_now=False) to_date = models.DateField(auto_now=False) Description = models.TextField() def __unicode__(self): return self.title I have two models above where Expense should be the object of Client . how to write templating part: 1.To get list of clients . 2.If we click on the client , should get list of expenses list related to the client.....
has answer: http://stackoverflow.com/a/48984885
upvote count: 0
has title: Django: Foreign key related list
has comment: http://stackoverflow.com/comment/84974332

http://stackoverflow.com/q/49034664
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
type: Question
has body: import pyautogui pyautogui.typewrite('Março') It types Maro (it skips the character 'ç').
tagged with: pyautogui
has title: Using pyautogui.typewrite() w/ special characters
has answer: http://stackoverflow.com/a/67271091
answer count: 1

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/49046757
tags question: http://stackoverflow.com/q/49099032
tags question: http://stackoverflow.com/q/48972470
type: Tag

http://stackoverflow.com/a/49108085
answers question: http://stackoverflow.com/q/49107867
upvote count: 1
has body: You can use math module in python to separate decimal and integer part import math x = 1001.0010101 math.modf(x) #output:(0.0010101000000304339, 1001.0) Iterate as you want Have doubt about extra numbers in end of decimal read docs
has comment: http://stackoverflow.com/comment/85221083
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/49026396
has body: I also encountered this problem. As far as I understand this version of pymqi-1.7.2.tar.rz is not suitable for python 3 Install the version of py3mqi-1.6.0.tar.gz
has comment: http://stackoverflow.com/comment/85099910
score: 0
answers question: http://stackoverflow.com/q/48990333
type: Answer

http://stackoverflow.com/comment/121801328
has text: Answering my own comment above, it is the sample number =)
comment on: http://stackoverflow.com/a/49009008
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85159113
score: 0
has text: If you only want to modify a variable in another module, just use `a.value` to access it. I don't know why you mention that function `x()`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49076566

http://stackoverflow.com/q/49020182
tagged with: multithreading
has body: I have a very simple list comprehension I would like to parallelize: nlp = spacy.load(model) texts = sorted(X['text']) # TODO: Parallelize docs = [nlp(text) for text in texts] However, when I try using Pool from the multiprocessing module like so: docs = Pool().map(nlp, texts) It gives me the following error: Traceback (most recent call last): File "main.py", line 117, in &lt;module&gt; main() File "main.py", line 99, in main docs = parse_docs(X) File "main.py", line 81, in parse_docs docs = Pool().map(nlp, texts) File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 260, in map return self._map_async(func, iterable, mapstar, chunksize).get() File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 608, in get raise self._value File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 385, in _handle_tasks put(task) File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) AttributeError: Can't pickle local object 'FeatureExtracter.&lt;locals&gt;.feature_extracter_fwd' Is it possible to do this parallel computation without having to make objects pickleable? I'm open to examples tied to third-party libraries such as joblib, etc. edit: I also tried docs = Pool().map(nlp.__call__, texts) and that didn't work either.
has title: Python parallel computation without pickling
tagged with: parallel-processing
has answer: http://stackoverflow.com/a/51004703
type: Question
tagged with: python-multiprocessing
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/49020257
tagged with: python
tagged with: joblib
type: UnansweredQuestion

http://stackoverflow.com/q/49062287
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85129666
answer count: 0
tagged with: tensorflow
type: Question
has body: I'm currently using LSTM to predict stock price sequence. I've found some implement code online, and try to do similar by myself. While running my program, I showed the train accuracy during iterations to check performance, but here comes the problem: sometimes the train accuracy improved during training epoch, but sometimes it remain unchanged. Here is my code: import tensorflow as tf from tensorflow.contrib import rnn import numpy as np import matplotlib.pyplot as plt from pandas_datareader import data, wb import pandas as pd import datetime sequence = 7 # time span inputD = 1 # input dimension outD = 1 # output dimension # normalize data in each column def Normalized(data): numerator = data - np.min(data, 0) denominator = np.max(data, 0) - np.min(data, 0) # noise term prevents the zero division return numerator / denominator # Convert sequence data to usable for training def dataConvert(data): data = data[::-1] data = Normalized(data) x_data = [] y_data = [] for i in range(0, len(data) - sequence): _x = data[i:i + sequence] _y = data[i + sequence] x_data.append(_x) y_data.append(_y) x_data = np.array(x_data) y_data = np.array(y_data) return x_data, y_data data = np.loadtxt('ibm2.csv') a = [] for i in range(len(data)): a.append([data[i]]) data = np.array(a) x_data, y_data = dataConvert(data) train_size = int(len(y_data) * 0.7) # 70% data for training x_train = np.array(x_data[:train_size]) x_test = np.array(x_data[train_size:]) y_train = np.array(y_data[:train_size]) y_test = np.array(y_data[train_size:]) X = tf.placeholder(tf.float32, [None, None, 1]) Y = tf.placeholder(tf.float32, [None, outD]) cell = rnn.BasicLSTMCell(num_units=10, state_is_tuple=True, activation=tf.tanh) outputs, _state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32) y_pred = tf.contrib.layers.fully_connected(outputs[:,-1], outD) loss = tf.reduce_sum(tf.square(y_pred - Y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.01) train = optimizer.minimize(loss) targets = tf.placeholder(tf.float32…
has comment: http://stackoverflow.com/comment/85130108
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/85129888
has comment: http://stackoverflow.com/comment/85129931
has title: Why does my performance of LSTM network sometimes worse?

http://stackoverflow.com/a/49108589
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has body: First you need to sort your infos queryset according to the sensor name using orderby https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by. Then you can use Javascript with django template tags to achieve &lt;script type="text/javascript"&gt; var sensor_name = ""; var counter = 1; {% for info in infos %} if (sensor_name != {{info.name}}) { sensor_name = {{info.name}}; counter = 1; } else { counter += 1; } $("span").text(counter); //this is your span where you show the sensor number {% endfor %} &lt;/script&gt;
answers question: http://stackoverflow.com/q/49108090
accepted answer of: http://stackoverflow.com/q/49108090

http://stackoverflow.com/q/48964030
accepted answer: http://stackoverflow.com/a/48964393
tagged with: python
type: AnsweredQuestion
has title: Unable to upload images to S3 from Scrapy
tagged with: scrapy
has body: My spider works fine if I use local file to store the downloaded images. But when trying to upload to Amazon S3, it shows this error 2018-02-24 14:37:06 [scrapy.core.scraper] ERROR: Error processing {'category': {'level_1': {'name': u'Electronics', 'url': u'electronics'}, 'level_2': {'name': u'Accessories', 'url': u'electronics-computers-office-accessories'}}, 'image_urls': [u'http://www.some.com/media/catalog/product/cache/1/small_image/165x/9df78eab33525d08d6e5fb8d27136e95/r/s/rs500.jpg'], }, 'name': u'Gift Card Rupees 500', } Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/scraper/scraper/pipelines.py", line 32, in process_item if not item['images']: File "/usr/local/lib/python2.7/site-packages/scrapy/item.py", line 59, in __getitem__ return self._values[key] KeyError: 'images' I have below settings for AWS IMAGES_STORE = 's3://myproject-products-images/' IMAGES_EXPIRES = 180 AWS_ACCESS_KEY_ID = 'sdfasfasfsaf' AWS_SECRET_ACCESS_KEY = 'adfasfasfasf' I have a fresh s3 account all default settings. Here is my pipeline to check for images which is throwing the above error class ImageCheckPipeline(object): """ Pipeline to check if image is present in the scraped product If not then remove that product from the process :param object: """ def process_item(self, item, spider): """ :param self: :param item: :param spider: """ if not item['images']: spider.logger.error('Images not found', {'item': item}) raise DropItem return item
type: Question
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/48964393
tagged with: amazon-web-services
score: 0
answer count: 1

http://stackoverflow.com/q/49071212
score: 1
type: Question
upvote count: 1
answer count: 1
tagged with: dataset
favorite count: 0
tagged with: tensorflow-datasets
has answer: http://stackoverflow.com/a/49071724
tagged with: python
has title: How to use tf.Dataset design in both training and inferring?
downvote count: 0
type: UnansweredQuestion
has body: Say, we have input x and label y: iterator = tf.data.Iterator.from_structure((x_type, y_type), (x_shape, y_shape)) tf_x, tf_y = iterator.get_next() Now I use generate function to create dataset: def gen(): for ....: yield (x, y) ds = tf.data.Dataset.from_generator(gen, (x_type, y_type), (x_shape, y_shape)) In my graph, I use tf_x and tf_y to do training, that is fine. But now I want to do referring, where I don't have label y. One workaround I made is to fake a y (like tf.zeros(y_shape)), then I use a placeholder to init the iterator. x_placeholder = tf.placeholder(...) y_placeholder = tf.placeholder(...) ds = tf.data.Dataset.from_tensors((x_placeholder, y_placeholder)) ds_init_op = iterator.make_initializer(ds) sess.run(ds_init_op, feed_dict={x_placeholder=x, y_placeholder=fake(y))}) My question is, is there a cleaner way to do that? without fake a y during inferring time? UPDATE: I experiment a little bit, looks like there is one dataset operation unzip missing: import numpy as np import tensorflow as tf x_type = tf.float32 y_type = tf.float32 x_shape = tf.TensorShape([None, 128]) y_shape = tf.TensorShape([None, 10]) x_shape_nobatch = tf.TensorShape([128]) y_shape_nobatch = tf.TensorShape([10]) iterator_x = tf.data.Iterator.from_structure((x_type,), (x_shape,)) iterator_y = tf.data.Iterator.from_structure((y_type,), (y_shape,)) def gen1(): for i in range(100): yield np.random.randn(128) ds1 = tf.data.Dataset.from_generator(gen1, (x_type,), (x_shape_nobatch,)) ds1 = ds1.batch(5) ds1_init_op = iterator_x.make_initializer(ds1) def gen2(): for i in range(80): yield np.random.randn(128), np.random.randn(10) ds2 = tf.data.Dataset.from_generator(gen2, (x_type, y_type), (x_shape_nobatch, y_shape_nobatch)) ds2 = ds2.batch(10) # my ds2 has two tensors in one element, now the problem is # how can I unzip this dataset so that I can apply them to iterator_x and iterator_y? # such as: ds2_x, ds2_y = tf.data.Dataset.unzip(ds2) #?? missing this unzip operation! ds2_x_init_op = it…
tagged with: tensorflow

http://stackoverflow.com/q/48994243
has title: Cannot allocate memory when forking in Python, but there is memory
answer count: 0
tagged with: fork
type: UnansweredQuestion
tagged with: multithreading
score: 2
downvote count: 0
type: Question
upvote count: 2
has body: When I run the following Thread, it spawns 5 forks. The first time I run it, it goes smooth, everything ok. But when it runs again, after the sleep(60) (while True loop), by the time the thread tries to fork() the processes, I get the following error: OSError: [Errno 12] Cannot allocate memory _td = threading.Thread(target=updateProxies,args=()) _td.start() def updateProxies(): while True: quota = 5 children = [] sons = 0 for i in range(50): pid = os.fork() if pid: children.append(pid) sons+=1 if sons &gt;= quota: os.wait() sons-=1 else: {CHILD CODE EXECUTION} #database calls, and network requests os._exit(0) for x in children: os.waitpid(x,0) sleep(60) Things I debugged: Already tracked if there are any defuncts left from the previous forks and there are none. Already monitored the server memory, and there are plenty left (at least to spawn more forks again) My bash script to monitor the memory is: #!/bin/bash while true do free | awk '/Mem/{printf("used: %.2f%"), $3/$2*100} /buffers\/cache/{printf(", buffers: %.2f%"), $4/($3+$4)*100} /Swap/{printf(", swap: %.2f%\n"), $3/$2*100}' sleep .5 done Which marked: used: 16.41%, swap: 3.86% #before the script execution used: 21.32%, swap: 3.86% #during the 5 forks execution used: 19.86%, swap: 3.86% #after the 5 forks ended This means that the 5 forks only increased around 5% percent of memory when they got spawned. So there is memory available. Then why I just can't spawn the forks again?
favorite count: 0
tagged with: memory-leaks
tagged with: python

http://stackoverflow.com/comment/85078170
type: QuestionComment
type: Comment
has text: No it's only my second week learning python. I'll start working on that when two more weeks pass, and I'll let you know.
score: 0
comment on: http://stackoverflow.com/q/49036032

http://stackoverflow.com/comment/85074413
comment on: http://stackoverflow.com/a/49034358
type: AnswerComment
type: Comment
has text: I see. That does what I need it to do, and is short and simple. Thanks!
score: 1

http://stackoverflow.com/q/48975975
score: -1
possible better answer: http://stackoverflow.com/a/48979911
has comment: http://stackoverflow.com/comment/84964958
tagged with: class
type: Question
has answer: http://stackoverflow.com/a/48979911
linked to: http://stackoverflow.com/q/1933451
answer count: 2
downvote count: 2
upvote count: 1
favorite count: 0
tagged with: python
has body: I'm creating a simple container system, in which my objects (all children of a class called GeneralWidget) are grouped in some containers, which are in another set of containers, and so on until all is in one Global container. I have a custom class, called GeneralContainer, in which I had to override the __str__ method to provide a describing name for my container, So I know what kind of objects or containers are stored inside of him. I am currently writing another class called ObjectTracker in which all positions of my Objects are stored, so when a new object is created, It gives a list with its' name in it in the __init__ method to it's "parent" in my hieracy, which adds itself to the list and passes it on. At some point this list with all objects that are above the new created instance of GeneralWidget will reach the global GeneralWidget (containing all containers and widgets) , which can access the ObjectTracker-object in my main(). This is the bachground of my problem. My ObjectTracker has got a dictionary, in which every "First Level container" is a key, and all objects inside such a container are stored in dictionarys as well. So I have many encapsulated dictionarys. As I don't know how many levels of containers there will be, I need a dynamic syntax that is independent of the number of dictionarys I need to pass unil I get to the place in the BIG dictionary that I want. A (static) call inside my ObjectRepository class would need to look something like this: self._OBJECTREPOSITORY[firstlevelcontainer12][secondlevel8][lastlevel4] = myNewObject with firstlevelcontainer12 containing secondlevel8 which contains lastlevel4 in which the new object should be placed But I know neither how the containers will be called, nor how many there will be, so I decided to use exec() and compose a string with all names in it. I will post my actual code here, the definition of ObjectTracker: class ObjectTracker: def __init__(self): self._NAMEREPOSITORY = {} def addItem(self, pat…
has comment: http://stackoverflow.com/comment/84958868
type: AnsweredQuestion
has title: Get the name of the instance of an object in python, when __str__ overridden?
has answer: http://stackoverflow.com/a/48979993
accepted answer: http://stackoverflow.com/a/48979993

http://stackoverflow.com/a/49018313
has comment: http://stackoverflow.com/comment/85042010
has comment: http://stackoverflow.com/comment/85041944
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49018232
downvote count: 0
has body: Try changing the positional argument you have in change_presence to a keyword argument: according to the docs, that would be game. Hence client.change_presence(discord.Game(name="use !commands")) to client.change_presence(game=discord.Game(name="use !commands")). In addition if we check out the source code for discord.py, we can see the exact reason for your error. Line 409 in this file defines change_presence as def change_presence(self, *, game=None, status=None, afk=False, since=0.0, idle=None) we can see the asterisk (*) right after the self argument which is Python 3 semantics for accepting only keyword arguments after the asterisk. You can see this StackOverflow answer for some more information. That means that all arguments after self are purely keyword arguments (need an identifier), you are passing an argument which coupled with self (passed in automatically) makes two positional arguments when the maximum positional arguments are just one (which is self). So you must change your positional argument to a keyword one.
accepted answer of: http://stackoverflow.com/q/49018232
has comment: http://stackoverflow.com/comment/85041791
has comment: http://stackoverflow.com/comment/85041821
type: Answer
upvote count: 2

http://stackoverflow.com/q/49018461
score: 1
upvote count: 1
type: Question
has title: TabPy TypeError %d format a number is required, not str, followed by no return value
tagged with: tabpy
answer count: 1
downvote count: 0
tagged with: tableau-api
favorite count: 0
has answer: http://stackoverflow.com/a/49048569
accepted answer: http://stackoverflow.com/a/49048569
tagged with: python
has body: I have just started to work with TabPy on 10.13.2. I used the conda pymysql packages (pymysql and PyMySQL-0.8.0-py2.7.egg-info) and placed them in the site-packages for anaconda, so that Tableau would be able to connect to the db, retrieve the dataset and hold in a calculated field. I originally tried mysql.connector, as I do within PyCharm and the CLI, but TabPy uses anaconda, which does not have a site-package for mysql. Anyways, it initially connects to the TabPy server, which returns: An error occurred while communicating with the Predictive Service. However, this is soon followed by the next two lines: Error processing script TypeError : %d format: a number is required, not str I have done some digging for the aforementioned error and everything that I have tried has produced the same error. I found the solution, but I have another error at the end. SCRIPT_REAL(" import pymysql db = pymysql.connect( host='localhost', port='9999', user='usern', passwd='passw', db='someDb' ) cur = db.cursor() t1 = int(0) t2 = datetime.datetime(2018, 2, 1) sqlStr = 'select distinct APPL_ID, APPL_SUBMIT_DT from APPL_APP where APPL_ACTIVE_FLAG &gt; %d and APPL_SUBMIT_DT &gt;= %d' % (t1, t2) cur.execute() for row in cur.fetchall(): print row db.close() ", COUNT([Appl Id]) ) I do not understand why the script would be returning such an error, until I ran it in PyCharm. It was my port number that needed to be a number instead of a string. import pymysql db = pymysql.connect( host='localhost', port=9999, user='usern', passwd='passw', db='someDb' ) cur = db.cursor() t1 = int(0) t2 = (2018-02-01) sqlStr = 'select distinct APPL_ID, APPL_SUBMIT_DT from APPL_APP where APPL_ACTIVE_FLAG &gt; %d and APPL_SUBMIT_DT &gt;= %d' % (t1, t2) cur.execute(sqlStr) for row in cur.fetchall(): print row db.close() Of course, while I could see all the data being returned in my terminal via the TabPy server, but it finished with the following: (3957423, datetime.datetime(2018, 2, 27, 15, 30, 16)) (3957424, da…
type: AnsweredQuestion

http://stackoverflow.com/comment/85157151
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49074033
has text: Where is *SE* used in this solution?
type: Comment

http://stackoverflow.com/a/48999881
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/48999379
downvote count: 0
has body: As per the error, it is clear that the failure is when your Application is trying to postgres and the important part to concentrate is Authentication. Do these steps to first understand and reproduce the issue. I assume it as a Linux Server and recommend these steps. Step 1: $ python3 &gt;&gt;&gt;import psycopg2 &gt;&gt;&gt;psycopg2.connect("dbname=postgres user=postgres host=localhost password=oracle port=5432") &gt;&gt;&gt;connection object at 0x5f03d2c402d8; dsn: 'host=localhost port=5432 dbname=postgres user=postgres password=xxx', closed: 0 You should get such a message. This is a success message. When i use a wrong password, i get this error. &gt;&gt;&gt;psycopg2.connect("dbname=postgres user=postgres host=localhost password=wrongpassword port=5432") &gt;&gt;&gt;Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" When there is no entry in pg_hba.conf file, i get the following error. &gt;&gt;&gt; psycopg2.connect("dbname=postgres user=postgres host=localhost password=oracle port=5432 ") &gt;&gt;&gt; Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "postgres", database "postgres", SSL on FATAL: no pg_hba.conf entry for host "::1", user "postgres", database "postgres", SSL off So, the issue is with password. Check if your password contains any special characters or spaces. if your password has spaces or special characters, use double quotes as i used below. &gt;&gt;&gt; …
has comment: http://stackoverflow.com/comment/85006594
type: Answer

http://stackoverflow.com/a/48963848
answers question: http://stackoverflow.com/q/48963762
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: django 2.0 needs python3. I recommend moving to python3

http://stackoverflow.com/q/49114202
tagged with: python
has body: I'm switching development from python to Ipython (because of the decision of the developers to drop the python console in spyder starting at version 3.x). I run into a problem, I didn't have before and I'm not really sure if this is due to Ipython or to the new spyder version I'm using. When I execute this code import sys reload(sys) sys.setdefaultencoding('cp1252') from foo import bar where foo.py looks like bar = 5 inside an Ipython shell in Spyder, the first time it executes without problems, the second time it hangs. I'm not actually looking for a solution to this, but rather would like to know why this is happening.
answer count: 0
tagged with: reload
tagged with: sys
has title: Import sys with reload hangs ipython inside Spyder
type: Question
has comment: http://stackoverflow.com/comment/85281913
score: 0
has comment: http://stackoverflow.com/comment/85310526
type: UnansweredQuestion
tagged with: spyder

http://stackoverflow.com/q/48978758
has title: How the speed up the calculation of updating values of each element in an array based on other elements in Python?
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84967347
has comment: http://stackoverflow.com/comment/84963632
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48981378
type: Question
has comment: http://stackoverflow.com/comment/84962750
tagged with: numpy
has answer: http://stackoverflow.com/a/48978794
has body: I am now working on a calculation shown below. I want to update the values of each element based on their adjacent elements. I am now using two for loops, but it shows the calculation is very slow since there are several outer iterations. I want to know whether there is any way can speed up this calculation> for i in range(1,nx+1): for j in range(1,ny+1): p[i,j]=(a*p[i-1,j]+b*p[i+1,j]+c*p[i,j-1]+d*p[i,j+1]) a, b, c, d are some constant, p is numpy.array type Sample input: import numpy as np p = np.ones((5,5)) for i in range(1,4): for j in range(1,4): p[i,j]=p[i-1,j] + p[i+1,j] +2*p[i,j+1]+2*p[i,j-1] print(p) The final output should be: [[ 1. 1. 1. 1. 1.] [ 1. 6. 16. 36. 1.] [ 1. 11. 41. 121. 1.] [ 1. 16. 76. 276. 1.] [ 1. 1. 1. 1. 1.]]

http://stackoverflow.com/q/49049266
has answer: http://stackoverflow.com/a/49052399
tagged with: django
tagged with: python
has title: Change logo of AdminLTE in django
type: Question
has comment: http://stackoverflow.com/comment/85103398
score: 0
answer count: 1
has body: I am using AdminLTE in my django admin site. I want to change its logo to my site name and also want to change its redirect link. But not getting any help related to that. Please give the solution if anyone has an idea about that.
tagged with: adminlte
type: UnansweredQuestion

http://stackoverflow.com/comment/85130417
score: 0
type: AnswerComment
has text: question is about using one set of variable. not one set of values. it's hardcoded right now, only coz it's code snippet and not actual code.
type: Comment
comment on: http://stackoverflow.com/a/49062396

http://stackoverflow.com/comment/85113331
type: AnswerComment
has text: hi thanks for this and apologies for more noob questions
type: Comment
comment on: http://stackoverflow.com/a/49048777
score: 0

http://stackoverflow.com/a/49042814
score: 0
answers question: http://stackoverflow.com/q/49011988
type: Answer
has comment: http://stackoverflow.com/comment/85100038
has body: For illustrative purposes, here is a general solution that doesn't require 3rd party libraries: from collections import deque from datetime import datetime, timedelta def sliding_window(it, size, dist=(lambda a, b: b - a), index=(lambda x: x)): q = deque() for item in it: i = index(item) while q and dist(q[0][0], i) &gt;= size: yield [x for _, x in q] q.popleft() q.append((i, item)) if q: yield [x for _, x in q] if __name__ == '__main__': import pprint pprint.pprint(list(sliding_window( [ { "timestamp": "2018-01-18T04:00:00Z" }, { "timestamp": "2018-01-18T04:00:01Z" }, { "timestamp": "2018-01-18T04:03:00Z" }, { "timestamp": "2018-01-18T04:04:00Z" }, { "timestamp": "2018-01-18T04:10:00Z" }, { "timestamp": "2018-01-18T04:24:00Z" }, { "timestamp": "2018-01-18T04:28:00Z" } ], timedelta(minutes=7), index=lambda x: datetime.strptime(x["timestamp"], "%Y-%m-%dT%H:%M:%SZ") ))) This outputs: [[{'timestamp': '2018-01-18T04:00:00Z'}, {'timestamp': '2018-01-18T04:00:01Z'}, {'timestamp': '2018-01-18T04:03:00Z'}, {'timestamp': '2018-01-18T04:04:00Z'}], [{'timestamp': '2018-01-18T04:00:01Z'}, {'timestamp': '2018-01-18T04:03:00Z'}, {'timestamp': '2018-01-18T04:04:00Z'}], [{'timestamp': '2018-01-18T04:03:00Z'}, {'timestamp': '2018-01-18T04:04:00Z'}], [{'timestamp': '2018-01-18T04:04:00Z'}, {'timestamp': '2018-01-18T04:10:00Z'}], [{'timestamp': '2018-01-18T04:10:00Z'}], [{'timestamp': '2018-01-18T04:24:00Z'}, {'timestamp': '2018-01-18T04:28:00Z'}]]

http://stackoverflow.com/q/49026570
answer count: 3
has answer: http://stackoverflow.com/a/49026856
has body: How can I convert any date to just number of days? This is what I tried: import datetime import calendar def leap_day_counter(yr): leap_days = 0 # since 1582 11 days are missing if yr &gt;= 1582: leap_days += 11 for specific_year in range(1, yr): if calendar.isleap(specific_year): leap_days += 1 return leap_days def month_to_day(yr, mth): all_days = 0 for specific_month in range(1, mth+1): days_in_month = calendar.monthrange(yr, specific_month) all_days += days_in_month[1] return all_days date = datetime.datetime.now() days_passed = ((date.year * 365) + leap_day_counter(date.year)) + month_to_day(date.year, date.month) + date.day print(days_passed) I got 737 158 days but according to https://www.timeanddate.com/date/durationresult.html I should have 736 755 days. Do I miss something? Is there easier way to do this?
favorite count: 0
has comment: http://stackoverflow.com/comment/85057935
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49027159
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/85058007
has comment: http://stackoverflow.com/comment/85057963
has comment: http://stackoverflow.com/comment/85058452
score: 2
has comment: http://stackoverflow.com/comment/85058684
has comment: http://stackoverflow.com/comment/85057812
has comment: http://stackoverflow.com/comment/85057918
upvote count: 3
has comment: http://stackoverflow.com/comment/85057943
has title: How to convert a date to a number of days from 0001-01-01?
downvote count: 1
has comment: http://stackoverflow.com/comment/85057849
has comment: http://stackoverflow.com/comment/85057924
has comment: http://stackoverflow.com/comment/85057987
type: Question
has answer: http://stackoverflow.com/a/49027671
has comment: http://stackoverflow.com/comment/85058386
has comment: http://stackoverflow.com/comment/85058027
tagged with: date
has comment: http://stackoverflow.com/comment/85058697
tagged with: python-2.7

http://stackoverflow.com/q/49059912
has title: Python - lifelines - add_covariate_to_timeline
tagged with: python
tagged with: survival-analysis
has body: I want to run a CoxTimeVaryingFitter on some data though I'm having some troubles with the add_covariate_to_timeline function which gives me the following error message: File "C:\Anaconda3\lib\site-packages\pandas\core\generic.py", line 692, in rename 'argument "{0}"'.format(list(kwargs.keys())[0])) TypeError: rename() got an unexpected keyword argument "axis"** from lifelines.utils import to_long_format from lifelines.utils import add_covariate_to_timeline l=data[data['duree']==1] df=to_long_format(l,duration_col='duree') h=data[data['duree']!=1] dfj=add_covariate_to_timeline(df,h,id_col="id",duration_col="duree",event_col="mort") I have run my code with the following dataframe 'data': id;mort;var;bar;duree 1;0;0,5;0;1 2;0;0,1;11;1 3;0;-1;111;1 1;0;1;5;2 1;1;1,5;6;3 2;0;0,2;12;2 3;1;-2;121;2 2;0;0,3;13;3 2;1;0,4;14;4
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85125380
type: Question
has comment: http://stackoverflow.com/comment/85184493
tagged with: lifelines
score: 0

http://stackoverflow.com/a/50286338
answers question: http://stackoverflow.com/q/49044853
type: Answer
has body: This might be due to openssl version. check your openssl version if its 0.9 then that might be a reason for the error. You can check openssl version in your python code using print ssl.OPENSSL_VERSION
has comment: http://stackoverflow.com/comment/138571302
downvote count: 1
score: -1
upvote count: 0

http://stackoverflow.com/a/49022356
has body: Try this. &lt;script language="JavaScript"&gt; function Select_All(source) { document.getElementByName("a1").checked = false; document.getElementByName("a2").checked = false; document.getElementByName("a3").checked = false; &lt;/script&gt; function turn_none_Off(source){ document.getElementByName("none").checked = false; &lt;/script language="JavaScript"&gt; &lt;input type="checkbox" name="a1" onClick="turn_none_Off(this)" value="1"&gt; A &lt;br/&gt; &lt;input type="checkbox" name="a2" onClick="turn_none_Off(this)" value="2"&gt; A &lt;br/&gt; &lt;input type="checkbox" name="a3" onClick="turn_none_Off(this)" value="3"&gt; A &lt;br/&gt; &lt;input type="checkbox" name ="none" onClick="Select_All(this)" /&gt; None of the Above &lt;br/&gt;
score: 0
has comment: http://stackoverflow.com/comment/85051277
type: Answer
has comment: http://stackoverflow.com/comment/85051261
answers question: http://stackoverflow.com/q/49022274
has comment: http://stackoverflow.com/comment/85049891
has comment: http://stackoverflow.com/comment/85050062
has comment: http://stackoverflow.com/comment/85051276
has comment: http://stackoverflow.com/comment/85050839

http://stackoverflow.com/a/49006474
score: 1
answers question: http://stackoverflow.com/q/49006391
downvote count: 0
type: Answer
has body: Store them? best_C = None best_gamma = None for C in np.arange(0.05, 2.05, 0.05): for gamma in np.arange(0.001, 0.101, 0.001): model = SVC(kernel='rbf', gamma=gamma, C=C) model.fit(X_train, y_train) score = model.score(X_test, y_test) if score &gt; best_score: best_score = score best_C = C best_gamma = gamma print('Highest Accuracy Score: ', best_score) print(best_C) print(best_gamma)
upvote count: 1

http://stackoverflow.com/comment/85015338
has text: @Scratch'N'Purr I've got your message, but there may be a misleading in the question. I'm ok with the result of neg_mean_squared_error and mse_path_, they are the same. The MSE calculated by myself is using the first alpha in the lassoCV result, and this MSE is supposed to be 5747.95194531 (for the first alpha and for the first test set in 10-fold CV). However I get 5625. That's what confusing me.
score: 0
comment on: http://stackoverflow.com/q/49004835
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85278649
score: 0
comment on: http://stackoverflow.com/q/49115494
type: Comment
type: QuestionComment
has text: Sorry i am new to this hehe

http://stackoverflow.com/a/49100302
type: AcceptedAnswer
downvote count: 0
score: 42
has body: I would suggest to look at supervisord approach. You can find how to use it in docker documentation. Some example: 1. Dockerfile is: FROM alpine:latest RUN apk update &amp;&amp; apk add --no-cache supervisor openssh nginx COPY supervisord.conf /etc/supervisord.conf CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"] 2. supervisord.conf is: [supervisord] nodaemon=true [program:sshd] command=/usr/sbin/sshd -D [program:nginx] command=nginx -c /etc/nginx/nginx.conf
type: Answer
has comment: http://stackoverflow.com/comment/95317528
accepted answer of: http://stackoverflow.com/q/49090469
answers question: http://stackoverflow.com/q/49090469
upvote count: 42

http://stackoverflow.com/q/49033015
type: Question
score: 1
has answer: http://stackoverflow.com/a/49342288
has comment: http://stackoverflow.com/comment/85105217
tagged with: import
has comment: http://stackoverflow.com/comment/85070960
answer count: 2
has body: I often end up in a situation where one package needs to use a sibling package. I want to clarify that I'm not asking about how Python allows you to import sibling packages, which has been asked many times. Instead, my question is about a best practice for writing maintainable code. Let's say we have a tools package, and the function tools.parse_name() depends on tools.split_name(). Initially, both might live in the same file where everything is easy: # tools/__init__.py from .name import parse_name, split_name # tools/name.py def parse_name(name): splits = split_name(name) # Can access from same file. return do_something_with_splits(splits) def split_name(name): return do_something_with_name(name) Now, at some point we decide that the functions have grown and split them into two files: # tools/__init__.py from .parse_name import parse_name from .split_name import split_name # tools/parse_name.py import tools def parse_name(name): splits = tools.split_name(name) # Won't work because of import order! return do_something_with_splits(splits) # tools/split_name.py def split_name(name): return do_something_with_name(name) The problem is that parse_name.py can't just import the tools package which it is part of itself. At least, this won't allow it to use tools listed below its own line in tools/__init__.py. The technical solution is to import tools.split_name rather than tools: # tools/__init__.py from .parse_name import parse_name from .split_name import split_name # tools/parse_name.py import tools.split_name as tools_split_name def parse_name(name): splits = tools_split_name.split_name(name) # Works but ugly! return do_something_with_splits(splits) # tools/split_name.py def split_name(name): return do_something_with_name(name) This solution technically works but quickly becomes messy if more than just one sibling packages are used. Moreover, renaming the package tools to utilities would be a nightmare, since now all the module aliases should change as well. It would l…
possible better answer: http://stackoverflow.com/a/49089630
has answer: http://stackoverflow.com/a/49089630
downvote count: 0
has comment: http://stackoverflow.com/comment/85071331
favorite count: 0
has comment: http://stackoverflow.com/comment/85162411
has title: How can I access sibling packages in a maintainable and readable way?
tagged with: maintainability
tagged with: package
accepted answer: http://stackoverflow.com/a/49342288
tagged with: python
has comment: http://stackoverflow.com/comment/85072167
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1

http://stackoverflow.com/a/49090211
downvote count: 1
answers question: http://stackoverflow.com/q/49089834
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49089834
type: Answer
has body: content[0x30:][:5][::-1].hex() Demo: &gt;&gt;&gt; content = b'.' * 0x30 + b'\x99\x9e\x36\x00\xac' + b'.' &gt;&gt;&gt; content[0x30:][:5][::-1].hex() 'ac00369e99' Though assuming this is an XY problem... &gt;&gt;&gt; int.from_bytes(content[0x30:][:4], 'little') 3579545 or &gt;&gt;&gt; struct.unpack('i', content[0x30:][:4])[0] 3579545 (Since you said "32 bits" and "clock rate" and apparently 3579545 Hz is a somewhat popular clock rate).
upvote count: 1

http://stackoverflow.com/a/49055000
has body: Your class subclasses logging.Logger, so you should not call getLogger or manipulate a logger as an attribute. Rather, the logger is self inside the class, and should be adjusted directly: import logging import sys print("imported module {}".format(__name__)) class PyLogger(logging.Logger): """Wrapper for logging.Logger to redirect its message to sys.stdout or sys.stderr accordingly """ def __init__(self, *args): super(PyLogger, self).__init__(self, *args) ##### # self *is* the logger! self.setLevel(logging.DEBUG) # build Formatter formatter = logging.Formatter(fmt="%(asctime)s:%(name)s %(message)s") # build StreamHandler for sys.stderr error = logging.StreamHandler(stream=sys.stderr) error.setLevel(logging.CRITICAL) error.setFormatter(formatter) ##### # Assign the handler to self self.addHandler(error) # build StreamHandler for sys.stdin out = logging.StreamHandler(stream=sys.stdout) out.setFormatter(formatter) out.setLevel(logging.WARNING) ##### # Assign the handler to self self.addHandler(out) def main(): logger = PyLogger() # help(logger) logger.info("INFO") logger.warning("WARN") logger.critical("CRIT") if __name__ == "__main__": main() This displays the following, as expected: ely@eschaton:~/programming$ python test_logger.py imported module __main__ 2018-03-01 11:59:41,896:&lt;__main__.PyLogger object at 0x7fa236aa4a50&gt; WARN 2018-03-01 11:59:41,896:&lt;__main__.PyLogger object at 0x7fa236aa4a50&gt; CRIT 2018-03-01 11:59:41,896:&lt;__main__.PyLogger object at 0x7fa236aa4a50&gt; CRIT Notice how the critical message trips two different output handlers, so it appears twice (once because it satisfied warning level, once for critical level). In your original code, notice that you are creating a variable called logger inside of __init__, but this not assigned to self or anything. This variable gets destroyed when it goes out of scope of the __init__ function, and so the assignment of any handlers is meaningless. Plus, because handlers weren't assigned to self, bu…
score: 1
has comment: http://stackoverflow.com/comment/85147079
accepted answer of: http://stackoverflow.com/q/49054556
has comment: http://stackoverflow.com/comment/85150981
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/102934426
has comment: http://stackoverflow.com/comment/85150894
has comment: http://stackoverflow.com/comment/100078232
has comment: http://stackoverflow.com/comment/99945399
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49054556

http://stackoverflow.com/q/48996789
favorite count: 0
has title: Maximum Likelihood Function in Python
type: UnansweredQuestion
tagged with: python
upvote count: 3
type: Question
score: 3
tagged with: math
tagged with: matplotlib
tagged with: gaussian
tagged with: bayesian
has answer: http://stackoverflow.com/a/49004396
downvote count: 0
answer count: 1
has body: I've been trying to write a Python code to generate a 2 dimensional matrix of likelihood values for a grid of x̄ and σ values using 10 values as a set of measurements. x̄ goes from 0.5 to 1.5 in steps of 0.01 and σ goes from 0.01 to 0.3 in steps of 0.01. After that I want to create a contour plot of the distribution. The likelihood function I'm using is Gaussian Likelihood. So far I have: List1 = open("DataSet1.dat").readlines() List2 = [float(i) for i in List1] x = List2[0:10] gaussian_pmf = lambda x, mu, sigma: (1 / (sigma*np.sqrt(2*np.pi)))*np.exp((- (x-mu)**2)/(2*(sigma**2))) mu = np.arange(0.5,1.51,0.01) sigma = np.arange(0.01,1.02,0.01) for i in range(0,len(mu)): distribution = [] for i in range (0,len(x)): distribution.append(gaussian_pmf(x[i],mu,sigma)) plt.contour(distribution) plt.show() X is an array of the 10 data values I need but I'm not sure what I am doing wrong here. plt.contour requires a 2d array and that is what I'm supposed to create but I'm not quite sure how. Any help would be much appreciated!

http://stackoverflow.com/q/49033295
tagged with: python-2.7
answer count: 1
has answer: http://stackoverflow.com/a/49047356
favorite count: 0
has body: I am trying to convert total physical memory into stick value, ie 128gb, 64gb..etc. if I take the value of total ram from my servers, example 16826298368, and run this code I get and expected output of 16gb. Which is great. But as the memory values increases, it begins to drift. Example: 134931955712 produces 126GB where 128GB is expected. Example: 67519483904 produces 63GB where 64GB is expected. So my question is, how can I modify to get the expected output consistently as the value changes? The memory value is provided by a few different bits of code depending on the OS. We use psutil on Solaris for example. psutil.virtual_memory().total def transform_memory(data): for x in ["bytes", " KB", " MB", " GB"]: if data &lt; 1024.0: return "%3.1f%s" % (math.ceil(data), x) data /= 1024.0 return "%3.1f%s" % (data, " TB")
has title: Python Convert Physical Memory to Stick Value
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85117557
score: 1
upvote count: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/85071851
tagged with: psutil

http://stackoverflow.com/a/49061024
type: Answer
answers question: http://stackoverflow.com/q/49060965
upvote count: 6
has comment: http://stackoverflow.com/comment/85127324
has comment: http://stackoverflow.com/comment/85127170
has body: If you're using Python-3.6+ the pythonic way is using f-strings, otherwise a dictionary comprehension: In [147]: x = 'TEST' In [148]: d = { ...: 'hello': f'world{x}', ...: 'foo': f'bar{x}' ...: } In [149]: d Out[149]: {'foo': 'barTEST', 'hello': 'worldTEST'} In python &lt; 3.6: d = { 'hello': f'world{var}', 'foo': f'bar{var}' } {k: val.format(var=x) for k, val in d.items()}
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85127070
accepted answer of: http://stackoverflow.com/q/49060965
score: 6

http://stackoverflow.com/a/49037910
type: Answer
accepted answer of: http://stackoverflow.com/q/49037294
answers question: http://stackoverflow.com/q/49037294
has body: You seem satisfied with integrate(2*x + 87*x*y + 7*y, y, manual=True) returning 2*x*y + 87*x*y**2/2 + 7*y**2/2 But the first term of this answer could also be 2*y*x. Or x*y + y*x. And these are all different answers. So, is the notion of an integral with noncommutative symbols well-defined to begin with? Maybe it's not that SymPy is weird, but the question you are asking it is. The concrete reason for this behavior is that manual integration is based on matching certain patterns. Such as "constant times something" pattern: coeff, f = integrand.as_independent(symbol) The method as_independent splits the product as independent * possibly_dependent, in this order. So, (x*y).as_independent(y) # returns (x, y) (x*y).as_independent(x) # returns (1, x*y) As a result, constant factors are recognized only in front of the expression, when the product is noncommutative. I don't think this can be fixed without rewriting one of the core methods as_independent to support noncommutative products (possibly returning independent * dependent * independent2) which looks like a lot of work to me. Before doing that work, I'd want to know whether the objective (antiderivative with noncommuting variables) is well defined.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/84942287
has text: He's not letting users input data into his pickle, he will only want to save his user objects somewhere so that he doesn't need to recreate them every time the script runs. You're right on the less functionality part though, I'll edit this.
comment on: http://stackoverflow.com/a/48967014
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/84995245
has text: Use [pastebin](https://pastebin.com/) to upload your JSON file to. Then post the URL here. We can then see your JSON file.
score: 0
comment on: http://stackoverflow.com/q/48993168
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49040228
type: AcceptedAnswer
downvote count: 0
has body: You can use next() to advance an iterator (including files): print(next(fq)) print(next(fq)) This consumes those lines, so the for loop will continue with @read2. if you don't want the AAA... line, you can also just consume it with next(fq). In full: fastq = open(Example.fastq, "r") IDs = [read1] with fastq as fq: for line in fq: if any(string in line for string in IDs): next(fq) # skip AAA line print(next(fq).strip()) # strip off the extra newlines print(next(fq).strip()) which gives + '(''%$'))%**)2+'.(&amp;&amp;'/5-
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49040100
upvote count: 3
answers question: http://stackoverflow.com/q/49040100

http://stackoverflow.com/a/49019803
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49016939
has body: There are two problems with your approach. One is related to programming. The gauss fit function has to work with a numpy array. math functions can't provide this functionality, they work with scalars. Therefore your fit functions should look like this def gauss(x, a, x0, sigma): return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) This produces with the right mean/sigma combination a Gauss curve like this And now we look at the distribution of the values from your file: This doesn't even vaguely look like a Gauss curve. No wonder that the fit function doesn't converge. Actually there is a third problem, your calculation of mean/sigma is wrong, but since you can't fit your data to a Gaussian distribution, we can neglect this problem for now.
type: Answer

http://stackoverflow.com/comment/85187740
has text: As a second note, you could even use the fact that a boolean is equivalent with an integer (`True == 1` and `False == 0`). In python 3 and python 2.6 the equivalence is guaranteed. So statements like `a = b > c` are perfectly valid. And also `a += b > c` could be used in your case.
comment on: http://stackoverflow.com/a/49090967
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48971251
has title: Changing the theme of yhat rodeo
upvote count: 3
downvote count: 1
tagged with: ide
tagged with: rodeo
favorite count: 0
tagged with: themes
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
type: Question
has body: I want to change the theme of the yhat rodeo, to a new theme which not in their themes, like Atom theme. Is there any way?

http://stackoverflow.com/a/52909222
type: Answer
has body: you can also check out this solution: def Gbus_Count(): T = int(input()) for i in range(T): if i == 0: N = int(input()) else: input() N = int(input()) A = list(map(int, input().split())) P = int(input()) C = list() D = dict() for k in range(P): C.append(int(input())) for m in range(P): for n in range(N): if A[2*n]&lt;=C[m]&lt;=A[2*n+1]: if C[m] not in D: D[C[m]] = 1 else: D[C[m]] += 1 print("Case #{}: {}".format(i+1, ' '.join(str(x) for x in D.values()))) Gbus_Count()
answers question: http://stackoverflow.com/q/48973195
score: 0

http://stackoverflow.com/comment/85102303
type: Comment
comment on: http://stackoverflow.com/q/49048370
type: QuestionComment
has text: Yes c is a global variable. I know it is undefined in C language but I want to know more about python. So in python it is always left to right which means the interpreter is going to take c as 5 instead of 10 while calculating the expression
score: 0

http://stackoverflow.com/comment/85055177
type: AnswerComment
has text: Even then, researching the state of the art is probably a good idea. Parsing is not a trivial thing.
comment on: http://stackoverflow.com/a/49009633
type: Comment
score: 0

http://stackoverflow.com/comment/86304527
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49016583
has text: @Blender I tried QOS 0 also. Its sending messages only after the loop ends.
score: 0

http://stackoverflow.com/q/48984858
has answer: http://stackoverflow.com/a/78745826
upvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/84975200
type: Question
has title: Fitting exponential decay with scipy negative log likelihood minimization not converging
has answer: http://stackoverflow.com/a/48995607
has body: I'm trying to fit exponential decay functions using negative log likelihood minimization, but even with good starting parameters x0 for the minimizer I can't seem to make this converge. Why? Did I write this up wrong? edited to include conventional binned likelihood aka a "curve" fit import numpy as np from scipy.optimize import minimize, curve_fit import matplotlib.pyplot as plt np.random.seed(1) def exp_fit(x, N, L): return N * np.exp(- L * x) def negloglik(args, func, data): """Negative log likelihood""" return - np.sum(np.log(func(data, *args))) def histpoints_w_err(X, bins): counts, bin_edges = np.histogram(X, bins = bins, normed = False) bin_centers = (bin_edges[1:] + bin_edges[:-1]) / 2 bin_err = np.sqrt(counts) # Generate fitting points x = bin_centers[counts &gt; 0] # filter along counts, to remove any value in the same position as an empty bin y = counts[counts &gt; 0] sy = bin_err[counts &gt; 0] return x, y, sy data = np.random.exponential(0.5, 1000) bins = np.arange(0, 3, 0.1) x, y, sy = histpoints_w_err(data, bins) popt, pcov = curve_fit(exp_fit, x, y, sigma = sy) xpts = np.linspace(0, 3, 100) # All variables must be positive bnds = ((0, None), (0, None)) result = minimize(negloglik, args = (exp_fit, data), x0 = (popt[0], popt[1]), # Give it the parameters of the fit that worked method = "SLSQP", bounds = bnds) jac = result.get("jac") plt.hist(data, bins = bins) plt.plot(xpts, exp_fit(xpts, *popt), label = "Binned fit: {:.2f}exp(-{:.2f}x)".format(*popt)) plt.plot(xpts, exp_fit(xpts, *jac), label = "Unbinned fit: {:.2f}exp(-{:.2f}x)".format(*jac)) plt.text(s = result, x = 0.8, y = popt[0]*0.2) plt.legend() plt.show()
answer count: 3
has comment: http://stackoverflow.com/comment/84982761
linked to: http://stackoverflow.com/q/58751242
downvote count: 0
has answer: http://stackoverflow.com/a/48985302
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84977488
linked to: http://stackoverflow.com/q/14349771
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/85062687
comment on: http://stackoverflow.com/q/49029019
type: Comment
type: QuestionComment
score: 1
has text: numpy.int32 type behaves differently than python int type

http://stackoverflow.com/q/49051111
has answer: http://stackoverflow.com/a/49051181
has comment: http://stackoverflow.com/comment/85108263
has answer: http://stackoverflow.com/a/55396945
has comment: http://stackoverflow.com/comment/85108637
has comment: http://stackoverflow.com/comment/85107682
tagged with: sendkeys
answer count: 3
downvote count: 0
tagged with: wait
has body: I have a question regarding the send_keys function. How can I make the test wait for the entire content of send_keys to be entered? I can not use time.sleep, so I tried: WebDriverWait(self.browser, 5).until( expected_conditions.presence_of_element_located((By.ID, "name"))) query = driver.find_element_by_id('name') query.send_keys('python') driver.find_element_by_id("button").click() the app clicks the button before the action completes send_keys thank you for an answer
favorite count: 0
has comment: http://stackoverflow.com/comment/85108340
type: UnansweredQuestion
has title: python selenium send_keys wait
tagged with: python
upvote count: 6
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/85106719
has answer: http://stackoverflow.com/a/49055232
tagged with: selenium
score: 6
type: Question

http://stackoverflow.com/comment/84986732
has text: Using code to do stuff other than what it was designed for makes your code harder-to-maintain, imho. Also, not everything is about speed.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48990886
score: 0

http://stackoverflow.com/comment/84947245
type: QuestionComment
comment on: http://stackoverflow.com/q/48970752
score: 0
type: Comment
has text: If you only want to do this once (as shown), then your code is pretty good. There's no way to modify a dictionary key in place -- you have to remove the old item and write a new one. If you want to do this for a whole dictionary, you can either scan through all the items and use code like you've shown, or you could construct a new dictionary based on the one you have (often a better choice).

http://stackoverflow.com/q/48999187
accepted answer: http://stackoverflow.com/a/48999414
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: python-requests
has title: How do I run my python file within another python file?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48999414
has answer: http://stackoverflow.com/a/48999248
tagged with: python-2.7
answer count: 2
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/48999248
favorite count: 0
has body: I have the following: # script_1 from ephem import * import time, math, commands, sys, os elements = open('orbital_elements.txt') # Then does some stuff and takes information from the text file, calculating diff_x, diff_y, diff_z return diff_x, diff_y, diff_z I then have a second script. This script imports script_1 as a module and then will loop over a range, each time altering orbital_elements.txt and running script_1 on the new text file to return new values of diff_x, diff_y, diff_z each time: #script_2 from __future__ import division import numpy as np import pandas as pd import os import script_1 df_input = pd.read_csv("sampling.txt", sep = ",", index_col=False) def convert(x): # Input single row of df_input epoch_osculation = '2018 02 22' M = x['M'] AOP = x['AOP'] LOAN = x['LOAN'] INCL = x['INCL'] e = x['e'] a = x['a'] text_file = open("orbital_elements.txt", "w") text_file.write("Object: 1 ceres\n") text_file.write("Epoch of osculation = " + str(epoch_osculation) + "\n") text_file.write("Mean anomaly = " + str(M) + "\n") text_file.write("Argument of perihelion = " + str(AOP) + "\n") text_file.write("Long. of ascending node = " + str(LOAN) + "\n") text_file.write("Inclination = " + str(INCL) + "\n") text_file.write("Eccentricity = " + str(e) + "\n") text_file.write("Semimajor axis = " + str(a)) text_file.close() index = np.arange(len(df_input)) df_output = pd.DataFrame(columns=['x', 'y', 'z'], index = index) for i in range(len(df_input)): # Creates text file for script_2.py convert(df_input.iloc[i]) script_1 # Record data in a table #df_output['x'][i] = script_1.diff_x #df_output['y'][i] = script_1.diff_y #df_output['z'][i] = script_1.diff_z Unfortunately, each time that I run the second script it is returning the same values as if the text file orbital_elements.txt hadn't been altered. I know that the text file is updating each time as I have tested that. The issue seems to lie in script_1 not recognising the updated version of orbital_elements.txt and retur…

http://stackoverflow.com/a/49112662
type: Answer
has comment: http://stackoverflow.com/comment/110464498
score: 37
answers question: http://stackoverflow.com/q/49112365
has comment: http://stackoverflow.com/comment/133687091
has comment: http://stackoverflow.com/comment/110853265
has comment: http://stackoverflow.com/comment/105690394
upvote count: 37
has body: My best guess is that in the settings.py file of your project you have set SECURE_SSL_REDIRECT = True which causes your http to redirect to https. You can read about it here. If that is the case, you might want to remove that line and clear your browser cache before it starts to work as intended.
downvote count: 0

http://stackoverflow.com/a/48965462
has comment: http://stackoverflow.com/comment/84936915
has comment: http://stackoverflow.com/comment/84936809
score: 2
has comment: http://stackoverflow.com/comment/84938470
has comment: http://stackoverflow.com/comment/84939004
has comment: http://stackoverflow.com/comment/84939165
downvote count: 0
has comment: http://stackoverflow.com/comment/84941534
has comment: http://stackoverflow.com/comment/84938903
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84941060
has comment: http://stackoverflow.com/comment/84938993
has comment: http://stackoverflow.com/comment/84937367
has comment: http://stackoverflow.com/comment/84938495
has body: You can use cumcount with set_index + unstack for reshape: g = df.groupby(['customer', 'products']).cumcount() df = ( df.set_index([g, 'customer', 'products'])['Sales'] .unstack().sort_index(level=1) .reset_index(level=0, drop=True) ) print (df) products a b c customer 1 10.0 NaN NaN 1 10.0 NaN NaN 2 NaN 20.0 NaN 3 NaN NaN 30.0 Notice: If duplicated values, maybe need aggregation, check how to pivot a dataframe
answers question: http://stackoverflow.com/q/48965221
has comment: http://stackoverflow.com/comment/84938797

http://stackoverflow.com/comment/84996219
comment on: http://stackoverflow.com/q/48986640
type: Comment
has text: I don't know, I'll check
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85131968
type: AnswerComment
has text: I copied your code verbatim and tried to run it. This is the error that I received: `TypeError: Cannot cast ufunc less input from dtype('<m8[ns]') to dtype('<m8') with casting rule 'same_kind'` Not sure where the <m8 is coming from. I explicitly checked the dtype of each date column and they are all showing `datetime64[ns]`. I am running Pandas 0.19.2 in iPython notebook.
type: Comment
comment on: http://stackoverflow.com/a/49063052
score: 0

http://stackoverflow.com/comment/84975822
score: 0
has text: I can't reproduce this behaviour. Do you want to specify the versions, you use?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48984312

http://stackoverflow.com/comment/85740297
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48967673
has text: can you modify my all questions i am ban to ask question for that i have to correctly format all the question but i am new on stackoverflow so please correct my questions
type: AnswerComment

http://stackoverflow.com/a/48995368
accepted answer of: http://stackoverflow.com/q/48995089
score: 0
type: AcceptedAnswer
has body: I think you can simplify: while True: response=int(raw_input("Enter 1 to see the next record, 2 to see the previous record or 3 to end the program:")) print"" if response &gt; 3: print ("Please respond with one of the set responses.") elif response == 3: break else if response==1: count += 1 if count &gt;= len(plain_text): count = 0 elif response==2: count -= 1 if count &lt; 0: count = len(plain_text) - 1 print("Record {0}:".format(count)) print("Latitude: {0} Longitude: {1} Unencrypted Text: {2} Encrypted Text: {3}".format(latitude[count],longitude[count], plain_text[count], encrypted_text[count]))
type: Answer
answers question: http://stackoverflow.com/q/48995089

graph-theory
tags question: http://stackoverflow.com/q/49095067
tags question: http://stackoverflow.com/q/49073711
tag name: graph-theory
type: Tag

http://stackoverflow.com/q/49033806
favorite count: 0
has title: Debugging Python function (or class) from the command line in Spyder
tagged with: python
upvote count: 4
possible better answer: http://stackoverflow.com/a/56688280
linked to: http://stackoverflow.com/q/419163
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56688280
downvote count: 0
accepted answer: http://stackoverflow.com/a/49034134
has body: I am a new Python user and I have been programming in Matlab, so I decided to use Spyder IDE (which looks pretty much like Matlab IDE). Right now I want to debug through (execute line by line in order to understand) some python code that is written as a class with several built-in functions. So, I inserted a breakpoint at the __init__ function of the class, however, when I started a debugging it did not go to the specified breakpoint (since I have to call for a class initialization, rather than just code execution). Is it possible to start class debugging from the command line? In Matlab I would just call a function from the command line and it would stop at a specified breakpoint. Here I have to start a debugger, rahter than calling a function. If I simply call the following: import energy_model x = energy_model.EnergyModel() It will just execute and ignore my breakpoint. Hope my question is clear. Thanks, Mikhail
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/49034134
score: 4
answer count: 2
tagged with: spyder

http://stackoverflow.com/comment/85182088
has text: df_pred_ult = pd.concat([df_pred_ult,temp], axis=0, ignore_index=True)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49088179
score: 0

http://stackoverflow.com/q/49032296
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49042817
tagged with: python
linked to: http://stackoverflow.com/q/49027906
accepted answer: http://stackoverflow.com/a/49042817
tagged with: bokeh
upvote count: 1
answer count: 1
has body: I have a complex multivariate dataset that is similar in structure to this: import pandas as pd import numpy as np import datetime as dt from itertools import cycle, islice N = 24 start_date = dt.date(2016,1,1) nbdays = int(365 / N) df = pd.DataFrame({'Date': [start_date + dt.timedelta(days=i*nbdays) for i in range(1,N+1)], 'Rating': [(100/N)*i for i in range(1,N+1)], 'Plot': list(islice(cycle(range(1, 9)), 0, N)), 'Treatment': list(islice(cycle(range(1, 7)), 0, N)), 'Trial': list(islice(cycle(range(1, 4)), 0, N)), 'Name': list(islice(cycle("ABCDEF"), 0, N)), 'Target': list(islice(cycle("JKLMNOP"), 0, N)), 'Part': list(islice(cycle("WXYZ"), 0, N)) }) I want: to plot Date versus Rating, colored by Treatment to have an interactive legend, so that clicking on a treatment toggles the visibility of the treatment to have buttons to the side of the plot for the other parameters (Plot, Trial, Name, Target, Part) so that clicking on a button toggles the visibility of corresponding dots to show all the parameters when you hover over a point This is the code that I have (dataset from above in variable df): from bokeh.plotting import figure from bokeh.models import ColumnDataSource from bokeh.palettes import Set1 from bokeh.models import (CDSView, BooleanFilter, Legend, DatetimeTickFormatter, Range1d, HoverTool) from bokeh.models.widgets import CheckboxButtonGroup, Div from bokeh.layouts import widgetbox, layout from bokeh.io import curdoc columns = ['Treatment', 'Plot', 'Trial', 'Name', 'Target', 'Part'] categories = [sorted(df[column].unique()) for column in columns] all_columns = ['Date', 'Rating'] + columns treatment_colormap = dict(zip(categories[0], Set1[6])) # Create Input controls divs = [Div(text=column+':') for column in columns[1:]] controls = [CheckboxButtonGroup(labels=list(map(str, category)), active=list(range(len(category)))) for category in categories[1:]] # Create Column Data Source that will be used by the plot source = ColumnDataSource(data=dict((column, [])…
has title: Interaction between CheckboxButtonGroup and Legend in complex bokeh plot
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/49101915
duplicate of: http://stackoverflow.com/q/19254765
has comment: http://stackoverflow.com/comment/85211354
has title: output doesn't go past enter first number. after I enter the first number (or x) it doesn't go on to the next line
upvote count: 1
has comment: http://stackoverflow.com/comment/85211059
has comment: http://stackoverflow.com/comment/85209016
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85209006
has body: def addNumber(fNum, lNum): sumNum = fNum + lNum return sumNum x = int(input('enter first number \n')) print(x) y = int(input('enter last number \n')) print(addNumber(x,y)) output is enter first number 10 20 no matter what I enter for my output nothing happens doesn't move to the next line of my program
has comment: http://stackoverflow.com/comment/85209093
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85209026
tagged with: sublimetext3
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85290569
linked to: http://stackoverflow.com/q/19254765
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/85209120
has comment: http://stackoverflow.com/comment/85209076
has comment: http://stackoverflow.com/comment/85212001

http://stackoverflow.com/comment/85153785
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49073934
has text: @Narendra This doesn't help. I've scoured the internet, and have seen that multiple times.

http://stackoverflow.com/comment/85237197
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49115809
score: 0
has text: -d is not a default. Directory path i have specified internally. In case they chosen -d to specify custom directory path

http://stackoverflow.com/a/49075464
upvote count: 17
has comment: http://stackoverflow.com/comment/85159644
score: 17
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85160719
has comment: http://stackoverflow.com/comment/85256768
answers question: http://stackoverflow.com/q/49075166
has body: It may be helpful to follow a tutorial on how to use pandas: df.columns is not callable, you cannot df.columns() it, hence TypeError: 'Index' object is not callable. type(df.'state'[0]) is not how you get a column in pandas, they are not attributes of the dataframe and you can't use strings as attribute names, hence the SyntaxError: df['state'][0] is how you would get the first item in the 'state' column.
accepted answer of: http://stackoverflow.com/q/49075166
type: Answer

http://stackoverflow.com/a/49019146
has comment: http://stackoverflow.com/comment/85083623
has comment: http://stackoverflow.com/comment/85072575
has comment: http://stackoverflow.com/comment/85083478
has comment: http://stackoverflow.com/comment/85073052
has comment: http://stackoverflow.com/comment/85082848
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85072251
has comment: http://stackoverflow.com/comment/85079250
score: 0
has body: While I know nothing of DynamoDB, your Python code should only pass one i and j value as your dynamo.put_item block of code is not nested in either of the for loops and hence takes their last assigned values. Simply run your image_id and risk_score search together in one loop which can be nested at the &lt;HOST&gt; level. And consider xpath(), available in lxml. And no need for the import lxml call as you import its method etree instead. doc = etree.fromstring(body) # PARSE ONLY ONCE hosts = doc.xpath('//HOST') for h in hosts: i = h.xpath('EC2_INFO/IMAGE_ID')[0].text print(i) j = h.xpath('VULN_INFO_LIST/VULN_INFO/CVSS_FINAL')[0].text print(j) response = dynamo.put_item( TableName='ExistingAMI', Item={ 'AMI_ID': { 'S': i }, 'CVSS_SCORE': { 'S': j }, } ) WriteItemToTable() # ami-xxxxxx # 3.5 # ami-yyyyyy # 3.6 For multiple CVSS_FINAL, use XPath to parse down to the &lt;CSVSS_FINAL&gt; then retrieve corresponding IMAGE_ID with ancestor::* cvss = obj.xpath('//CVSS_FINAL') # ALL CVSS_FINAL NODES for c in cvss: i = c.xpath('ancestor::HOST/EC2_INFO/IMAGE_ID')[0].text print(i) j = c.text print(j) k = c.xpath('concat(following-sibling::RESULT, "")') print(k) response = dynamo.put_item( ... ) # ami-xxxxxx # 3.5 # TLSv1.0 is supported # ami-xxxxxx # 2.1 # # ami-xxxxxx # 4.3 # TLSv1.0 is supported # ami-yyyyyy # 3.6 #
accepted answer of: http://stackoverflow.com/q/49012822
type: Answer
has comment: http://stackoverflow.com/comment/85078635
answers question: http://stackoverflow.com/q/49012822

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/49119044

http://stackoverflow.com/q/49014947
has comment: http://stackoverflow.com/comment/85035377
has comment: http://stackoverflow.com/comment/85035090
has answer: http://stackoverflow.com/a/49015145
has comment: http://stackoverflow.com/comment/85034888
has comment: http://stackoverflow.com/comment/85035020
has body: I have a simple python GUI that fills in a grid based on the values in an array, and I want this simple GUI to sit on screen while other functions run. The time for these other functions is indeterminate, so I can't simply call them at some regular interval using after(time, function) def go(self): """ Start the main GUI loop :return: """ mainloop() The mainloop starts in the go function, and I want to know if it is possible to either break out of mainloop without closing the window or to draw the GUI without calling mainloop at all? I know I can do after(time, function) but I'm at a loss as to what to call to kill the mainloop while keeping the GUI on-screen.
has comment: http://stackoverflow.com/comment/85035188
tagged with: python
has answer: http://stackoverflow.com/a/49015176
has comment: http://stackoverflow.com/comment/85035863
has answer: http://stackoverflow.com/a/49015357
has comment: http://stackoverflow.com/comment/85036344
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85034920
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85036100
has comment: http://stackoverflow.com/comment/85039382
has comment: http://stackoverflow.com/comment/85035295
has comment: http://stackoverflow.com/comment/85035399
has comment: http://stackoverflow.com/comment/85035473
has comment: http://stackoverflow.com/comment/85035519
has comment: http://stackoverflow.com/comment/85035145
has comment: http://stackoverflow.com/comment/85035667
has title: how to break out of mainloop() without closing the gui
type: Question
score: 0
answer count: 3

http://stackoverflow.com/comment/85029314
comment on: http://stackoverflow.com/q/49011601
has text: It's because you never cancel any pending "after" jobs, you just keep adding more.
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/49065038
type: Question
tagged with: filesystems
has answer: http://stackoverflow.com/a/49065643
possible better answer: http://stackoverflow.com/a/67940979
tagged with: python-2.7
answer count: 2
upvote count: 1
has body: I have written the following script that allows me to compress a src (which can be either a single file or a directory) to target 'dst': #!/usr/bin/env python2 import tarfile from ntpath import basename, dirname from os import path, listdir, makedirs, chdir import errno import sys class Archivator: @staticmethod def compress(src='input/test', dst='output'): # if not path.isfile(src_file): # print('Expecting absolute path to file (not directory) as "src". If "src" does contain a file, the file does not exist') # return False if not path.isdir(dst): return False # try: # makedirs(dst_dir) # except OSError as err: # if err.errno != errno.EEXIST: # return False filename = basename(src) if path.isdir(src) else src tar_file = dst + '/' + filename + '.tar.gz' print(tar_file) print(src) with tarfile.open(tar_file, 'w:gz') as tar: print('Creating archive "' + tar_file + '"') # chdir(dirname(dst_dir)) recr = path.isdir(src) if recr: print('Source is a directory. Will compress all contents using recursion') tar.add(src, recursive=recr) return True if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Uses tar to compress file') parser.add_argument('-src', '--source', type=str, help='Absolute path to file (not directory) that will be compressed') parser.add_argument('-dst', '--destination', type=str, default='output/', help='Path to output directory. Create archive inside the directory will have the same name as value of "--src" argument') # Generate configuration config = parser.parse_args() Archivator.compress(config.source, config.destination) For single files I haven't had an issue so far. However while the compression of src (as a directory) does worked (recursion and all) I have noticed a very annoying issue namely that the complete directory structure is replicated inside the tar.gz archive. Example: Let's say I have the following file structure: ./ |---compression.py (script above) | |---updates/ | | | |---package1/ | | | |---file1 | |…
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/67940979
type: AnsweredQuestion
has title: Compressing only the files inside a given directory using tarfile (Python)
downvote count: 0
score: 1
tagged with: compression
tagged with: http://stackoverflow.com/tag/tar
accepted answer: http://stackoverflow.com/a/49065643

http://stackoverflow.com/a/49073929
downvote count: 0
answers question: http://stackoverflow.com/q/49073656
upvote count: 2
type: Answer
has body: You can use idxmin() df.iloc[df.groupby('SourceID')['Distance'].idxmin(), :] Index SourceID ComparedID Distance 1 572 106 11 0.0000 3 574 107 84 0.0028
score: 2

http://stackoverflow.com/q/49089555
has answer: http://stackoverflow.com/a/49089575
favorite count: 0
has answer: http://stackoverflow.com/a/49089595
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I'm currently stuck in this right now. I have a code right here: words = ["Hello","how","are","you"] arrlen = len(words) val1, val2, val3, val4 = words What I want to do is add ".mp4" in each val1, val2, val3 and val4. Is there any way to achieve this? I have tried val1 + ".mp4", but it does not work.
has title: Python - Adding a string in a data from a list
type: Question
accepted answer: http://stackoverflow.com/a/49089573
answer count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/49089575
has answer: http://stackoverflow.com/a/49089573

http://stackoverflow.com/comment/85211268
type: Comment
has text: Thanks for clarifying- I added some sample data. When I tried that code it gave me 'IndexError: single positional indexer is out-of-bounds', maybe because it's going through the whole set and it gets messed up at the end? should I do a try and except continue?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49091458

http://stackoverflow.com/comment/92311668
has text: @PatrickHaugh I tried same like yours with with some changes `if message.content.startswith("!ping"):` but it adds reaction for our message `!ping` not for bots message.
type: AnswerComment
comment on: http://stackoverflow.com/a/48982339
score: 0
type: Comment

http://stackoverflow.com/comment/85043941
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49019245
has text: [This post](https://stackoverflow.com/questions/43556344/pandas-monthly-rolling-operation) illustrates how resample is able to use calendar months, but "rolling", with min_periods option, cannot.
score: 0

http://stackoverflow.com/q/49114633
upvote count: 3
has answer: http://stackoverflow.com/a/49114702
accepted answer: http://stackoverflow.com/a/49114702
possible better answer: http://stackoverflow.com/a/49114678
tagged with: python
has title: Cycle through iterable and keep only relevant elements
has comment: http://stackoverflow.com/comment/85235195
has comment: http://stackoverflow.com/comment/85234534
has comment: http://stackoverflow.com/comment/85235230
has comment: http://stackoverflow.com/comment/85235066
downvote count: 0
answer count: 5
has body: Background: I have the following for python 3 data = [{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}, {'name': 'Jim','id_str': '03'}] id = ['01','1133', '02', '2222'] Goal: Keep data when id == id_str and append to a list. The code below appends the first data point [{'id_str': '01', 'name': 'Jon'}] (which is what I want) id_list = [] for d in range(len(data)): t = data[d] id_str = t['id_str'] if id_str == id[d]: keep = data[d] id_list.append(keep) Problem: Now I want to move onto the next id in the list '1133'. But since the second id value '1133' does not equal the id_str for the second value in data ({'name': 'Tom','id_str': '02'}, I want it to skip this and move on to the third value in id which is '02'. Since id ('02') is equal to id_str ({'name': 'Tom','id_str': '02'}) I want to append. I want to continue this process and cycle until all of the id = ['01','1133', '02', '2222'] are checked. This website http://love-python.blogspot.com/2012/03/get-next-element-from-list-in-python.html. suggests that I should add a counter at some point, along with if-else statements but I've tried many times and I'm not sure how. I would guess my final code would look something like the following id_list = [] for d in range(len(data)): t = data[d] id_str = t['id_str'] if id_str == id[d]: keep = data[d] id_list.append(keep) elif id_str != id_list[d]: skip check next id else: if no more id to check break Desired final output: [{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}] Question: How do I accomplish these goals: 1) keep and append desired data (when id == id_str) 2) skip unwanted data (when id != id_str) 3) break when finished cycling through id (that is, once all of the elements in id = ['01','1133', '02', '2222'] are indexed and compared to all id_str in data)
type: Question
type: AnsweredQuestion
score: 3
tagged with: if-statement
has answer: http://stackoverflow.com/a/49114678
has comment: http://stackoverflow.com/comment/85234460
tagged with: for-loop
has answer: http://stackoverflow.com/a/49114771
has answer: http://stackoverflow.com/a/49115010
has answer: http://stackoverflow.com/a/49114888
has comment: http://stackoverflow.com/comment/85235596
has comment: http://stackoverflow.com/comment/85235334
favorite count: 0
has comment: http://stackoverflow.com/comment/85234559

http://stackoverflow.com/comment/85030367
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49012761
has text: _"But, I would like to do the former."_ Why? What's wrong with the import statement?

http://stackoverflow.com/comment/84963378
type: AnswerComment
has text: I don't know if it's works but look there : https://stackoverflow.com/questions/42047253/how-to-detect-current-keyboard-language-in-python
type: Comment
comment on: http://stackoverflow.com/a/48978942
score: 1

http://stackoverflow.com/a/64719095
answers question: http://stackoverflow.com/q/49063058
type: Answer
has body: I had the same error when using PyCharm and executing code in the Python Console in Windows 10, however, I was able to run this same code without error when launching pyspark from the terminal. After trying solutions from many searches, the solution for the Pycharm Python Console error was a combination of all of the environment variable (I set them up for both User and System) and PyCharm setting steps in the following two blog posts, setup pyspark locally and spark &amp; pycharm.
score: 0

http://stackoverflow.com/a/49026615
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49025562
upvote count: 3
answers question: http://stackoverflow.com/q/49025562
type: Answer
has body: Try this: root = open('/your/path_to_file/data.xml', 'rb+') doc = ET.parse(root).getroot() valuelist = [] for i in doc.findall('.//bin'): val = i.findall('value') for v in val: valuelist.append(v.text) print valuelist Output: ['"Envelopes"', '"Labels"', '"Pens &amp; Art Supplies"', '"Rubber Bands"', '"Scissors, Rulers and Trimmers"'] [Finished in 0.0s]
downvote count: 0
score: 3

http://stackoverflow.com/a/49100104
has body: You can insert multiple pdb.set_trace() inside your code. They will break the code while you run it. the first one launches pdb.
type: Answer
answers question: http://stackoverflow.com/q/49099824
score: 0

http://stackoverflow.com/q/48984948
type: Question
has answer: http://stackoverflow.com/a/48985081
tagged with: dataframe
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48985081
has title: Search for repeated strings corresponding to a values across multiple columns in python(preferably with pandas dataframe)
tagged with: python
possible better answer: http://stackoverflow.com/a/48989094
type: AnsweredQuestion
has body: I have a dataset of three columns which looks something like this: X1 X5 X1 X2 X9 X2 X3 X3 X5 X4 X8 X3 X5 X1 X4 I want to search for the variable which is present in all the columns. In this case, the output would be, X1 X3 X5 Can someone please help doing this in python?
has answer: http://stackoverflow.com/a/48989094
score: 1
upvote count: 1

http://stackoverflow.com/comment/85062562
type: QuestionComment
has text: @Ev.Kounis I tried with various negative numbers and fractions, the result was always `nan` if the fraction doesn't round.
score: 0
comment on: http://stackoverflow.com/q/49029019
type: Comment

http://stackoverflow.com/a/49039670
has body: For me it has nothing to do with python or HTTP requests. The site whiteboard.cactusglobal is not an API, it is a website. It is not meant to able you to access its page only programatically. It expects a real user that interacts with it thanks to its browser. So for me, the tool that you need is Selenium. Or any User Testing Automation tool, really. That kind of tools will let you emulate a browser that goes to the website, is redirected to the log page, and enter the authentification information in the relevant fields, all within Python. As your use-case is basic, if you understand the basic tutorials, in particular how to fill forms, you will easily find your way :)
type: Answer
accepted answer of: http://stackoverflow.com/q/49039241
answers question: http://stackoverflow.com/q/49039241
has comment: http://stackoverflow.com/comment/85086010
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/128110741

http://stackoverflow.com/q/49039153
has title: pandas merge_asof keys must be sorted error after sorting
downvote count: 0
has answer: http://stackoverflow.com/a/56722438
tagged with: pandas
has answer: http://stackoverflow.com/a/49051591
possible better answer: http://stackoverflow.com/a/56722438
favorite count: 0
has comment: http://stackoverflow.com/comment/85107539
accepted answer: http://stackoverflow.com/a/49051591
has comment: http://stackoverflow.com/comment/85084067
tagged with: python
tagged with: merge
type: AnsweredQuestion
has body: I would like to merge a target column from one data frame to another. The merged data frame has many more keys and they are are close, but do not exactly match the original data frame. See an example below: Original data frame (FDMA) DMA 130506 130510 130512 130555 130556 Merged data frame (ZC) DMA Distance (Miles) 1305060 303.87 1305061 305.35 1305062 278.80 1305065 299.94 1305067 291.83 pd.merge_asof(FDMA,ZC'DMA','Distance (Miles)',on='DMA') This is what I am expecting DMA Distance (Miles) 130506 303.87 130510 291.83 130512 XXX 130555 XXX 130556 XXX I have tried the above code and get a ValueError: right keys must be sorted error. I have sorted the values and reset the indexes, but still get the error. Any help is appreciated!
has comment: http://stackoverflow.com/comment/85107454
type: Question
score: 12
answer count: 2
upvote count: 12

http://stackoverflow.com/q/49105343
upvote count: 2
accepted answer: http://stackoverflow.com/a/49105470
has answer: http://stackoverflow.com/a/49106583
type: Question
possible better answer: http://stackoverflow.com/a/49105497
has body: is there a way in Pandas data frame where I can extract words from a column of strings that are only of length of 2 characters? For example: Singapore SG Jalan ID Indonesia Malaysia MY And the results will be SG ID MY
has answer: http://stackoverflow.com/a/49105497
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49105470
linked to: http://stackoverflow.com/q/29689516
favorite count: 0
has answer: http://stackoverflow.com/a/49105516
tagged with: python
answer count: 4
has title: Only extract words with 2 characters Pandas Series
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/49058266
has title: How to solve an inseparable equation when you cannot get the variable you're solving for onto one side? (Python)
has body: Have an equation where I cannot get the variable I want to solve for onto only one side. I want to solve for that variable for given values of all the other variables in the equation. For a simple example as clarification, suppose you couldn't get x onto only one side of the following equation even though you can: sqrt(x)=(a/13)*log(b/x^2) Since you can't get it onto one side, you can't define x as an expression - how would you solve for x (with given values of a and b) when x is an undefined variable?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85121882
answer count: 2
has answer: http://stackoverflow.com/a/49058548
has comment: http://stackoverflow.com/comment/85121746
has comment: http://stackoverflow.com/comment/85121831
has answer: http://stackoverflow.com/a/49058591
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85121933

http://stackoverflow.com/a/49060836
has body: Don't use a custom class for it. Use the stdlib's enum type, they'll do the right thing here. from enum import Enum class Insect(Enum): ... If you want a hard crash: class MyEnum(Enum): def __eq__(self, other): if type(other) is not type(self): raise Exception("Don't do that") return super().__eq__(other) But I caution against this design, since: enum instances are often compared by identity and not equality there is little (no?) precedent in Python for equality comparisons raising errors
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/49060812
accepted answer of: http://stackoverflow.com/q/49060812
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85127141
has comment: http://stackoverflow.com/comment/85126896
has comment: http://stackoverflow.com/comment/85126811
type: Answer

http://stackoverflow.com/a/49089540
score: 1
answers question: http://stackoverflow.com/q/49087311
upvote count: 1
type: Answer
downvote count: 0
has body: Benchmarking different solutions, using lists of length 10000 similar to the shown ones and searching all existing pairs, using Python 2.7.14: 2.380 seconds rajat # The original 1.712 seconds rajat2 # Precomputed range 1.843 seconds rajat3 # xrange instead of range 5.243 seconds stefan1 # zip(a, b).index 0.954 seconds stefan1b # Precomputed zip(a, b).index 16.108 seconds stefan2 # dict 0.002 seconds stefan2b # Precomputed dict 10.782 seconds chris # next(generator) 6.728 seconds chris2 # bit optimized 1.754 seconds chris3 # Precomputed zip(a, b, c) The code: from timeit import timeit b = range(100) * 100 a = sorted(b) c = range(10000) #------------------------------------------------------------------------- def rajat(A, B): 'The original' for i in range(0, len(a)): if a[i] == A and b[i] == B: return c[i] def rajat2(A, B, r=range(0, len(a))): ' Precomputed range' for i in r: if a[i] == A and b[i] == B: return c[i] def rajat3(A, B): ' xrange instead of range' for i in xrange(0, len(a)): if a[i] == A and b[i] == B: return c[i] def stefan1(A, B): 'zip(a, b).index' return c[zip(a, b).index((A, B))] def stefan1b(A, B, index=zip(a, b).index): ' Precomputed zip(a, b).index' return c[index((A, B))] def stefan2(A, B): 'dict' return dict(zip(zip(a, b), c))[A, B] def stefan2b(A, B, d=dict(zip(zip(a, b), c))): ' Precomputed dict' return d[A, B] def chris(A, B): 'next(generator)' return next((z for x, y, z in zip(a, b, c) if (x, y) == (A, B)), 'None found') def chris2(A, B): ' bit optimized' return next((z for x, y, z in zip(a, b, c) if x == A and y == B), 'None found') def chris3(A, B, abc=zip(a, b, c)): ' Precomputed zip(a, b, c)' return next((z for x, y, z in abc if x == A and y == B), 'None found') #------------------------------------------------------------------------- ab = zip(a, b) def test(): for A, B in ab: func(A, B) for func in rajat, rajat2, rajat3, stefan1, stefan1b, stefan2, stefan2b, chris, chris2, chris3: t = timeit(test, number=1) print '%6.3f seconds %-10s # …

http://stackoverflow.com/a/49022565
score: -1
upvote count: 0
has body: You can try to change your last line of code: From : print (fullpath) To: print (fullpath[:-4])
type: Answer
answers question: http://stackoverflow.com/q/49022538
downvote count: 1

http://stackoverflow.com/comment/85115000
type: Comment
type: QuestionComment
has text: If you want to restrict who can access `a`, you can re-structure your code thinking about the scope of each variable/function... or you can use a hack. If you decide to restructure, you can limit the scope by using modules/class or namespace. For this simple example, namespace will do the trick.
score: 0
comment on: http://stackoverflow.com/q/49054993

http://stackoverflow.com/a/48986582
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48985722
has body: To check if there are attachments to an e-mail you can search the headers for Content-Type and see if it says "multipart/*". E-mails with multipart content types may contain attachments. To inspect the text for links, images, etc, you can try using Regular Expressions. As a matter of fact, this is probably your best option in my opinion. With regex (or Regular Expressions) you can find strings that match a given pattern. The pattern "<a[^>]+href=\"(.*?)\"[^>]*>(.*)?", for example, should match all links in your email message regardless of whether they are a single word or a full URL. I hope that helps! Here's an example of how you can implement this in Python: import re text = "This is your e-mail body. It contains a link to Google." link_pattern = re.compile('<a[^>]+href=\'(.*?)\'[^>]*>(.*)?') search = link_pattern.search(text) if search is not None: print("Link found! -> " + search.group(0)) else: print("No links were found.") For the "end-user" the link will just appear as "Google", without www and much less http(s)... However, the source code will have the html wrapping it, so by inspecting the raw body of the message you can find all links. My code is not perfect but I hope it gives you a general direction... You can have multiple patterns looked up in your e-mail body text, for image occurences, videos, etc. To learn Regular Expressions you'll need to research a little, here's another link, to Wikipedia
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48985722
score: 3
has comment: http://stackoverflow.com/comment/85081364
upvote count: 3
has comment: http://stackoverflow.com/comment/85061023

http://stackoverflow.com/comment/85278701
type: AnswerComment
score: 0
type: Comment
has text: The optimizers are receiving a list of `(variable, gradient)` pairs. So I know there's no way in the optimizer interface to do that, short of re-coding each optimizer for specific support.
comment on: http://stackoverflow.com/a/49136724

marker
tag name: marker
tags question: http://stackoverflow.com/q/49051124
tags question: http://stackoverflow.com/q/49070800
tags question: http://stackoverflow.com/q/48973335
type: Tag

http://stackoverflow.com/a/49012639
score: 3
upvote count: 3
has body: The reason it doesn't add up is because you have two occasions which should add a negative amount of letters because the value is lower than the previous number: (69, 'not-MIT') (68, 'not-MIT') (76, 'not-MIT') (71, 'not-MIT') For future reference: it's better not to call your variables 'str' as 'str()' already is a defined function in python.
answers question: http://stackoverflow.com/q/49012114
has comment: http://stackoverflow.com/comment/85030725
downvote count: 0
has comment: http://stackoverflow.com/comment/85030588
type: Answer

http://stackoverflow.com/comment/85366208
type: AnswerComment
has text: Yes, that is exactly what my problem was. I knew I had to be overlooking something that should be obvious. Thank you very much for the second set of eyes.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49091924

http://stackoverflow.com/a/50338808
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49029873
answers question: http://stackoverflow.com/q/49029873
has body: import os file_list = os.listdir(r"C:\Users\ساشلاشى\Desktop\game") save_ = os.getcwd() os.chdir("C:\Users\ساشلاشى\Desktop\game") for file_name in file_list: print("old name = "+file_name) print("new name = "+file_name.translate(None,"0123456789")) os.rename(file_name,file_name.translate(None,"0123456789")) os.chdir(save_)

http://stackoverflow.com/comment/85209034
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49101761
has text: What is your .kv name?
score: 0

http://stackoverflow.com/q/49047318
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/102510504
has comment: http://stackoverflow.com/comment/102460226
type: Question
has title: PermissionError: [Errno 13] Permission denied: 'desktop.ini'
downvote count: 0
tagged with: python
favorite count: 0
has body: import os, subprocess, configparser # Search for folder! # First locate the directory root_dir = input("Enter the root directory you wanna enter:") try: os.chdir(root_dir) except FileNotFoundError: print("ERROR:Directory not found") exit(505) # second locate the folder now! folder_name = input("Enter the name of folder you wanna hide:") # Hiding part starts now! # check the entered information # Start by checking if the folder is present in the directory check_dir = os.listdir(root_dir) print(check_dir) if folder_name in check_dir: # If the folder is present lets hide it! # step 1: Give a hidden name(No-Break space) by pressing alt + 0160 folder = ' ' os.rename(folder_name, folder) # step 2: Enter the properties of this folder # first change the folder to read only using cmd subprocess.call('cd' + " " + root_dir, shell=True) cmd_command = "attrib +s" + " " + folder returned = subprocess.call(cmd_command, shell=True) print("Shell returned", returned) # second change the folder icon with desktop.ini and configParser config = configparser.RawConfigParser() config['.ShellClassInfo'] = { 'ConfirmFileOp': '0', 'NoSharing': '1', 'IconFile': 'Folder.ico', 'IconIndex': '0', 'InfoTip': 'This is folder man' } with open("desktop.ini", "wt") as configFile: config.write(configFile) else: print("ERROR: folder not present!!!") # Check At the end for success print(os.listdir(root_dir)) I am currently trying to create a program that hides folders but for some reason, I am getting this error: with open("desktop.ini", "wt") as configFile: PermissionError: [Errno 13] Permission denied: 'desktop.ini' help!!!
score: 2
tagged with: python-3.x
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/84983330
has text: I'm afraid you do not understand correctly. Please read the FineManual (the official doc I mean, not "some book") to understand what `commit=False` means and why it's used in your first snippet.
type: Comment
comment on: http://stackoverflow.com/a/48988360
score: 0
type: AnswerComment

http://stackoverflow.com/q/49077405
tagged with: python
possible better answer: http://stackoverflow.com/a/49077813
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85161179
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/49077455
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49077813
has answer: http://stackoverflow.com/a/49077455
has body: I have this data frame: import pandas as pd import numpy as np df = pd.DataFrame({ 'CITY' : np.random.choice(['PHOENIX','ATLANTA','CHICAGO', 'MIAMI', 'DENVER'], 1000), 'DAY': np.random.choice(['Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 1000), 'LOCATION' : np.random.choice(['Location1','Location2','Location3', 'Location4', 'Location5'], 1000), 'COUNT': np.random.randint(1, 700, size=1000)}) print(df) CITY COUNT DAY LOCATION 0 DENVER 521 Wednesday Location4 1 MIAMI 123 Saturday Location3 2 ATLANTA 122 Wednesday Location3 3 DENVER 363 Saturday Location1 4 PHOENIX 656 Saturday Location4 5 PHOENIX 369 Saturday Location3 6 MIAMI 455 Tuesday Location5 How do I divide the count column by a list of integers based on location such as if location1 then divide COUNT by 13 if location2 then divide COUNT by 85 if location3 then divide COUNT by 42 if locationx then divide COUNT by intx...
has title: How to divide pandas column by list of integers based on row value
tagged with: pandas
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/48976906
type: Answer
has body: As stated in the comments by Haleemur Ali, this data is a properly formatted JSON. He pointed me in the right direction by suggesting I handle it as one. Using the following function will convert the string to a JSON object, which can be handled much more easily. logJSON = json.loads(inputstring) I used the following video to familiarize myself with JSON handling in Python prior to reading the documentation: https://www.youtube.com/watch?v=9N6a-VLBa2I
has comment: http://stackoverflow.com/comment/84960077
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48976751
score: 1
answers question: http://stackoverflow.com/q/48976751
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84959084

http://stackoverflow.com/comment/85047157
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49019716
has text: @sm544 how big of a read are we talking about, i.e. what's `min(start)` and `max(stop)`? Probably best way to do it is to just fill a list from 1 - 0 with the row indices and sample from that list

http://stackoverflow.com/a/49063790
has body: To make this code work, you can remove the line that says: import error And on the line that says: if f1*f2 &gt; 0.0: error.err('Root is not bracketed') Change that to: if f1*f2 &gt; 0.0: quit('Root is not bracketed')
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49063730
type: Answer
answers question: http://stackoverflow.com/q/49063730

http://stackoverflow.com/comment/85127264
comment on: http://stackoverflow.com/q/49061099
score: 0
type: Comment
type: QuestionComment
has text: tokens=re.findall(r'[^\-\_][a-zA-Z]+|[a-zA-Z]+-+_[a-zA-Z]', newtext)

http://stackoverflow.com/comment/85154733
has text: ["Can Someone Help Me?" is not a valid SO question](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). This usually suggests that what you need is half an hour with a local tutor or walk through a tutorial, rather than Stack Overflow.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49074095
type: QuestionComment

http://stackoverflow.com/comment/85127100
score: 0
comment on: http://stackoverflow.com/q/49060908
type: Comment
type: QuestionComment
has text: thanks - I was looking for an example of your suggested method, but I think I can get it. Cheers!

http://stackoverflow.com/q/49020495
has title: Is it reliable and documented how PYTHONPATH populates the sys.path?
favorite count: 0
score: 12
accepted answer: http://stackoverflow.com/a/49020847
tagged with: python
has comment: http://stackoverflow.com/comment/85046309
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85046624
has comment: http://stackoverflow.com/comment/85046391
has body: On my machine, the values from PYTHONPATH appear to get inserted in sys.path: beginning at index 1 order preserved de-duplicated For example, with PYTHONPATH=/spam:/eggs:/spam and then checking in python -m site, I get a result like: sys.path = [ something, '/spam', '/eggs', more, stuff, after ] It seems to be the same behaviour on Python 2 and Python 3. The question is, how much of this handling of PYTHONPATH is documented / reliable, and what if any might be different on other platforms? Is this baked into the interpreter, or is handled by site.py and/or in danger of being "tweaked" by sysadmins? I can't see it explained in the documentation here, it just says sys.path is "augmented" (and, contrary to the documentation, non-existent directories do not appear to be silently ignored).
type: Question
has comment: http://stackoverflow.com/comment/85046281
tagged with: python-import
upvote count: 12
has answer: http://stackoverflow.com/a/49020847
tagged with: environment-variables
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/85060233
type: Comment
type: QuestionComment
score: 0
has text: Thanks, I shall have another look at pandas and report back if this module is useful.
comment on: http://stackoverflow.com/q/49026919

http://stackoverflow.com/a/49114278
has body: Even though Age is intended to be a numeric value, xml attribute values should be quoted strings: person = ElementTree.Element("Person", Name="John", Age="18") Alternatively, if the data was stored as a variable, convert it to a string with str() age = 18 person = ElementTree.Element("Person", Name="John", Age=str(age))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49114087
score: 8
answers question: http://stackoverflow.com/q/49114087
type: Answer
downvote count: 0
upvote count: 8

http://stackoverflow.com/comment/85192588
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49092630
has text: @talonmies: what makes you think that? I've just tested and the above code also fails if I use int32 instead.
score: 0

http://stackoverflow.com/comment/85178945
score: 1
has text: StackOverflow is not a coding service.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49086789

http://stackoverflow.com/comment/85086310
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49040208
has text: what do you mean by that? plotted?
type: Comment

http://stackoverflow.com/q/49019383
tagged with: keras
has comment: http://stackoverflow.com/comment/85092045
tagged with: python
type: AnsweredQuestion
has title: Keras - Precision and Recall is greater than 1 (Multi classification)
tagged with: classification
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49085100
type: Question
has body: I am working on a multi classification problem using CNN's in keras. My precision and recall score is always over 1 which does not make any sense at all. Attached below is my code, what am I doing wrong? def recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy',recall,precision])
score: 0
has comment: http://stackoverflow.com/comment/85100732
accepted answer: http://stackoverflow.com/a/49085100
answer count: 1
tagged with: precision-recall

http://stackoverflow.com/comment/84965649
type: Comment
type: QuestionComment
has text: @Nick.McDermaid - I can INSERT a DATETIME value with sub-second precision, retrieve the value using ADODB, and confirm that the sub-second precision is preserved. However, if I try to round-trip the value by passing that same object back in as a parameter value for a subsequent insert, the sub-second precision is silently discarded. So we're back to the original question: is the failure of ADODB to conform to the documentation (preserving the accuracy of the value passed as a parameter) a known bug?
score: 0
comment on: http://stackoverflow.com/q/48969397

http://stackoverflow.com/a/49112113
has body: Kinda made it work with .filter(SomeClass.some_json_column["key_that_contains_list_value"][0].has_key('inner_dict_key')) because in my case list always contains at least one entry, but as you can imagine it does not give all the answers. It is quite ok for my testing purposes for now. Although I would really like to know if somebody got better answer.
type: Answer
answers question: http://stackoverflow.com/q/49110660
score: 0

influxdb-python
tags question: http://stackoverflow.com/q/48995936
tag name: influxdb-python
type: Tag

http://stackoverflow.com/q/49106732
has answer: http://stackoverflow.com/a/49106844
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49107146
type: AnsweredQuestion
score: -1
favorite count: 0
type: Question
answer count: 2
tagged with: python
linked to: http://stackoverflow.com/q/20109391
downvote count: 1
has title: how do i load csv into array?
has body: I am using pandas to load csv files containing questions/answers and assigning them to dict. kids_csv_file = pd.read_csv(...) #columns Questions, SubQuestions, Answers questions_dict = dict() for i in ... : _key = kids_csv_file.Questions[i] + '-' + kids_csv_file.SubQuestion[i] questions_dict[_key] = kids_csv_file.Answers[i]; I am getting: TypeError: must be str, not numpy.int64
accepted answer: http://stackoverflow.com/a/49107146
upvote count: 0
possible better answer: http://stackoverflow.com/a/49106844
has comment: http://stackoverflow.com/comment/85218407

http://stackoverflow.com/q/49024459
has comment: http://stackoverflow.com/comment/85056763
accepted answer: http://stackoverflow.com/a/49031320
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85054195
has comment: http://stackoverflow.com/comment/85054173
tagged with: python
tagged with: python-3.x
tagged with: sha256
has answer: http://stackoverflow.com/a/49031320
upvote count: 1
has comment: http://stackoverflow.com/comment/85066901
linked to: http://stackoverflow.com/q/34771268
type: AnsweredQuestion
has body: I have a csv file with 1000+ emailadreses which I want to hash using a SHA256 HMAC and a shared key, encoded to Base64. There was a similiar problem here, but I can't adapt the solution to work for me. I am new to python and I don't know where to change the code in order to make use of the shared key. This is the slightly adapted code from the answer: import csv import hashlib import hmac import base64 IN_PATH = 'test.csv' OUT_PATH = 'test_hashed.csv' ENCODING = 'utf8' HASH_COLUMNS = dict(Mail='md5') def main(): with open(IN_PATH, 'rt', encoding=ENCODING, newline='') as in_file, \ open(OUT_PATH, 'wt', encoding=ENCODING, newline='') as out_file: reader = csv.DictReader(in_file) writer = csv.DictWriter(out_file, reader.fieldnames) writer.writeheader() for row in reader: for column, method in HASH_COLUMNS.items(): data = row[column].encode(ENCODING) digest = hashlib.new(method, data).hexdigest() row[column] = '0x' + digest.upper() writer.writerow(row) if __name__ == '__main__': main() The input file (.csv) looks like this: Mail DHSKA@gmail.com DJÖANw12@gmail.com JSNÖS83@ymail.com HDKDLSA@gmail.com KKKDLAmS19@yamil.com And with the code above, the output file looks like this: 0xB6A77B6EB853CC4CC8342B312293FA9C 0xEB439592D8EEC2A38A597350EF80E512 0x833EB6AEC1D03D7D8C94606E0D749B80 0x8007D8D1702E8A749EBD6033A52A7897 0x415E067487C4A5FBDB86AB0F855DB114 But since I do want to use a HMAC with secret key and sha256, the above solution doesn't work for me and I don't know how to incorporate this approach. The key would be something like this: 123Abc I was trying to do something like this, but for the whole file: import hmac import hashlib import base64 secret = "123Abc" secret_bytes = bytes(secret, 'latin-1') data = "DHSKA@gmail.com" data_bytes = bytes(data, 'latin-1') digest = hmac.new(secret_bytes, msg=data_bytes, digestmod=hashlib.sha256).digest() signature = base64.b64encode(digest).decode() Thus, my question is how I can incorporate the HMAC SHA 256 hashing wile using the a…
has title: Hashing a csv file in python with a key
score: 1
tagged with: hmac
type: Question

http://stackoverflow.com/comment/85372550
type: Comment
type: QuestionComment
has text: I don't believe so unless it was used somewhere in Amazon's backend. The model I used was created with a script very similar to this example: https://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/imageclassification_caltech/Image-classification-fulltraining.ipynb
comment on: http://stackoverflow.com/q/49103679
score: 0

http://stackoverflow.com/q/48964845
has comment: http://stackoverflow.com/comment/84935759
has comment: http://stackoverflow.com/comment/84935706
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/84935593
has title: Getting Error in user Login in Django
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/84936672
type: UnansweredQuestion
has body: When I try to log-in in this code getting some error. Django 2.0 and Python 3.6.3 views.py def user_login(request): context = RequestContext(request) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user)#Error in this line return HttpResponseRedirect('/') else: return HttpResponse("Your account is disabled.") else: print("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: return render(request, 'Login/login.html', context) Error in Terminal:- Internal Server Error: /user_login/ .... .... File "/home/rails/projects/DevProject/DataCraft/DataSearch/views.py", line 45, in user_login login(request, user) TypeError: 'str' object is not callable Please help me
tagged with: django
tagged with: python
tagged with: django-views
score: 0
type: Question

http://stackoverflow.com/q/49111444
downvote count: 0
type: UnansweredQuestion
tagged with: python
has title: Testing and accessing values in tuples within lists?
has body: I'm doing some exercises on list comprehensions and in this one the y coordinate needs to be limited to 0&lt;=y&lt;=10, I know this doesn't work at all but I can't get my head round tuples within lists and how to access the second part of the tuple in order to test it xvals = [x for x in range(-5,5)] yvals = [(x**2)+5 for x in xvals] coords = list(zip(xvals, yvals)) limitedcoords = [i for i in coords if ((j in i) &lt;= 10)] print(limitedcoords) thanks for your help!
score: 1
type: Question
has answer: http://stackoverflow.com/a/49111842
has answer: http://stackoverflow.com/a/49111562
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/49111510
has comment: http://stackoverflow.com/comment/85228039
favorite count: 0

http://stackoverflow.com/comment/94834064
score: 1
comment on: http://stackoverflow.com/q/48989632
type: Comment
type: QuestionComment
has text: I have exactly the same problem, did you ever find a solution?

http://stackoverflow.com/q/49012601
favorite count: 0
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
has title: SetLayeredWindowAttributes error when used on Tkinter Canvas Item when compiled by PyInstaller
type: Question
has body: I am creating an overlay HUD for a game using transparent Tkinter windows. SetLayeredWindowAttributes is throwing up an error explaining "The parameter is incorrect". But this only happens in the compiled version of the program using PyInstaller. If I launch it from PyCharm, the code works perfectly. canvas = Canvas(root, width = prereswidth, height = preresheight, bg = 'black', bd=0, highlightthickness=0) canvas.master.overrideredirect(True) canvas.master.wm_attributes("-topmost", True) canvas.master.wm_attributes("-disabled", True) canvas.master.wm_attributes("-transparentcolor", "black") canvas.pack() hwnd = root.winfo_id() # getting hwnd with Tkinter windows lExStyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) lExStyle = win32con.WS_EX_COMPOSITED | WS_EX_TRANSPARENT win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, lExStyle) hwnd2 = canvas.winfo_id() lExStyle = win32gui.GetWindowLong(hwnd2, win32con.GWL_EXSTYLE) lExStyle = win32con.WS_EX_LAYERED | win32con.WS_EX_COMPOSITED | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_TOPMOST | win32con.WS_EX_NOACTIVATE win32gui.SetWindowLong(hwnd2, win32con.GWL_EXSTYLE, lExStyle) SetLayeredWindowAttributes(hwnd2, RGB(0, 0, 0), 0, LWA_COLORKEY); I believe my issue here could be something to do with how Tkinter canvas items work. I've tried everything I can think of and Googled for hours and hours. I'm at my wits end with this one.
score: 1
downvote count: 0

http://stackoverflow.com/comment/85179992
has text: @GuoJiachen, I don't think that would be the case. See solution below.
comment on: http://stackoverflow.com/q/49086896
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49110113
answers question: http://stackoverflow.com/q/49109987
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: The csv module of the standard library has a bunch of useful functions for dealing with csv files including easy ways to both read and write them. DictReader is the one you'd want to look at for converting entries into a dictionary. csv module documentation

http://stackoverflow.com/q/49068214
tagged with: twitter
type: Question
has answer: http://stackoverflow.com/a/49069790
answer count: 1
has title: Accessing Tweets of specific time Interval
score: 0
tagged with: python
has body: As of now, I can able to access tweets of a particular count from specific channel(like 100,500)--Etc How to access Tweets from specific time to other specific time of a particular channel Eg: I have to access Tweets from (2nd March 2018 12:00 Am to 3rd March 2018 2:00 pm) I have found one way from Github to access tweets, But I am getting errors, Can anybody help me in solving the Error. Picture Link Thank you.
tagged with: python-3.x
tagged with: tweets
type: UnansweredQuestion
tagged with: streaming
has comment: http://stackoverflow.com/comment/85141935

http://stackoverflow.com/comment/85195928
score: 0
type: AnswerComment
type: Comment
has text: How do i import image instead? whats the code i need to add? I'm really confused
comment on: http://stackoverflow.com/a/49085084

http://stackoverflow.com/q/49029142
tagged with: python
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I've been working trying to use the pretrained model given in this repo https://github.com/tensorflow/models/tree/master/research/slim. I'm using this net https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_v3.py and the checkpoint file given in the main page of the repository for ILSVRC-2012-CLS image classification dataset. I'm downloading the one for Inception V3. I'm just trying to make a prediction so my code is as follow: placeholder = tf.placeholder(tf.float32, shape=[None, input_width, input_height, 3]) # Select the model model = inception(placeholder) # Predict with tf.Session() as sess: tf.train.Saver().restore(sess, "./model/inception_v3.ckpt") init_op = tf.initialize_all_variables() predictions = sess.run(model, feed_dict={placeholder: input}) But I'm receiving an error "NotFoundError (see above for traceback): Tensor name "InceptionV3/AuxLogits/Conv2d_2a_5x5/biases" not found in checkpoint files ./model/inception_v3.ckpt". So I don't know if the ckpt file is not updated to the Tensor names or if I'm doing something wrong. I've check all Tensor Names in the inception_v3.ckpt file and I weren't able to find the tensor name which give me the error. Thanks in advance.
tagged with: machine-learning
tagged with: tensorflow
type: Question
score: 2
downvote count: 0
favorite count: 0
has title: TF: Tensor name not found in checkpoint files

http://stackoverflow.com/comment/84938458
has text: Corrected original post as the absolute import wasn't highlighted as code at the bottom of `myproject/myproject/__init__.py`. Have also added the `__all__ = ['celery_app']` as per Celery docs but hasn't changed anything. Thanks for your help so far.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48963659
score: 0

http://stackoverflow.com/a/49119703
has comment: http://stackoverflow.com/comment/85244998
has body: Just loop through and add 2 elements at a time: the_list = [1, 2, 3, 4, 5] while len(the_list) &gt; 1: the_list = [the_list[i] + the_list[i+1] for i in range(len(the_list)-1)] print(the_list) Output: [3, 5, 7, 9] [8, 12, 16] [20, 28] [48] EDIT I would recommend @CoryKramer's answer, it performs better than this one: In [1]: def get_to_one(arr): ...: while len(arr) &gt; 1: ...: arr = [arr[i] + arr[i+1] for i in range(len(arr)-1)] ...: return arr ...: ...: def kramer_solution(l): ...: while len(l) &gt; 1: ...: l = [i + j for i, j in zip(l, l[1:])] ...: return l ...: In [2]: %timeit get_to_one(range(100)) 1.01 ms ± 2.16 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [3]: %timeit kramer_solution(range(100)) 646 µs ± 1.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [4]: %timeit get_to_one(range(200)) 3.81 ms ± 14.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [5]: %timeit kramer_solution(range(200)) 2.45 ms ± 19.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/49119674
downvote count: 0
score: 3

http://stackoverflow.com/comment/85065677
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49028807
has text: oh right! sorry, edited the answer. Be careful if you're using python 2. Don't call decode on the result.
type: Comment

http://stackoverflow.com/q/49077128
downvote count: 0
favorite count: 0
tagged with: python
has title: How to import arrays from a .txt file to numpy arrays?
has answer: http://stackoverflow.com/a/49077184
type: AnsweredQuestion
score: 1
has body: Apologies if this is super noob, but I've tried searching all over StackOverflow and cannot find out how to import an array from a text file to a numpy array when there are "[" or "[[" chars already present. Context: I saved system log output to a text file, and I've tried using np.genfromtxt() and np.loadtxt(). Also, the arrays are actually highly structured, (they are always 10 columns, but my resulting text file splits apart a single row of 10 columns into one row of, say 6, and another of 4 columns. I was wondering if there was already a built in way to read this data without having to declare "start new row" at "[" and end row at "]". [[ 2.16089589e-07 -2.41978796e-07 5.81936831e-07 2.67195929e-07 1.41540781e-07 -2.39142167e-07 2.11576619e-07 2.70369611e-07 3.11488321e-07 1.41789783e-07] [ -3.81266403e-07 -2.30981200e-07 -7.07703123e-08 -9.66262661e-08 -3.73168461e-07 -2.65608435e-07 -2.38021940e-07 3.23960222e-07 -1.73911175e-07 -4.02730223e-07]]
upvote count: 1
tagged with: import
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85160115
tagged with: arrays
accepted answer: http://stackoverflow.com/a/49077184
tagged with: genfromtxt
answer count: 1

http://stackoverflow.com/comment/85089550
has text: @JimWright it is the name of the form in a `str`. Yes, `signup` and `submit` are there among the others.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49042180

http://stackoverflow.com/a/49040869
has body: You can use the Sieve of Eratosthenes. It's a much faster method to find the first n prime numbers.
has comment: http://stackoverflow.com/comment/85087124
answers question: http://stackoverflow.com/q/49040843
has comment: http://stackoverflow.com/comment/85087037
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85087134
has comment: http://stackoverflow.com/comment/85087072
downvote count: 0
score: 1

http://stackoverflow.com/comment/84979955
has text: Okay, please do not remove that line on which I referred, rather change it to that meaning ;-)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48987634

http://stackoverflow.com/q/48971852
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48971917
upvote count: 9
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48971917
type: AnsweredQuestion
type: Question
score: 9
has title: How to convert .mp3 files to arrays of frequencies and amplitudes using python?
has body: I wanted to design a neural network, which after training would take .mp3 files as input, and then based on training, it would decide if the music is good or bad on a scale of 1-10. But for this, I would need to convert the audio file into arrays of wavelength, frequencies, amplitude and all other parameters required to define music, and then use these arrays as input to the neural network. How should I approach this problem?
answer count: 1
downvote count: 0
tagged with: neural-network

http://stackoverflow.com/a/49004672
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49000268
has body: This has nothing to do with loc. This is a standard way how assignment works in python. A data frame is an object. loc is a method in the dataframe object. Consider the example below where a is created as a list and b is a reference to a, when you are changing b, you are only making the assignment of the variable b to point to something else. a remains the same, until you change the assignment to variable a. #create a list a = [1,2,3] # add another reference to the list b = a b[1] = 5 b Out[4]: [1, 5, 3] # reassign the reference b = 3 b Out[6]: 3 a Out[7]: [1, 5, 3]
score: 1

http://stackoverflow.com/comment/85046338
type: Comment
has text: Hi. Thanks for your help on this Saguara. Much appreciated.
comment on: http://stackoverflow.com/a/48997512
type: AnswerComment
score: 0

http://stackoverflow.com/a/49065698
has body: x = False #True y = 1,2,3,4,5,6,7,8,9, z = 11,22,33,44,55,66,77,88,99 for i in y if x else z: print(i) Should be fairly easy to understand, hope it helps.
downvote count: 0
has comment: http://stackoverflow.com/comment/85137008
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49065615

http://stackoverflow.com/comment/84969948
score: 0
has text: Indeed this is not sorting. Checkout a Python package called Pandas. I am pretty sure it contains all you need to perform this kind of transformation.
comment on: http://stackoverflow.com/q/48982201
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85063865
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49022752
has text: I don't know the reason of the downvotes but maybe you can produce a [mcve](https://stackoverflow.com/help/mcve)

http://stackoverflow.com/comment/85125737
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49059551
has text: This doesn't error out, but nothing gets written to the file. I have a full `json` file but, there is no data in the `csv` file.
score: 0

http://stackoverflow.com/comment/96023027
type: AnswerComment
has text: The same as I. The 'stopOnEntry' is not default attribute, but added flowing other's tutorial 。After remove it ,everything is OK.
type: Comment
comment on: http://stackoverflow.com/a/48966572
score: 0

http://stackoverflow.com/comment/85223199
has text: @Batman that python modules just includes a couple of "constants" declarations that I moved to a different module (sections_elements) to avoid the cluttering of the routes module.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49108742
type: Comment

http://stackoverflow.com/comment/85123335
type: QuestionComment
has text: Your indexing isn't efficient: http://cython.readthedocs.io/en/latest/src/tutorial/numpy.html#efficient-indexing
comment on: http://stackoverflow.com/q/49058949
score: 0
type: Comment

http://stackoverflow.com/a/49121744
type: Answer
has body: I figured it out. I had to remove some garbage letters that were associated with the decimal values. First, I change the received data to string and replaced the garbage letters. Here's how I changed it: [date_now,time_now] = Timestamp() fio2_data = str(fio2.Reader()).replace("\r\n","") fio2_data = fio2_data.replace("\x000","") write_list = [date_now,time_now,fio2_data]
accepted answer of: http://stackoverflow.com/q/49118882
answers question: http://stackoverflow.com/q/49118882
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48978658
has comment: http://stackoverflow.com/comment/84967781
score: 0
upvote count: 1
has body: You might use a dictionary: spines = "spineA_jnt", "spineB_jnt", "spineC_jnt", "spineA_jb", "spineB_jb", "spineC_jb" def group_spines(spines): spine_dict = {} for spine in spines: parts = spine.split('_') if parts[0] in spine_dict: spine_dict[parts[0]].append(spine) else: spine_dict[parts[0]]=[spine] return spine_dict spine_dict = group_spines(spines) # results of group_spines function {'spineA': ['spineA_jnt', 'spineA_jb'], 'spineB': ['spineB_jnt', 'spineB_jb'], 'spineC': ['spineC_jnt', 'spineC_jb']} final_result = dict(spine_dict.values()) # now we have parented the spine parts together {'spineA_jnt': 'spineA_jb', 'spineB_jnt': 'spineB_jb', 'spineC_jnt': 'spineC_jb'}
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48973152

http://stackoverflow.com/a/53573224
downvote count: 1
has comment: http://stackoverflow.com/comment/134788304
has comment: http://stackoverflow.com/comment/94012923
has body: Just for the record, the solution was very simple: remove the extra_compile_args argument completely, but still set the language argument as c++, i.e. from distutils.core import setup, Extension from Cython.Distutils import build_ext from distutils.extension import Extension sources_list = ["timgraph.pyx", "Graph.cpp", "InfGraph.cpp", "sfmt/SFMT.c"] setup(ext_modules=[Extension("pytim", sources=sources_list, language="c++") ], cmdclass={'build_ext':build_ext}) This for whatever reason successfully compiles both the C and the C++.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49000674
answers question: http://stackoverflow.com/q/49000674
upvote count: 1

http://stackoverflow.com/comment/85005314
score: 1
has text: @lotyrin fantastic I sovled my problem using your advice thank you
comment on: http://stackoverflow.com/q/48999861
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49038164
tagged with: pandas
has answer: http://stackoverflow.com/a/49038413
tagged with: python
accepted answer: http://stackoverflow.com/a/49038234
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49038413
type: Question
has body: import pandas as pd df = pd.DataFrame({ 'item':['a','b','c','d','e','f','g','h','i','k'], 'counter':[1,2,3,1,2,3,1,2,3,1] }) Given this structure, what is the best way to auto-generate df['counter'] as a repeating range of integers, cycling through 1, 2, and 3 until it comes to the last row?
has answer: http://stackoverflow.com/a/49038234
score: 0
has title: Repeating Counts in Pandas Data Frame
has answer: http://stackoverflow.com/a/49038342
answer count: 3

http://stackoverflow.com/q/49087038
type: Question
has comment: http://stackoverflow.com/comment/85182569
has comment: http://stackoverflow.com/comment/85181459
score: 0
tagged with: pandas
answer count: 1
tagged with: rolling-average
accepted answer: http://stackoverflow.com/a/49089266
has title: How to set the 5 minutes rolling mean window to re-sample data with Pandas Python
tagged with: python
has body: How can I set the 5 minutes window size to re-sample the data through the rolling mean? I tried different ways but I always get error about the DateTimeIndex, even my data has Index as DateTimeIndex.. Any one knows the right way to do it?? Data index Speed rolling_meanVal DateTime 1/1/2011 0:04 2165 0.057579 NaN 1/1/2011 0:07 3438 0.044646 NaN 1/1/2011 0:10 4713 0.043154 NaN 1/1/2011 0:13 6054 0.014403 NaN 1/1/2011 0:16 7385 0.038972 0.039751 1/1/2011 0:19 8734 0.019927 0.036447 1/1/2011 0:21 10045 0.039548 0.03689 1/1/2011 0:24 11374 0.089709 0.043492 1/1/2011 0:27 12661 0.102816 0.050084 1/1/2011 0:30 13960 0.119699 0.057045 1/1/2011 0:33 15261 0.095108 0.060505 1/1/2011 0:36 16579 0.051854 0.059784 1/1/2011 0:40 17848 0.035654 0.057928 1/1/2011 0:43 19163 0.083695 0.059769 1/1/2011 0:46 20458 0.091149 0.061861 1/1/2011 0:49 21784 0.082233 0.063134 1/1/2011 0:52 23105 0.043388 0.061972 1/1/2011 0:55 24415 0.032073 0.060311 1/1/2011 0:58 25689 0.108548 0.06285 1/1/2011 0:59 27117 0.140965 0.066756 1/1/2011 1:02 28492 0.029816 0.065368 1/1/2011 1:05 29861 0.028124 0.064542 1/1/2011 1:09 31195 0.042464 0.064507 1/1/2011 1:12 32471 0.065898 0.067082 1/1/2011 1:15 33793 0.128899 0.071578 1/1/2011 1:18 35094 0.019488 0.071556 1/1/2011 1:21 36407 0.041034 0.071631 1/1/2011 1:24 37728 0.038828 0.069087 1/1/2011 1:27 39053 0.039328 0.065912 1/1/2011 1:30 40340 0.080378 0.063946 here is the sample data, If I want to take the rolling mean of 5 minutes of window size? I tried the code result_frame['Speed'].rolling(window=20,min_periods=5).mean().rename('rollingmenaVal') but don't understand how to set the frequency of 5 minutes? any Help
has answer: http://stackoverflow.com/a/49089266
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85181436

http://stackoverflow.com/a/49014402
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49013956
has comment: http://stackoverflow.com/comment/85038377
type: Answer
has comment: http://stackoverflow.com/comment/85038153
has comment: http://stackoverflow.com/comment/85039189
has body: You should only need a single loop through the students. {% with crs_stud=course.student.all %} {% for student in students %} {% if student in crs_stud %} &lt;p&gt;{{ student.name.upper }} is already enrolled.&lt;/p&gt; {% else %} // display enrollment form {% endif %} {% endfor %} {% endwith %} The {% with %} tag isn't required here, but will prevent duplicate queries. You might want to try to move this logic out of the template and into your view/helper functions/model methods. For example, you could pass two lists to the template, enrolled_students and unenrolled_students, then loop through both lists in the template.
has comment: http://stackoverflow.com/comment/85038498
score: 0
accepted answer of: http://stackoverflow.com/q/49013956

http://stackoverflow.com/q/49050710
has title: Compare tables to create presence/absence matrix filling empty without decimals
has comment: http://stackoverflow.com/comment/85106590
tagged with: python
linked to: http://stackoverflow.com/q/21801507
linked to: http://stackoverflow.com/q/49035358
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49050769
upvote count: 1
type: Question
tagged with: pandas-groupby
tagged with: pandas
has body: Command line: files can be found at git-hub. File1: https://raw.githubusercontent.com/felipelira/files_to_test/master/file1.txt File2: https://raw.githubusercontent.com/felipelira/files_to_test/master/file2.txt Command line: python teste2.py file1.txt file2.txt test When converting a tabular file in a presence/absence matrix I missed some data in the end. The genomes without a match with an accession were not plot. My previous result was something like this (according the script and example at the post Convert tables to presence/absence matrix python - Solved): genome accession1 accession2 accession3 accession4 accession5 genome1 1 1 1 0 0 genome2 1 0 0 1 1 But I need the other genomes in my forward analysis. I tried to arrange this moving the block that defines df2 before the df1: asmbly_dict = sys.argv[1] blast_result = sys.argv[2] outName = sys.argv[3] + '.txt' with open(blast_result, 'r') as file2: col_genes = ['gene', 'accession'] df2 = pd.read_csv(file2, sep='\t', header=None, names=col_genes) print df2 with open(asmbly_dict, 'r') as file1: col_asmbly = ['gene', 'genome'] df1 = pd.read_csv(file1, sep='\t', header=None, names=col_asmbly) df1['accession'] = df1['gene'].map(df2.set_index('gene')['accession']) #print df1 g = df1.groupby('genome')['accession'].apply(list).reset_index() testdf = g.join(pd.get_dummies(g['accession'].apply(pd.Series).stack()).sum(level=0)).drop('accession', 1) #print testdf.to_string(index=False) testdf.to_csv(outName, sep='\t', header=True, index=False) Print of df2: gene accession 0 gene1 accession1 1 gene2 accession2 2 gene3 accession3 3 gene4 accession1 4 gene5 accession4 5 gene6 accession5 Print of df1: gene genome accession 0 gene1 genome1 accession1 1 gene2 genome1 accession2 2 gene3 genome1 accession3 3 gene4 genome2 accession1 4 gene5 genome2 accession4 5 gene6 genome2 accession5 6 gene7 genome3 NaN 7 gene8 genome3 NaN 8 gene9 genome4 NaN Print of testdf: genome accession1 accession2 accession3 accession4 accession5 genome1 1…
accepted answer: http://stackoverflow.com/a/49050769
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/49120835
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49128659
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49129385
type: Question
has title: Replace duplicate columns in data frame
has body: I have a data frame in pyspark. This data frame has say some columns with special characters. cols = df.schema.names cols ['abc test', 'test*abc', 'eng)test', 'abc_&amp;test'] reps = ((' ', '_&amp;'), ('(', '*_'), (')', '_*'), ('{', '#_'), ('}', '_#'), (';', '_##'), ('.', '_$'), (',', '_$$'), ('=', '_**')) def col_rename(x): new_cols = reduce(lambda a, kv: a.replace(*kv), reps, x) for i in cols: df = df.withColumnRenamed(i, col_rename(cols, i)) return df Now I want to see if after replacing the special characters in the column names if there are any duplicate columns. As we can see there is a duplicate of columns in the new_cols abc_&amp;test I want to return extra _ underscore when this happens. My new_cols shoul be like below ['abc__&amp;test', 'test*_abc', 'eng_*test', 'abc_&amp;test'] How can I achieve what I want?
tagged with: pyspark
possible better answer: http://stackoverflow.com/a/49129385
has answer: http://stackoverflow.com/a/49128659
answer count: 2
tagged with: apache-spark
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49031703
has comment: http://stackoverflow.com/comment/85070208
score: -1
has title: Xpath or css selector attrbute value in scrapy
tagged with: css-selectors
has answer: http://stackoverflow.com/a/49033036
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85069057
type: UnansweredQuestion
tagged with: python
tagged with: xpath
upvote count: 0
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/85069125
has comment: http://stackoverflow.com/comment/85068441
type: Question
has body: Hi there I am new to scrapy and I want to extract an attribute value form an html element. So what could be the right way to extract that attribute value form that html . I want to extract "data-next-url" attribute I am using that xpath but it is not working response.xpath('//*[@class="loading_more_jobs"]/@data-next-url').extract()

http://stackoverflow.com/comment/84976788
comment on: http://stackoverflow.com/q/48985717
score: 0
type: Comment
type: QuestionComment
has text: @CongMa I want to implement this output in some other language, whose output should match to python's output.

http://stackoverflow.com/comment/84936289
type: AnswerComment
comment on: http://stackoverflow.com/a/48964899
score: 0
type: Comment
has text: Thanks alot! That helped me find the error. I have used the same variable (pix_per_cell) inside my code and it was overwritten :)

http://stackoverflow.com/comment/84939108
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48964455
has text: make a console.log in your buttonHandler.... was it called? make print in your receiver. was it called after you hitting the button?
type: AnswerComment

http://stackoverflow.com/a/49097052
downvote count: 0
type: AcceptedAnswer
has body: First of all dictionaries only use keys (see: How to index into a dictionary?). If you are a lazy person you cold catch both KeyError and IndexError with the LookupError (lest say you have a dictionary filled with lists). Never the less i would prefer to catch them separately with two different exceptions. E.g.: try: # do some stuff here except KeyError: # key error handling except IndexError: # index error handling This way you can respond to these exceptions in different ways, as they were caused by different events. Furthermore there might be other exceptions that are a variation of a LookupError (see below) and you do not want to catch these exceptions as well (same reason one does not simply use except:). Another way to use the LookupError could be if you are in need of your own exception, as your error that this exception represents is nether described by a KeyError, nor an IndexError, but is a type of LookupError. In this case your custom exception could inherit from LookupError.
answers question: http://stackoverflow.com/q/49096749
has comment: http://stackoverflow.com/comment/121023310
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49096749
upvote count: 5
has comment: http://stackoverflow.com/comment/85202076

http://stackoverflow.com/q/49072681
score: 3
has title: Python CLoader and Unicode
has comment: http://stackoverflow.com/comment/85151552
downvote count: 0
has comment: http://stackoverflow.com/comment/85152889
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85151108
has answer: http://stackoverflow.com/a/49074198
accepted answer: http://stackoverflow.com/a/49074198
type: Question
has comment: http://stackoverflow.com/comment/85153804
has comment: http://stackoverflow.com/comment/85152616
has body: When using CLoader as the Loader for yaml.load, it will not process unicode in my json. However, when I use the default loader the json is loaded fine. I can work around this by catching the exception and loading it without CLoader. Has anyone any experience with this that knows of a solution? #!/usr/bin/python import yaml from yaml import CLoader as Loader1 from yaml import Loader data_string = "\"nickname\": \"Stringhere \ud83d\udcaf\"" print "Loading with default loader" json_data = yaml.load(data_string, Loader=Loader) print "Loading with CLoader" json_data = yaml.load(data_string, Loader=Loader1) yaml.scanner.ScannerError: while parsing a quoted scalar in "&lt;byte string&gt;", line 1, column 13 found invalid Unicode character escape code in "&lt;byte string&gt;", line 1, column 27
upvote count: 3
tagged with: yaml
has comment: http://stackoverflow.com/comment/85154534
answer count: 1
has comment: http://stackoverflow.com/comment/85151725
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/85157893
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85086916
comment on: http://stackoverflow.com/q/49040765
type: Comment
type: QuestionComment
score: 1
has text: What version of Python 2 are you using?

http://stackoverflow.com/comment/94845248
type: QuestionComment
has text: I ended up not using dlib after all, but it seems dlib 19.10 fixes this problem. From http://dlib.net/release_notes.html : Added support for variadic Python functions in find_max_global().
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48989632

http://stackoverflow.com/q/48988182
has comment: http://stackoverflow.com/comment/84982162
upvote count: 13
tagged with: numpy
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84981939
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/29082001
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84982205
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84982288
downvote count: 0
has body: I have a dataframe of the form, df: cat_var_1 cat_var_2 num_var_1 0 Orange Monkey 34 1 Banana Cat 56 2 Orange Dog 22 3 Banana Monkey 6 .. Suppose the possible values of cat_var_1 in the dataset have the ratios- ['Orange': 0.6, 'Banana': 0.4] and the possible values of cat_var_2 have the ratios ['Monkey': 0.2, 'Cat': 0.7, 'Dog': 0.1]. How to I split the data into train, test and validation sets (60:20:20 split) such that the ratios of the categorical variables remain preserved? In practice, these variables can be of any number, not just two. Also, clearly, the exact ratios may never be achieved in practice, but we would like it to be as near as possible. I have looked into the StratifiedKFold method from sklearn described here: how to split a dataset into training and validation set keeping ratio between classes? but this is restricted to evaluating on the basis of one categorical variable only. Additionally, I would be grateful if you could provide the complexity of the solution you achieve.
tagged with: machine-learning
score: 13
type: Question
has title: How to achieve stratified K fold splitting for arbitrary number of categorical variables?
has answer: http://stackoverflow.com/a/49045202
accepted answer: http://stackoverflow.com/a/49045202
has comment: http://stackoverflow.com/comment/85094090

http://stackoverflow.com/q/49036853
tagged with: python
has answer: http://stackoverflow.com/a/49036934
tagged with: scipy
type: Question
tagged with: numpy
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 8
tagged with: random
has title: Scipy randint vs numpy randint
score: 8
has body: I have a simple yet broad question regarding two methods: scipy.stats.randint and numpy.random.randint After reading the API for both methods I'm a bit confused as to when it is best to use each method; therefore, I was wondering if someone could outline the differences between the two and possibly offer some examples of when one method would be preferable to use over the other. Thanks! Edit: Links to each method's documentation -> numpy.random.randint, scipy.stats.randint
type: UnansweredQuestion

http://stackoverflow.com/comment/84988034
comment on: http://stackoverflow.com/q/48991200
type: QuestionComment
type: Comment
has text: Are numbers always integers?
score: 0

http://stackoverflow.com/comment/85126030
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49060459
has text: Confusing thing: your text mentions you need to replace the ending of a string. Do you mean a *word*, or a *line*? Your code shows the latter, but it isn't clear from your text.

pip
tags question: http://stackoverflow.com/q/49094768
tags question: http://stackoverflow.com/q/49053131
tags question: http://stackoverflow.com/q/49090271
tags question: http://stackoverflow.com/q/49101629
tags question: http://stackoverflow.com/q/49031454
tags question: http://stackoverflow.com/q/49018135
tags question: http://stackoverflow.com/q/49019784
tags question: http://stackoverflow.com/q/49090986
tags question: http://stackoverflow.com/q/49057888
tags question: http://stackoverflow.com/q/49028533
tags question: http://stackoverflow.com/q/48970914
tags question: http://stackoverflow.com/q/49031878
tags question: http://stackoverflow.com/q/49042878
tags question: http://stackoverflow.com/q/49019136
tags question: http://stackoverflow.com/q/49056702
tags question: http://stackoverflow.com/q/49074022
tags question: http://stackoverflow.com/q/49061002
tag name: pip
tags question: http://stackoverflow.com/q/49085633
tags question: http://stackoverflow.com/q/49027030
tags question: http://stackoverflow.com/q/49007742
tags question: http://stackoverflow.com/q/49096890
tags question: http://stackoverflow.com/q/49119453
tags question: http://stackoverflow.com/q/48972193
tags question: http://stackoverflow.com/q/49075909
tags question: http://stackoverflow.com/q/48965928
tags question: http://stackoverflow.com/q/48969022
tags question: http://stackoverflow.com/q/49012215
tags question: http://stackoverflow.com/q/49061973
tags question: http://stackoverflow.com/q/49028739
tags question: http://stackoverflow.com/q/48990067
tags question: http://stackoverflow.com/q/49121286
tags question: http://stackoverflow.com/q/48964492
tags question: http://stackoverflow.com/q/49074327
tags question: http://stackoverflow.com/q/49017568
tags question: http://stackoverflow.com/q/49028871
tags question: http://stackoverflow.com/q/49121012
type: Tag
tags question: http://stackoverflow.com/q/48976670
tags question: http://stackoverflow.com/q/48986689
tags question: http://stackoverflow.com/q/48968668
tags question: http://stackoverflow.com/q/49023099
tags question: http://stackoverflow.com/q/48988232
tags question: http://stackoverflow.com/q/49020879
tags question: http://stackoverflow.com/q/49039882
tags question: http://stackoverflow.com/q/48965493
tags question: http://stackoverflow.com/q/49094597
tags question: http://stackoverflow.com/q/48990333
tags question: http://stackoverflow.com/q/49093582
tags question: http://stackoverflow.com/q/48999177
tags question: http://stackoverflow.com/q/49036741
tags question: http://stackoverflow.com/q/49085503
tags question: http://stackoverflow.com/q/48986820
tags question: http://stackoverflow.com/q/49001065
tags question: http://stackoverflow.com/q/49069714
tags question: http://stackoverflow.com/q/49091782

http://stackoverflow.com/comment/85104911
score: 0
type: AnswerComment
has text: Hold up, there's another problem, sorry. Abstracting the code as we've done here removes the variables txtCost and txtFinalBalance, which do the job of actually performing the functions (adding up the cost for all the chocolates, and subtracting that sum from the initial balance, respectively). Search up txtCost.insert(0, CostOfMeal) and txtFinalBalance.insert(0, FinalBal) on the document and you'll see what I mean. On the unobstructed code, I basically used those variables to print the Label and Entry boxes. How can I maintain the abstracted code while fixing this issue?
type: Comment
comment on: http://stackoverflow.com/a/49029637

http://stackoverflow.com/comment/85123862
type: QuestionComment
type: Comment
has text: Solved. The text file to export to needs to exist.
comment on: http://stackoverflow.com/q/49045184
score: 0

http://stackoverflow.com/q/48996352
has answer: http://stackoverflow.com/a/48996454
type: Question
tagged with: ipc
upvote count: 0
has comment: http://stackoverflow.com/comment/84998581
answer count: 1
favorite count: 0
tagged with: python
has body: I want to write a few python3 scripts that can retrieve almost instantly some variables (less than 400 integers in total) shared by one another. One script shares specific variable. Many scripts can read this variable. Script can update value up to 50 times per second and share up to 50 variables. Bus should allow at least 10k R/W operations per second. Bus can be managed by master process Hardware: ARM based board with modern Debian OS and 1GiB of RAM. KISS and lightweight Some scripts are reading data from sensors and sharing their values. Some are logging values, other is processing data and sets its variables according to target motor speed.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84999096
has title: Recommendations for communication between Python scripts
accepted answer: http://stackoverflow.com/a/48996454
downvote count: 3
score: -3
type: AnsweredQuestion

http://stackoverflow.com/comment/85247989
type: Comment
score: 0
has text: Your output is ambiguous should the value for 1:00 AM (value 2) get aggregated into the first row or the second row or both?
comment on: http://stackoverflow.com/q/49120845
type: QuestionComment

http://stackoverflow.com/comment/85069057
type: Comment
has text: so what would I do if I want to get that attribute value
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49031703

http://stackoverflow.com/comment/85214576
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49104779
has text: What? This output matches exactly what your question said the result should be.

http://stackoverflow.com/q/49041839
has body: First of all, sorry for my English. I'm from Buenos Aires, and I've started learning Python just a few weeks ago. Furthermore, I have a really basic knowledge in programming. All I was able to do so far was by getting the info from internet (no formal education in this matter-I was studying Accounting last year). As of this post, I want to find an element in a web page but I can't seem to get it right. I've even tried to click on "space" key-the simplest thing to do in this case. I want to click on "OK" button. I have from "Inspect element": No Pending Documents print: I've tried these 5 codes: from selenium.webdriver.common.action_chains import ActionChains element_ok = driver.find_element_by_xpath("//input[@id='popup_ok']") Action.Chains(driver).move_to_element(element_ok).perform() element.click() driver.find_element_by_xpath(".//*[@id='popup_ok']/div/input").click() driver.find_element_by_css_selector(".button_main[value='OK']").click() clear_button = driver.find_element_by_xpath("//input[@id='popup_panel'][@type='button']") clear_button = driver.find_element_by_xpath("//form[@id='popup_ok']/input[1]") import keyboard keyboard.press_and_release('shift+s, space') Would someone help me get through this? PS: I'm using selenium (read from it in the book 'Automate the Boring Stuff with Python. Practical Programming for Total Beginners'. And chrome webdriver.
answer count: 4
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/49042767
has title: Unable to find_element in web through Python (selenium)
has answer: http://stackoverflow.com/a/49051342
score: 0
has answer: http://stackoverflow.com/a/49043018
has answer: http://stackoverflow.com/a/49042265
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85135270
has text: Pleas show your simple code.
type: Comment
comment on: http://stackoverflow.com/q/49064817
score: 0
type: QuestionComment

http://stackoverflow.com/a/48975854
answers question: http://stackoverflow.com/q/48974730
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84968947
accepted answer of: http://stackoverflow.com/q/48974730
has body: If you want to duplicate any existing binding, the first thing you need to do is understand what the original sequence is bound to. In this case, the binding &lt;Control-/&gt; is bound to the binding tag "Listbox" (the name of the internal widget class) The first step is to get the existing binding by making a raw call to the Tcl interpreter: func = root.call("bind", "Listbox", "&lt;Control-/&gt;") The second step is to associate that original function to the new key combination: root.call("bind", "Listbox", "&lt;Control-A&gt;", func) Note: the above will associate the binding with all Listbox widgets rather than just a specific listbox.

http://stackoverflow.com/comment/84987195
comment on: http://stackoverflow.com/q/48986237
score: 0
has text: How is *date* not the same for all rows per from your `assign` call? Also, `timedelta` is neither defined nor imported method. Be sure code is fully compilable for us to reproduce.
type: Comment
type: QuestionComment

ruamel.yaml
tags question: http://stackoverflow.com/q/49093736
type: Tag
tag name: ruamel.yaml
tags question: http://stackoverflow.com/q/49029459

http://stackoverflow.com/a/48990066
has comment: http://stackoverflow.com/comment/84984727
downvote count: 0
has comment: http://stackoverflow.com/comment/84984750
accepted answer of: http://stackoverflow.com/q/48989472
answers question: http://stackoverflow.com/q/48989472
type: AcceptedAnswer
has body: This might help. Use the isalpha method to remove all alpha chars and the use eval Ex: s = "1abc0+5*1hv0" s = "".join([i for i in s if not i.isalpha()]) print eval(s) Output: 60
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/49061132
has comment: http://stackoverflow.com/comment/85129619
score: 0
has body: I'm currently working on a little side project yet having multiple issues. I'm reading a file within the folder where the project is that holds data for 10 users. As for the code itself...it's pretty big. def ouvrir_fichier(nomFichier): """ Ne pas oublier les docstring """ try: fp = open(nomFichier, 'r') return fp except: return print("Le fichier n'existe pas. Veuillez réessayer.") def lire_fichier(fp): """ Ne pas oublier les docstring""" # Lis n et initialise une liste vide -- # où il y a une liste vide pour chaque usager du réseau # ensuite lis le reste du fichier et ajouter l'information à reseau liste1 = fp.readlines() n = int(liste1[0]) liste2 = liste1[1:] reseau = [[] for i in range(n)] for i in liste2: i = i.replace("\n", "") data = i.split(" ") valeur1 = int(data[0]) valeur2 = int(data[1]) reseau[valeur1].append(valeur2) reseau[valeur2].append(valeur1) fp.close() return reseau def trouver_nombre_elements_communs_entre_listes(liste1, liste2): """ Ne pas oublier les docstring""" compteur_amis_commun = 0 for element in liste1: if element in liste2: compteur_amis_commun = compteur_amis_commun + 1 return compteur_amis_commun def initialiser_matrice(n): """ Crée une matrice nxn, initialisée avec des zéros et retourne la matrice. Args: n (int): dimension de la matrice nxn Returns: matrice (list): matrice initialisée """ matrice = [] for ligne in range(n): # pour chacune des lignes dans n matrice.append([]) # créer une ligne (liste) et l'initialiser à 0 for colonne in range(n): matrice[ligne].append(0) # ajouter un 0 pour chaque n colonne return matrice def calculer_scores_similarite(reseau): """ Ne pas oublier les docstring""" n = len(reseau) matrice_similarite = initialiser_matrice(n) liste1 = [] liste2 = [] compteur_liste1 = 0 compteur_liste2 = 0 for element_liste1 in reseau: liste1 = element_liste1 for element_liste2 in reseau: liste2 = element_liste2 compteur_amis_commun = trouver_nombre_elements_communs_entre_listes(liste1, liste2) matrice_similarite[compteur_…
has comment: http://stackoverflow.com/comment/85127695
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/85129359
has comment: http://stackoverflow.com/comment/85128018
has answer: http://stackoverflow.com/a/49062292
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85129415
type: Question
has comment: http://stackoverflow.com/comment/85127598
has comment: http://stackoverflow.com/comment/85129470
has comment: http://stackoverflow.com/comment/85129307
has comment: http://stackoverflow.com/comment/85127301
has comment: http://stackoverflow.com/comment/85129236
accepted answer: http://stackoverflow.com/a/49062292
has comment: http://stackoverflow.com/comment/85129263
has comment: http://stackoverflow.com/comment/85128249
has comment: http://stackoverflow.com/comment/85129662
has title: ValueError: 0 is not in list when running this code
has comment: http://stackoverflow.com/comment/85128846
has comment: http://stackoverflow.com/comment/85127444
answer count: 1
has comment: http://stackoverflow.com/comment/85129082
has comment: http://stackoverflow.com/comment/85129280
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85127360
has comment: http://stackoverflow.com/comment/85129600

http://stackoverflow.com/comment/85109833
score: 0
comment on: http://stackoverflow.com/q/49051965
has text: I'm still not sure how to modify two different attributes individually though
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84956607
has text: welcome please upvote and accept the answer if you got your answer. Happy to help you :-)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48966810
type: AnswerComment

http://stackoverflow.com/comment/85092851
has text: Something like this `response = requests.get('<MY_URI>', headers={'Authorization': 'Token <MY_TOKEN>'})`. Authorization header will authenticate user.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49043267

http://stackoverflow.com/comment/85229524
type: QuestionComment
has text: @Dhanvanth I'm not sure, if I fully understand what you want achieve. But if you want to return the sum of all challan types, you need to store the individual values in a list for example. Create a global list, and each time the user enters a number, add the corresponding value to the list. Once the while loop is exited calculate the sum of the list
score: 0
comment on: http://stackoverflow.com/q/49112152
type: Comment

connexion
tag name: connexion
type: Tag
tags question: http://stackoverflow.com/q/48995459

http://stackoverflow.com/comment/85157770
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49075920
type: Comment
has text: I did have to add TP.UserID in the SELECT statement, but adjusting the nolock worked. Thanks!

http://stackoverflow.com/a/49053930
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has body: sst only supports Python 2 even though pip will let you install it for Python 3. The error NameError: name 'StandardError' is not defined is from sst trying to use the built in exception StandardError which was removed in Python 3. To resolve this, you can either use a different module (which I would recommend) or downgrade to Python 2.7.
accepted answer of: http://stackoverflow.com/q/49053105
type: Answer
answers question: http://stackoverflow.com/q/49053105

http://stackoverflow.com/q/49058931
answer count: 3
linked to: http://stackoverflow.com/q/29950956
downvote count: 0
possible better answer: http://stackoverflow.com/a/54400714
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/54400714
favorite count: 0
score: 6
tagged with: django
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/49068529
type: AnsweredQuestion
has body: (project is available on github with that problem) For some reason serializer's depth option makes fields ignored on create. Serializer: class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('question', 'body',) depth = 1 View: class AnswerList(ListCreateAPIView): queryset = Answer.objects.all() serializer_class = AnswerSerializer When I try to create an answer with depth = 1 I get NOT NULL constraint failed: forum_answer.question_id, but when I comment out depth = 1 everything works. But of course I don't get a full Question object, only pk of it.
has answer: http://stackoverflow.com/a/49068392
type: Question
has title: DRF serializer depth makes fields ignored on create
accepted answer: http://stackoverflow.com/a/49068529

http://stackoverflow.com/q/49062852
has answer: http://stackoverflow.com/a/49063012
has title: Conditionally increase integer count with an if statement in python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85131020
has answer: http://stackoverflow.com/a/49062934
upvote count: 3
type: Question
type: AnsweredQuestion
score: 3
tagged with: if-statement
linked to: http://stackoverflow.com/q/44012748
tagged with: global-variables
accepted answer: http://stackoverflow.com/a/49062934
answer count: 3
downvote count: 0
has body: I'm trying to increase the count of an integer given that an if statement returns true. However, when this program is ran it always prints 0.I want n to increase to 1 the first time the program is ran. To 2 the second time and so on. I know functions, classes and modules you can use the global command, to go outside it, but this doesn't work with an if statement. n = 0 print(n) if True: n += 1
favorite count: 0
has answer: http://stackoverflow.com/a/63396040
possible better answer: http://stackoverflow.com/a/49063012
tagged with: python

http://stackoverflow.com/q/48980187
score: 1
has body: I want to insert 2.5 between 2 and 3 in this linklist-like structure. class edge_model: def __init__(self): self.ymax = None self.xmin = None self.dx = None self.edge_next = None if __name__ == '__main__': e1 = edge_model() e2 = edge_model() e3 = edge_model() e_in = edge_model() e1.dx = 1 e2.dx = 2 e3.dx = 3 e_in.dx = 2.5 e1.edge_next = e2 e2.edge_next = e3 e3.edge_next = None p = e1 while p.edge_next: if e_in.dx &lt; p.edge_next.dx: e_in.edge_next = p.edge_next p.edge_next = e_in break else: p = p.edge_next.edge_next print e1.dx print e1.edge_next.dx print e1.edge_next.edge_next.dx print "=====" Why is the result of outputs not 1 -&gt; 2 -&gt; 2.5-&gt; 3? and how to make it? Some change. But the same question.
upvote count: 1
type: Question
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48980239
linked to: http://stackoverflow.com/q/48980843
accepted answer: http://stackoverflow.com/a/48980239
tagged with: python
has title: How to insert a new node in a link list like structure?
type: AnsweredQuestion

cookies
tags question: http://stackoverflow.com/q/49042232
type: Tag
tags question: http://stackoverflow.com/q/49042064
tag name: cookies

http://stackoverflow.com/comment/84993510
has text: Pickle does not support that. Check out alternative serialization mechanisms, such as [dill](https://github.com/uqfoundation/dill).
comment on: http://stackoverflow.com/q/48993993
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85041501
type: Comment
type: QuestionComment
has text: On a mac, open terminal, and type `pip install nltk` (not in python). Then, in your python interpreter, try `import nltk`
comment on: http://stackoverflow.com/q/49018135
score: 0

http://stackoverflow.com/comment/85239241
type: AnswerComment
has text: It does accept 'None` statically, but it can't *grow* in any direction easily. Tensorflow checks it at runtime. If you do need to grow the tensor, you have to specify `shape_invariants` and be careful in your body function. In short, `tf.while_loop` is tricky.
score: 0
comment on: http://stackoverflow.com/a/49115521
type: Comment

http://stackoverflow.com/comment/85155943
type: Comment
comment on: http://stackoverflow.com/a/49073146
has text: Thanks, I went about it slightly different, kind of like @DavidW points out by just getting the returned dictionary. But I like this answer, it shows how I could actually implement classes between c and python a little clearer than I was able to find online. Thanks.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84976686
type: QuestionComment
has text: Then you need to be explicit, it is not understood by Python in the way you might express it in English. `if not S[0].isalpha() and not S[2].isalpha() and not S[4].isalpha():`. For longer lists of conditions you might want to use `any()` or `all()`. But at the moment, it's not doing what you think it's doing. I'm not even sure you should be using `and` but `or` instead.
comment on: http://stackoverflow.com/q/48985875
score: 0
type: Comment

http://stackoverflow.com/a/49018034
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/49017818
has comment: http://stackoverflow.com/comment/85041819
score: 1
accepted answer of: http://stackoverflow.com/q/49017818
has body: You can iterate through a list of desired indices. places = (3, 4, 7) if [L1[i] for i in places] == \ [L2[i] for i in places]: print "YES" else: print "NO" Of course, this reduces to a simple if all, but the above might help you understand the logic. print all(L1[i] == L2[i] for i in places)
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/comment/85171571
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49082424
has text: Use pandas to load the data in to data frames and join them

http://stackoverflow.com/comment/85071135
type: QuestionComment
type: Comment
score: 1
has text: [`fuck_captcha("data/bv22.jpg")`](https://emojipedia.org/thinking-face/)
comment on: http://stackoverflow.com/q/49030273

http://stackoverflow.com/q/49063535
has title: model.predict in keras giving same output
tagged with: python
answer count: 0
has body: I have a dataset of 10 million, each record having 4 parameters. If I model using the following when I carry out model.predict, I get the same result. # create model model = Sequential() model.add(Dense(12,input_dim=4, kernel_initializer='uniform', activation='tanh')) model.add(Dense(8, kernel_initializer='uniform', activation='tanh')) model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(numpy.array(X1), numpy.array(Y1), epochs=50, batch_size=1000000, verbose=2)
has comment: http://stackoverflow.com/comment/85229015
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85228735
has comment: http://stackoverflow.com/comment/85132286
score: 0
tagged with: keras
type: UnansweredQuestion

http://stackoverflow.com/q/49001095
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85007459
upvote count: 1
answer count: 1
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/49001186
downvote count: 1
has body: Silly question... I want to try out multiprocessing. I would like to just test a basic test doing for x in range(10): p = Process(target=func, args=(100)) p.Daemon = True p.start() p.join() I am looking for a func function that takes a few second to run, so that i can check the basics are working. Ideally it would be CPU heavy too so i can chek with htop that it is really using multiple processors. I tried the factorial def func(n): if n == 0: return 1 else: return n * factorial(n-1) but i cannot having do more than a 1000 recursion , which is not taking long enough. Any idea of a simple function taking like 5s to run that I could use to do a simple multiprocessor test?
tagged with: python
has title: Python - Need a function that takes few seconds to run to test multiprocessing
has answer: http://stackoverflow.com/a/49001186

http://stackoverflow.com/a/49297448
accepted answer of: http://stackoverflow.com/q/48984203
has comment: http://stackoverflow.com/comment/85596794
has body: Try using shell command to open that,something like xdg-open.Though that python code should work. Btw are you using vnc to access the remote host? If you are please check the remote host you're running this code on has display or export its display to the vnc client.I had the same issue and if you're using vnc then you will need to export display
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48984203
type: AcceptedAnswer

http://stackoverflow.com/comment/85104816
comment on: http://stackoverflow.com/q/49050108
score: 0
has text: It is because my app has its own static folder and when I use `collect-static `it creates another one in root directory as i have given ` STATIC_ROOT` as base dir.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49064114
answer count: 2
has answer: http://stackoverflow.com/a/49065135
has answer: http://stackoverflow.com/a/49065874
tagged with: nltk
type: UnansweredQuestion
has body: Say that I have 100 tweets. In those tweets, I need to extract: 1) food names, and 2) beverage names. Example of tweet: "Yesterday I had a coca cola, and a hot dog for lunch, and some bana split for desert. I liked the coke, but the banana in the banana split dessert was ripe" I have to my disposal two lexicons. One with food names, and one with beverage names. Example in food names lexicon: "hot dog" "banana" "banana split" Example in beverage names lexicon: "coke" "cola" "coca cola" What I should be able to extract: [[["coca cola", "beverage"], ["hot dog", "food"], ["banana split", "food"]], [["coke", "beverage"], ["banana", "food"], ["banana split", "food"]]] The names in the lexicons can be 1-5 word(s) long. How do I go about extracting n-grams from the tweets, using my lexicons?
linked to: http://stackoverflow.com/q/43593428
tagged with: n-gram
type: Question
has title: extracting n-grams from tweets in python
tagged with: python
linked to: http://stackoverflow.com/q/49091931
tagged with: nlp
linked to: http://stackoverflow.com/q/47663870
score: 0

http://stackoverflow.com/q/49088820
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85183416
has body: so as i'm out of ideas I've turned to geniuses on this site. What I want to be able to do is to have two separate csv files. One of which has a bunch of store names on it, and the other to have black listed stores. I'd like to be able to run a python script that reads the 'black listed' sheet, then checks if those specific names are within the other sheet, and if they are, then delete those off the main sheet. I've tried for about two days straight and cannot for the life of me get it to work. So i'm coming to you guys to help me out. Thanks so much in advance. p.s If you can comment the hell out out of the script so I know what's going on it would be greatly appreciated. EDIT: I deleted the code I originally had but hopefully this will give you an idea of what I was trying to do. (I also realise it's completely incorrect) import csv with open('Black List.csv', 'r') as bl: reader = csv.reader(bl) with open('Destinations.csv', 'r') as dest: readern = csv.reader(dest) for line in reader: if line in readern: with open('Destinations.csv', 'w'): del(line)
has comment: http://stackoverflow.com/comment/85184410
has comment: http://stackoverflow.com/comment/85183691
tagged with: python
has answer: http://stackoverflow.com/a/49090186
accepted answer: http://stackoverflow.com/a/49090186
possible better answer: http://stackoverflow.com/a/49090263
has comment: http://stackoverflow.com/comment/85184318
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85183628
has comment: http://stackoverflow.com/comment/85183133
has comment: http://stackoverflow.com/comment/85183326
type: Question
has comment: http://stackoverflow.com/comment/85183371
has title: Cross referencing two csv files in python
has answer: http://stackoverflow.com/a/49090263

http://stackoverflow.com/q/49114071
type: UnansweredQuestion
downvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/49114274
has title: Code of merge sort, why there is two same while loop?
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: The following code is copy from this website http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html def mergeSort(alist): print("Splitting ",alist) if len(alist)&gt;1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i &lt; len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j &lt; len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",alist) alist = [54,26,93,17,77,31,44,55,20] mergeSort(alist) print(alist) In the above code, there is two almost the same while loop, e.g. while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; righthalf[j]: alist[k]=lefthalf[i] i=i+1 and while i &lt; len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 What is the reason of adding the last while loop? Thank you!

http://stackoverflow.com/comment/85120726
type: QuestionComment
has text: Yes. I mean making a generic class to use as a data container.
comment on: http://stackoverflow.com/q/49057951
score: 0
type: Comment

http://stackoverflow.com/comment/85254422
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49048893
type: Comment
has text: @SagnikSarkar: Welcome! Yeah Sure that will be great!

http://stackoverflow.com/q/49031746
answer count: 1
tagged with: test-reporting
has body: So I have a selenium/Python script that reads a JSON file for a list of URL and then one by one browses them; and takes screenshot. I want to generate a result report (HTML) at the end of test BUT with following; The report should not just say that script passed/failed but it also shares the result against each parameter URL. For example if 2 out of 5 websites were down at the point of test then it is reflected in the HTML results. Like facebook.com - OK while www.sdadas.com - Failed Here is my code: with open('Path to JSON file', encoding='utf-8') as s: data = json.loads(s.read()) driver = Edge() driver.set_page_load_timeout(10) driver.implicitly_wait(5) for site in data['sites']: driver.get(data['sites'][site]) driver.get_screenshot_as_file("Screenshot path\\Image" + site + '.png') driver.close() My JSON file { "sites": { "facebook": "http://www.facebook.com", "Wrong": "http://www.gonssgle.com" } }
tagged with: python
has answer: http://stackoverflow.com/a/49032861
type: AnsweredQuestion
tagged with: selenium
type: Question
has title: Test Result Status at Parameter level with Selenium Python
accepted answer: http://stackoverflow.com/a/49032861
score: 0
tagged with: automated-tests

http://stackoverflow.com/q/48969460
has body: So what I want to do is kind of hard to describe in the title. Here's what I want to do: In the code below, I want to have some general methods someone can call on the Room class (ex. Search, Loot) and the Player class (ex. quit, heal). The way I want that to happen is the player enters what they want to do in an input, and python will look up that choice in a dict which matches the choice to a method. I've already successfully done that with the exits on the rooms. I can probably do it by making a child class and listing the methods there, but I really don't want to do that as that would seem cluttery. When I run the code below, it just auto exits. If I run it with that first dictionary commented out, I get an error saying that __init__() is missing a required positional argument. from textwrap import dedent from sys import exit class Player(object): actions = { 'QUIT': quit } def __init__(self, actions): self.actions = actions # Want actions to be a list of actions like in the Room Class # def quit(self): # Quits the game exit(0) class Room(object): # Description is just a basic room description. No items needed to be added here. def __init__(self, desc, exits, exitdesc): self.desc = desc self.exits = exits self.exitdesc = exitdesc # Also want list of general actions for a room here. def enterroom(self): #First print the description of the room print(self.desc) #Then print the list of exits. if len(self.exits) &gt; 1: print(f"You see the following exits:") for exd in self.exitdesc: print(self.exitdesc[exd]) elif len(self.exits) == 1: print(f"There is one exit:") for exd in self.exitdesc: print(self.exitdesc[exd]) else: print("There are no exits.") # Then allow the player to make a choice. self.roomactivity() # Here's what I mean about calling the methods via a dictionary def roomactivity(self): while True: print("What do you want to do?") choice = input("&gt; ").upper() if choice in self.exits: self.exits[choice].enterroom() #And here's where I want to call action…
has answer: http://stackoverflow.com/a/48969635
accepted answer: http://stackoverflow.com/a/48969635
tagged with: adventure
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48969505
has comment: http://stackoverflow.com/comment/84944502
favorite count: 0
has title: Python: Listing methods in a dict in __init__
possible better answer: http://stackoverflow.com/a/48969505
tagged with: python
tagged with: text
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/q/49007292
has body: I configured remote Python interpreter 3 months ago with Vagrant, when I was using it, everything was fine, for the last two days I am receiving Couldn't refresh skeletons for remote interpreter error very frequently, as on the video: http://take.ms/0Mr8b I am not sure what might be error for this. Environment: Vagrant Ver.2.0.0 PyCharm 2017.3.3 (Professional Edition) Build #PY-173.4301.16, built on January 11, 2018 Licensed to my name Subscription is active until May 23, 2018 For educational use only. JRE: 1.8.0_152-release-1024-b11 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.13.3
favorite count: 0
possible better answer: http://stackoverflow.com/a/65663334
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/65663334
tagged with: python
has comment: http://stackoverflow.com/comment/85267949
tagged with: pycharm
has answer: http://stackoverflow.com/a/67871071
answer count: 3
has answer: http://stackoverflow.com/a/49145426
has title: PyCharm Vagrant Couldn't refresh skeletons for remote interpreter
score: 8
tagged with: vagrant
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49145426
downvote count: 0

http://stackoverflow.com/a/49042005
answers question: http://stackoverflow.com/q/49041981
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/85089450
has body: You are almost correct, the only problem with your code is that you keep adding elements to list2. Instead, you should create a new list every time: list1 = [] for i in range(3): list2 = [] for j in range(5, 7): list2.append(j) list1.append(list2)
downvote count: 0

http://stackoverflow.com/a/49047834
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49026524
type: Answer
accepted answer of: http://stackoverflow.com/q/49026524
has body: The errors are due probably to legacy commands in the scripts. The first exemple works substituting the first instructions with splash:set_viewport_size(800, 600) splash:set_user_agent('Splash bot') The second isn't working simply because of unsure javascript evaluation with splash:evaljs not permitted under the site policy.

http://stackoverflow.com/comment/85134478
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49064275
has text: Which module should I use? Can you please point me in the right direction?
score: 0

http://stackoverflow.com/comment/85203581
score: 0
comment on: http://stackoverflow.com/q/49099147
type: QuestionComment
has text: I thrown question directly from my practice. I am not sure that whether my code is in right direction to express my problem. but simply I was expecting <Error> at 4th line . why it is not there?
type: Comment

apache-spark
tags question: http://stackoverflow.com/q/49039294
tags question: http://stackoverflow.com/q/48970822
tags question: http://stackoverflow.com/q/49046909
tags question: http://stackoverflow.com/q/49051910
tags question: http://stackoverflow.com/q/48992497
tags question: http://stackoverflow.com/q/49110803
tags question: http://stackoverflow.com/q/48994798
tags question: http://stackoverflow.com/q/49026896
tags question: http://stackoverflow.com/q/48986917
tags question: http://stackoverflow.com/q/48994810
tag name: apache-spark
tags question: http://stackoverflow.com/q/49023893
tags question: http://stackoverflow.com/q/49120835
tags question: http://stackoverflow.com/q/49103077
tags question: http://stackoverflow.com/q/49108541
tags question: http://stackoverflow.com/q/49064162
tags question: http://stackoverflow.com/q/49060960
tags question: http://stackoverflow.com/q/49120965
tags question: http://stackoverflow.com/q/48981511
tags question: http://stackoverflow.com/q/49039956
tags question: http://stackoverflow.com/q/48986212
tags question: http://stackoverflow.com/q/49098114
tags question: http://stackoverflow.com/q/48973611
tags question: http://stackoverflow.com/q/49010335
tags question: http://stackoverflow.com/q/49073915
tags question: http://stackoverflow.com/q/48979245
tags question: http://stackoverflow.com/q/49019091
tags question: http://stackoverflow.com/q/48979579
tags question: http://stackoverflow.com/q/49079133
type: Tag
tags question: http://stackoverflow.com/q/49058182
tags question: http://stackoverflow.com/q/49037621
tags question: http://stackoverflow.com/q/49020056
tags question: http://stackoverflow.com/q/49116437
tags question: http://stackoverflow.com/q/49078434
tags question: http://stackoverflow.com/q/48967987
tags question: http://stackoverflow.com/q/49064338
tags question: http://stackoverflow.com/q/49048212
tags question: http://stackoverflow.com/q/49063058

http://stackoverflow.com/a/49114342
answers question: http://stackoverflow.com/q/49113912
type: Answer
has body: It might qualify as a bug. The SysLogHandler uses self.priority_map.get(levelName, "warning") to determine the priority to send to syslog, and it appears addLevelName doesn't (or possibly cannot) update the map. As a workaround, you could update it manually: SysLogHandler.priority_names.update({ '(CC)': logging.LOG_CRIT, '(EE)': logging.LOG_ERR, # etc })
has comment: http://stackoverflow.com/comment/85234157
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/q/48999393
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48999425
has comment: http://stackoverflow.com/comment/85004314
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/52759392
has answer: http://stackoverflow.com/a/52759392
has answer: http://stackoverflow.com/a/62492862
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/48999425
tagged with: python
answer count: 4
has title: Downloading all pdf files from a url address using Python
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48999608
has body: I need to find a way to download all PDF files to be found in a given url and I found a script that supposedly accomplishes this task (I have not tested it): import urllib.parse import urllib2 import os import sys from bs4 import BeautifulSoup from urllib3 import request url = "https://...." headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"} i = 0 request = urlib2.request(url, None, headers) html = urllib2.urlopen(request) soup = BeuatifulSoup(html.read()) for tag in soup.findAll("a" , href = True) tag["href"] = urlparse.urljoin(url, tag["href"]) if os.path.splitext(os.path.basename(tag["href"]))[1] == ".pdf" current = urllib2.urlopen(tag["href"]) print("\n[*] Downloading: %s" %(os.path.basename(tag["href"]))) f = open(download_path + "\\" + os.path.basename(tag["href"], "wb")) f.write(current.read()) f.close() i += 1 print("\n[*] Downloaded %d files" %(i + 1)) raw_input("[+] Press any key to exit ... ") The problem is that I have Python 3.3 installed and this script does not run with Python 3.3. E.g. urllib2 is not available for Python 3.3. How can I amend the script to be compatible with Python 3.3?

http://stackoverflow.com/a/49103759
type: Answer
answers question: http://stackoverflow.com/q/49095187
score: 0
has body: Here's what I've done to work around this - I'm not sure if it is 'right' but it has allowed me to move forward with what I'm doing and helped me to understand a bit more of the goings on under the hood. I've created a factory methods on my Event, Competition and Match classes and a class attribute on Competition and Match that gives me access to each event type's event_type_id value: from sqlalchemy import inspect class Event(Base): __tablename__ = 'tbl_events' event_id = Column(Integer, primary_key=True) event_type_id = Column(String(50)) # 0 is Match, 1 is Competition __mapper_args__ = {'polymorphic_on': event_type_id} @classmethod def from_id(cls, id, session): mapper = inspect(cls).mapper mapper.polymorphic_map[cls.EVENT_TYPE_ID] = mapper mapper.polymorphic_identity = cls.EVENT_TYPE_ID return session.query(cls).filter_by(event_id=id).one() class Match(Event): EVENT_TYPE_ID = 0 __tablename__ = 'tbl_match_details' event_id = Column(Integer, ForeignKey('tbl_events.event_id'), primary_key=True) team_1 = Column(String(50)) team_2 = Column(String(50)) __mapper_args__ = {'polymorphic_identity': EVENT_TYPE_ID} This way, whenever classes that inherit from Match or Competition are instantiated using the factory methods, the polymorphic identity is forced to the identity defined on the parent class and the polymorphic map points that identity to the class that the factory is being called upon. A disadvantage obvious to me is that this will only work when objects are instantiated through the factory methods. Fine in this case but maybe not for all. Would appreciate any feedback on how I've gone about this and any pointers toward a cleaner solution. Thanks

http://stackoverflow.com/q/48970217
has comment: http://stackoverflow.com/comment/84945913
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/84946150
type: Question
has body: I am trying to scrape quotes from google finance's new site as the old one going to be deprecated soon. I have written some code to extract stock quotes, but it is painfully slow and takes about 2 minutes to return a single quote and returns only a few quotes every time i run the program. import urllib import re import time def get_quote(symbol): base_url = 'http://google.com/finance?q=' content = urllib.urlopen(base_url + symbol).read() m = re.search('id="ref_(.*?)"&gt;(.*?)&lt;', content) if m: quote = m.group(2) print quote,m else: quote = 'no quote available for: ' + symbol return quote while True: get_quote('AMZN') Output: 1,500.00 &lt;_sre.SRE_Match object at 0x109f66360> 1,500.00 &lt;_sre.SRE_Match object at 0x109f66360> 1,500.00 &lt;_sre.SRE_Match object at 0x109f66360> If you print variable m each time the loops, you will see that most of the time it will return value 'none' How do I fix this?
has comment: http://stackoverflow.com/comment/84945899
answer count: 1
linked to: http://stackoverflow.com/q/22657548
has comment: http://stackoverflow.com/comment/84946051
score: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84946031
has answer: http://stackoverflow.com/a/49089768
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84945932
has title: Quote scraping from google.com/finance with python

http://stackoverflow.com/q/48978640
has title: "local variable referenced before assignment" but assigning the variable is the first thing i do
has comment: http://stackoverflow.com/comment/84962291
score: 0
answer count: 2
has body: I'm in a beginner Python class and my instructor wrote pseudocode for us to follow. I've followed it to a T (I feel) and have been getting bugs no matter how I try changing the program. I'd rather have my mistake quickly pointed out than spend more time mucking about. This is written in Python 2.7.8. #Anthony Richards #25 February 2018 #This program is a simple simulation of an order-taking software. #It demonstrates multiple variables, functions, decisions, and loops. def main(): declareVariables() while keepGoing == "y": resetVariables() while moreFood == "y": print "Enter 1 for Yum Yum Burger" print "Enter 2 for Grease Yum Fries" print "Enter 3 for Soda Yum" option = input("Please enter a number: ") if option == 1: getBurger() elif option == 2: getFries() elif option == 3: getSoda() else: print "You've made an incorrect entry. Please try again." moreFood = raw_input("Would you like to order anything else? (y/n): ") calcTotal(totalBurger, totalFries, totalSoda) printReceipt(total) keepGoing = raw_input("Would you like to place another order? (y/n): ") def declareVariables(): keepGoing = "y" moreFood = "y" totalBurger = 0 totalFries = 0 totalSoda = 0 subtotal = 0 tax = 0 total = 0 option = 0 burgerCount = 0 fryCount = 0 sodaCount = 0 def resetVariables(): totalBurger = 0 totalFries = 0 totalSoda = 0 total = 0 tax = 0 def getBurger(totalBurger): burgerCount = input("Please enter the number of burgers: ") totalBurger = totalBurger + burgerCount * .99 def getFries(totalFries): fryCount = input("Please enter the number of fry orders: ") totalFries = totalFries + fryCount * .79 def getSoda(totalSoda): sodaCount = input("Please enter the number of drinks: ") totalSoda = totalSoda + sodaCount * 1.09 def calcTotal(totalBurger, totalFries, totalSoda): subtotal = totalBurger + totalFries + totalSoda tax = subtotal * .06 total = subtotal + tax def printReceipt(total): print "Your total is $"+str(total) main()
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48978675
tagged with: local-variables
has answer: http://stackoverflow.com/a/48978662
type: Question

http://stackoverflow.com/comment/85206471
type: QuestionComment
comment on: http://stackoverflow.com/q/49100622
score: 0
has text: Seems you just need to remove `plt.show()` in between the plotting commands.
type: Comment

http://stackoverflow.com/comment/84955085
comment on: http://stackoverflow.com/a/48975110
has text: Thanks so mutch , ok i understand , one row is one document in the collection. one unique doc id. What a shitty mistake sorry
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49035253
answer count: 2
has answer: http://stackoverflow.com/a/49035305
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85075723
accepted answer: http://stackoverflow.com/a/49035305
possible better answer: http://stackoverflow.com/a/49035295
tagged with: python
has title: Why are the results of StringMethods comparisons not automatically converted to boolean array?
has answer: http://stackoverflow.com/a/49035295
type: AnsweredQuestion
type: Question
has body: I was testing my dataset and was trying to compare strings using pandas StringMethods and discovered that I cannot compare boolean array generated by the StringMethods with another boolean array unless saving it to the variable import pandas as pd df = pd.DataFrame([{"pet":"cat", "gender":"M"}, {"pet":"Cat", "gender":"M"}, {"pet":"dog", "gender":"F"}]) result = df[df.gender== "M" &amp; df.pet.str.lower() == "cat"] # TypeError: cannot compare a dtyped [object] array with a scalar of type [bool] But when saving it to a variable before using binary operators it seems to work. first = df.gender == "M" second = df.pet.str.lower() == "cat" df[(first) &amp; (second)] # gender pet # 0 M cat # 1 M Cat Based on the error message, df.pet.str.lower() == "cat" isn't converted to a boolean array until I save them to the variable. Why are the results of StringMethods comparisons not automatically converted to boolean array?

http://stackoverflow.com/q/49000860
type: AnsweredQuestion
score: 1
has title: Python Pygame, image has white background even if it's PNG and I did not designate white background
tagged with: image
upvote count: 2
answer count: 1
has body: I am building a silly game in Python using Pygame. I have a cat that poops. And in a previous version these poops had a transparent background. So I want to make my poops in a class for clarity of mind and control. And now my poops have a white background... I am at a loss to why this is happening. The images are PNG The images are of type surface and use 32 depth which allows for transparency. Here is a link to my https://github.com/ironsketch/catPoop/blob/cat3.0/catNewGame.py
favorite count: 0
tagged with: transparency
tagged with: python
tagged with: pygame
tagged with: http://stackoverflow.com/tag/png
has answer: http://stackoverflow.com/a/49001144
accepted answer: http://stackoverflow.com/a/49001144
has comment: http://stackoverflow.com/comment/85007239
downvote count: 1
type: Question

http://stackoverflow.com/q/49109340
tagged with: formula
has answer: http://stackoverflow.com/a/49109975
answer count: 1
accepted answer: http://stackoverflow.com/a/49109975
downvote count: 0
tagged with: renpy
favorite count: 0
tagged with: zooming
tagged with: python
has title: Simple zoom formula
tagged with: playing-cards
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I'm making a cards game in python language. I need a formula to zooming the cards in screen. I put the following formula by now: zoom=(NumberOfCards*0.042857) This formula get a zoom factor of 0.3 for Number=7. This is the standard for the first hand. Now the number of cards can increase of decrease and the hand should fit into screen accordingly. Now I want to improve the formula to: If Number&lt;7 -> Keep the zoom the same (because cards can fit in screen) If Number from 7 to 54 decrease the zoom slightly (or even keep to 0.3 til a higher number because could fit in screen). The screen is 1280x720. The 54 cards are saved 600x868 in png format (zoomed to 0.3 factor: 180x260.4 overlapped as you can see in the capture) How should be the formula? I'm weak at maths, hahaha. Thanks in advance. :-)
type: Question

http://stackoverflow.com/comment/85216738
has text: @evilSnobu but i am not able to figure out why the app name is required. Even the heroku docs say that no app name is required.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49105888

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/49111504

http://stackoverflow.com/comment/92814724
has text: I used the 3.5 version for conda 3.7 and it worked fine by renaming the file. Thanks. You might want to set permissions like the other files in the directory.
type: Comment
comment on: http://stackoverflow.com/a/49597001
score: 1
type: AnswerComment

http://stackoverflow.com/a/48986919
has body: import numpy as np unique, counts = np.unique(a, return_counts=True) idx = tuple(zip(unique, counts)) I think this will work for you.
downvote count: 2
answers question: http://stackoverflow.com/q/48986755
score: -2
has comment: http://stackoverflow.com/comment/84978630
upvote count: 0
has comment: http://stackoverflow.com/comment/84978687
type: Answer

http://stackoverflow.com/comment/85080153
comment on: http://stackoverflow.com/a/49022451
type: AnswerComment
has text: @kinderchan What do you mean change them?
score: 0
type: Comment

http://stackoverflow.com/comment/85232496
type: QuestionComment
comment on: http://stackoverflow.com/q/49113572
has text: It does... However, if I return edited_line outside of this loop it just returns the last line.
score: 0
type: Comment

http://stackoverflow.com/q/49121365
accepted answer: http://stackoverflow.com/a/49121508
downvote count: 0
has comment: http://stackoverflow.com/comment/85248274
score: 24
has body: How do I implement a retry count of 5 times, 10 seconds apart when sending a POST request using the requests package. I have found plenty of examples for GET requests, just not post. This is what I am working with at the moment, sometimes I get a 503 error. I just need to implement a retry if I get a bad response HTTP code. for x in final_payload: post_response = requests.post(url=endpoint, data=json.dumps(x), headers=headers) #Email me the error if str(post_response.status_code) not in ["201","200"]: email(str(post_response.status_code))
possible better answer: http://stackoverflow.com/a/54356575
favorite count: 0
tagged with: python-3.x
has title: Implementing retry for requests in Python
has answer: http://stackoverflow.com/a/54356575
has comment: http://stackoverflow.com/comment/85248407
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49121508
tagged with: python-requests
linked to: http://stackoverflow.com/q/474528
upvote count: 24
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85248298

http://stackoverflow.com/comment/85110526
type: Comment
comment on: http://stackoverflow.com/a/49052759
type: AnswerComment
has text: thanks, i'm not used to python, how would i able able to run that script if you could help?
score: 0

http://stackoverflow.com/q/48977734
favorite count: 0
type: UnansweredQuestion
tagged with: amazon-dynamodb
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49519780
has comment: http://stackoverflow.com/comment/84960636
score: 1
has body: It works fine on my local machine with .aws configured. However, lambda is unable to connect with the dynamodb tables through the auto-generated iam role. I even tried adding a policy explicitly to the role via IAM console: { "Sid": "VisualEditor1", "Effect": "Allow", "Action": "dynamodb:*", "Resource": "arn:aws:dynamodb:ap-south-1:*:table/*" } But still getting this error (Debug Logs): An error occurred (AccessDeniedException) on request (SQ60ECK3UMM6LLEBC2K04S6HE7VV4KQNSO5AEMVJF66Q9ASUAAJG) on table (lmk_staging_posts) when calling the DescribeTable operation: 2018-02-26 00:11:18.723000 3ca1b0 [DEBUG] 2018-02-25T18:41:18.722Z Calling DescribeTable with arguments {'TableName': 'lmk_staging_posts'} 2018-02-26 00:19:16.045000 5e175a [DEBUG] 2018-02-25T18:49:16.45Z Calling DescribeTable with arguments {'TableName': 'lmk_staging_posts'} 2018-02-26 00:19:16.110000 5e175a [DEBUG] 2018-02-25T18:49:16.110Z Calling DescribeTable with arguments {'TableName': 'lmk_staging_comments'} 2018-02-26 00:19:16.157000 5e175a [DEBUG] 2018-02-25T18:49:16.157Z Calling DescribeTable with arguments {'TableName': 'lmk_staging_groups'} 2018-02-26 00:19:16.200000 5e175a [DEBUG] 2018-02-25T18:49:16.199Z Calling DescribeTable with arguments {'TableName': 'lmk_staging_user_profile'}
tagged with: chalice
answer count: 1
downvote count: 0
tagged with: amazon-web-services
has title: Chalice: Unable to connect with DynamoDB through pynamodb
tagged with: python

http://stackoverflow.com/comment/84997926
type: Comment
comment on: http://stackoverflow.com/a/48996036
score: 0
type: AnswerComment
has text: You don't have to have an access. Google ML use Tensorflow so technically the problem is "reading HDF5 files in Tensorflow". At least I guess so. Anyway, I think I'm going to create one huge CSV file instead of several thousand files, I think that'll be easier.

http://stackoverflow.com/q/48995329
possible better answer: http://stackoverflow.com/a/48995417
has answer: http://stackoverflow.com/a/48995404
has answer: http://stackoverflow.com/a/48995417
tagged with: python
has title: Efficient way in pandas to do an operation that requires access multiple rows
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48995404
linked to: http://stackoverflow.com/q/20109391
has body: Is there an efficient way to update each individual row in a DataFrame with values from the row below it in sequence? The DataFrame contains a sequence of positions to which a vehicle travelled in order. I've added two new columns next_x and next_y, and want to populate those columns, by row, with the values in the current_x and current_y column from the row directly beneath. The idea being each row will then contain pairs of coordinates describing a position, and the next position a vehicle travelled. This is working using iterrows but is prohibitively slow over the full dataset. for index, row in df.iterrows(): if int(index) &lt; len(df)-1: df['next_x'].iloc[int(index)] = df['current_x'].iloc[(int(index)+1)] df['next_y'].iloc[int(index)] = df['current_y'].iloc[(int(index)+1)] I can't figure out a good way to use apply - am I missing something?
type: Question
answer count: 2
tagged with: dataframe
tagged with: rows
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84996068

http://stackoverflow.com/tag/gif
tags question: http://stackoverflow.com/q/49016760
tags question: http://stackoverflow.com/q/49011601
tag name: gif
tags question: http://stackoverflow.com/q/49086447
type: Tag

http://stackoverflow.com/q/49077885
tagged with: python-3.x
tagged with: python
tagged with: merge
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/49078073
has body: I have two dataframes: df1: contains all information rowname a b c d R1 1 2 0 1 R2 2 2 0 1 R3 0 2 0 0 R4 1 2 0 1 df2: contains a subset of the rows and columns: rowname a b c R1 1 2 0 R2 2 2 0 R4 1 2 0 I want to filter out all the rows df2 that are not in df1. So for this case, I'm looking to get rid of R3 in df1 while keeping all columns. I think using df1.merge(df2, ...) could work to make this happen, but I've tried a variety of arguments with no success. I'm using python3.
accepted answer: http://stackoverflow.com/a/49078061
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/49078073
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/49078061
has title: Pandas dataframe in python: Removing rows from df1 based on rows in df2
favorite count: 0

http://stackoverflow.com/a/59436807
score: 1
upvote count: 1
has body: I meet the same question with using the Traci4J. If you want to use Traas, I can give you some tips. You could find the WebService class here: traas/src/main/java/de/tudresden/ws/WebService.java This is an executable java file. Then you will get a running server. If you create a web service client, you could connect with the traas server and do the simulation with sumo. Btw I still have some doubt that the api of traas is less than the api for python and C++; Here is a small demo, supposing that you have already imported the traas.jar; public class MyWebService { public static void main(String[] args) { Config.config_file = "resources/map.sumo.cfg"; de.tudresden.ws.WebService.main(new String[]{}); } } The web service client: public class HelloWorldClient { public static TraasWSLocator locator; public static ServiceImpl service; static { try { locator = new TraasWSLocator(); service = locator.getServiceImplPort(); } catch (Exception e){ e.printStackTrace(); } } public static void main(String[] argv) throws RemoteException{ service.setSumoBinary("sumo-gui"); service.start("username"); while (service.simulation_getMinExpectedNumber()&gt;0){ service.doTimestep(); } } }
answers question: http://stackoverflow.com/q/49041071
downvote count: 0
type: Answer

http://stackoverflow.com/q/48989472
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48990066
downvote count: 2
has body: How we can perform mathematical operation on string in python. Consider below example with open('/home/akashk/projects/math.txt') as f: content = f.readlines() content = [x.strip() for x in content] for x in content: print(x) print(type(x)) output is like 1abc0+5*1hv0 I want to perform operation using operand and operators above should be considered as 10+5*10 = 60 In short remove characters and perform mathematical operation on operands. eval('10+5*10') which gives 60 but it will not handle characters.
has title: How to perform math operation on numbers in string of python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84983534
score: -2
linked to: http://stackoverflow.com/q/2371436
type: Question
tagged with: operation
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/48990066
possible better answer: http://stackoverflow.com/a/48989568
tagged with: string
has answer: http://stackoverflow.com/a/48989568
has comment: http://stackoverflow.com/comment/84983556
tagged with: python
favorite count: 0

http://stackoverflow.com/q/48979450
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49090724
tagged with: sqlalchemy
type: Question
answer count: 2
upvote count: 12
downvote count: 0
score: 12
has body: I have an Order - FoodItem Many-To-Many relationship that is as follows: association_table = db.Table('association', db.Model.metadata, db.Column('left_id', db.Integer, db.ForeignKey('orders.order_id')), db.Column('right_id', db.Integer, db.ForeignKey('fooditems.fooditem_id')) ) class OrderModel(ReviewableModel): __tablename__ = 'orders' order_id = db.Column(db.Integer, db.ForeignKey('reviewables.id'), primary_key=True) food_items = db.relationship("FoodItemModel", secondary = association_table) __mapper_args__ = {'polymorphic_identity':'orders'} class FoodItemModel(ReviewableModel): __tablename__ = 'fooditems' fooditem_id = db.Column(db.Integer, db.ForeignKey('reviewables.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity':'fooditems'} The user can request an order with duplicate foodItems. This is created properly, but when I save the changes to the database, the duplicates are removed. For e.g., I order 3 Pizzas: def save_to_db(self): print('before: '+str(self.food_items)) db.session.add(self) db.session.commit() print('after: '+str(self.food_items)) The output is like this: before: [&lt;FoodItemModel u'Pizza'&gt;, &lt;FoodItemModel u'Pizza'&gt;, &lt;FoodItemModel u'Pizza'&gt;] after: [&lt;FoodItemModel u'Pizza'&gt;] The association table is updated properly: "left_id" "right_id" "6" "3" "6" "3" "6" "3" However, the food_items in the OrderModel only contains 1 item
has title: Flask-SqlAlchemy Many-To-Many relationship with duplicates allowed
favorite count: 0
has answer: http://stackoverflow.com/a/49031036

http://stackoverflow.com/comment/84958004
score: 0
type: Comment
type: QuestionComment
has text: @Lou Do you just have three function calls hardcoded like that, or do you have a list with functions of unknown size?
comment on: http://stackoverflow.com/q/48976431

http://stackoverflow.com/a/49002484
type: AcceptedAnswer
downvote count: 0
has body: This might help. a = [["a","b","c"],["d","e","f"]] b = [["g","h","i"],["k","l","m"],["n","o","c"]] check = [i[2] for i in a] print([i for i in b if i[2] not in check]) Output: [['g', 'h', 'i'], ['k', 'l', 'm']]
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49002409
answers question: http://stackoverflow.com/q/49002409

http://stackoverflow.com/comment/95454251
comment on: http://stackoverflow.com/q/49064144
type: Comment
score: 1
has text: @sangeethasivakumar were you able to get an answer to this ?
type: QuestionComment

http://stackoverflow.com/q/48998105
answer count: 1
has body: I have a list of addresses that are street names in a US city. I want to turn them into GoogleV3 location objects. I seem to have trouble restricting to a city, and can't find any solid examples of how to go about doing so in Python. For example, Columbus Avenue is in Derwood, MD. However the following line of code: from geopy import geocoders from geopy.geocoders import GoogleV3 gmaps = GoogleV3(api_key=MY_KEY) gmaps.geocode('Columbus Avenue', components = {'country':'US','postal_code_prefix':'20','region':'MD'}, timeout=15) returns Location(9th Ave, New York, NY, USA, (40.76921230000001, -73.9847724, 0.0)) How can I restrict the geocode command to search only for places near to Derwood?
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
upvote count: 0
score: -1
tagged with: google-maps-api-3
has title: Restrict geocode from GoogleMaps API to a city?
has answer: http://stackoverflow.com/a/49004572

http://stackoverflow.com/comment/85095242
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49045301
has text: Thank you, but when I tried to timeit it was actually slower @jezrael
score: 0

http://stackoverflow.com/comment/85138055
comment on: http://stackoverflow.com/q/49066476
has text: Deleting `__init__` doesn't make a difference, you get the error either way.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49030430
score: 0
answer count: 1
tagged with: neo4j
tagged with: py2neo
tagged with: python
has answer: http://stackoverflow.com/a/49031094
accepted answer: http://stackoverflow.com/a/49031094
has title: how to use graph.pull in py2neo?
type: AnsweredQuestion
type: Question
has body: in my code, i use py2neo to create objects with the label foobar. If i want to pull some of them out of the database, it returns: None code (note that there are already foobar objects in the DB): class foobar(GraphObject): __primarykey__ = "name" name = Property() #... graph initialized etc. foo = foobar() foo.name = "bar" foo = graph.pull(foo) #get all foobar data from graph print(foo) None

http://stackoverflow.com/q/48990047
has body: I wanna have that V_old takes on the values of V after a complete loop over j_now. However, V_old takes on the Values of V directly after each j_now iteration and therefore I get wrong values because the new V_old value is always part of the new maximum and so on. for i_iter in range(0,5): for j_now in range(0, 400): V[j_now] = np.max(matrix_M[:,j_now] + beta * V_old) V_old = V Would be great if sb. could help me! Cheers, Tobias
tagged with: for-loop
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48990237
tagged with: python
has title: Python: Appoint vector values after each loop but not for each iteration
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/85242132
comment on: http://stackoverflow.com/a/49059794
score: 0
type: AnswerComment
type: Comment
has text: The issue discussed in the above comments was a result of me neglecting to preface the `df.sort_values()` call with `df =`, and the sorting doesn't happen in place by default, so the sorted values went away since they weren't assigned back into the `df` variable.

http://stackoverflow.com/comment/84954092
type: Comment
has text: if you look through my post, you can see I already tried that to no avail
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48972055

http://stackoverflow.com/comment/85059324
has text: https://stackoverflow.com/help/how-to-ask
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49027382

http://stackoverflow.com/a/49122598
answers question: http://stackoverflow.com/q/49098606
score: 0
has body: Okay, so i'm not sure if this is the perfect way to do this, but it appears to be working. I created a variable 'favorite' to grab the selected item and then then saved in the user object. def favorite(request, pk): if request.method == 'POST': favorite = Deal.objects.get(pk=pk) user = request.user user.favorites.add(favorite) messages.add_message(request, messages.INFO, 'Deal Favorited.') return redirect('home')
type: Answer

http://stackoverflow.com/a/48978171
score: 0
type: AcceptedAnswer
has body: You could try something like this: dict(sorted(zip(sorrend,sms))).values() For your shortened example: &gt;&gt;&gt; sms=['love', 'I', 'much', 'so', 'you'] &gt;&gt;&gt; sorrend=[2,1,5,4,3] &gt;&gt;&gt; ' '.join(dict(sorted(zip(sorrend,sms))).values()) 'I love you so much'
type: Answer
accepted answer of: http://stackoverflow.com/q/48977951
answers question: http://stackoverflow.com/q/48977951

http://stackoverflow.com/q/49029687
has comment: http://stackoverflow.com/comment/85064698
score: 0
has body: I have videostreams and I'd like to convert them to foreground detected videos on which everything is white that moving and all others are black. When I run this below script nothing happens, python ide just waits. Should I wait, does the video render or do i make something wrong? Thanks import cv2 import numpy cap = cv2.VideoCapture('2018_02_28_12_07_42.h264') fgbg = cv2.createBackgroundSubtractorMOG2() fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) #while(cap.isOpened()): while True: ret, frame = cap.read() #if ret == True: fgmask = fgbg.apply(frame) out.write(frame) cv2.imshow('original', frame) cv2.imshow('fg', fgmask) k = cv2.waitKey(30) &amp; 0xff if k == 27: break cap.release() out.release() cv2.destroyWindows()
has comment: http://stackoverflow.com/comment/85063686
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: can't save video file in opencv
tagged with: opencv
has comment: http://stackoverflow.com/comment/85063820
has comment: http://stackoverflow.com/comment/85064197
type: Question

http://stackoverflow.com/comment/85100300
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49032819
has text: Typically, your *.dll*'s `DllMain` is returning **0**. You have the code, so you can check why. Probably an *OS* version conditional right inside the func?

http://stackoverflow.com/a/49057486
score: 1
answers question: http://stackoverflow.com/q/49039734
has comment: http://stackoverflow.com/comment/85155235
downvote count: 0
has body: Time Delay in Above Solution @MaxU's solution adding isolation_level=None to the database connection is short and sweet. For whichever reason, however, it slowed writing/committing each chunk to the database dramatically. For example, when I tested the solution on a table of 12 million rows, the code took over 6 hours to complete. Conversely, building the original table from several text files took a few minutes. This insight led to a faster but less elegant solution, which took less than 7 minutes to complete on a table of 12 million rows versus over 6 hours. The output rows matched the input rows, solving the problem in my original question. Faster but less Elegant Solution Since constructing the original table from text files/csv files and using SQL scripts to load the data, I combined that approach with Panda's chunk capabilities. The essential basic steps are as follows: Connect to the db Use a SQL script to create a new table (columns and order should match whatever you do to the pandas df) Read the massive table in chunks For each chunk, modify the df as desired, write to csv, load csv using sql, and commit the change. Main code of solution: import pandas as pd import sqlite3 #Note I Used Functions I Wrote in build_db.py #(shown below after example solution) from build_db import * #Helper Functions Used in Example def lower_var(var, df): s = df[var].str.lower() df = df.drop(var, axis=1) df = pd.concat([df, s], axis=1) return(df) #Connect to Data db = sqlite3.connect("test.db") c = db.cursor() #create statement create_table(c, "create_test.sql", path='sql_clean/') #Load Data in Chunks df_generator = pd.read_sql_query("select * from example_table;", con=db, chunksize = 100000) for df in df_generator: #functions to modify data, example df = lower_var("name", df) #changes column order #restore df to column order in sql table db_order = ["cmte_id", "amndt_ind", "rpt_tp", "transaction_pgi", "image_num", "transaction_tp", \ "entity_tp", "name", "city", "state", "zip…
upvote count: 1
type: Answer

http://stackoverflow.com/a/48972144
upvote count: 7
answers question: http://stackoverflow.com/q/48972115
downvote count: 1
has body: First install a module using pip Open Cmd write command pip install pycrypto (It require installation of Microsoft Visual C++ 14.0) Then use it in your code as you use in your code above
score: 6
has comment: http://stackoverflow.com/comment/105728627
type: Answer

http://stackoverflow.com/comment/106701273
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48994132
has text: Where this farm.animals().insert came from?
type: AnswerComment

http://stackoverflow.com/q/49014885
has body: Suppose that I have following code: import tensorflow as tf with tf.variable_scope('Embedding'): embd = tf.get_variable('embedding_matrix', [100, 10], dtype = tf.float32) And I want to reuse the tensor with name embedding_matrix within new scope: with tf.variable_scope('not_related'): with tf.variable_scope('Embedding', reuse = True) as scope: # I want the name of 'call_embd' be 'Embedding/embedding_matrix # but not 'not_related/Embedding/embedding_matrix' call_embd = tf.get_variable('embedding_matrix') Any way to let call_embd has name Embedding/embedding_matrix ?
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85035645
upvote count: 1
linked to: http://stackoverflow.com/q/35919020
answer count: 1
has comment: http://stackoverflow.com/comment/85037236
has answer: http://stackoverflow.com/a/49031462
has title: Any way not to inherit parent variable_scope?

http://stackoverflow.com/a/49029573
score: 1
has body: you can use it Reset
answers question: http://stackoverflow.com/q/49015686
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/49083120
has answer: http://stackoverflow.com/a/49324478
has comment: http://stackoverflow.com/comment/85171967
linked to: http://stackoverflow.com/q/7534622
has comment: http://stackoverflow.com/comment/85171452
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85171758
linked to: http://stackoverflow.com/q/40458138
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/85171724
has comment: http://stackoverflow.com/comment/85775725
has title: how to extract openload link from a website using selenium in python
has body: I have been trying to extract the src which is a openload link from a website. The src is loacted in iframe which is loaded dynamically. the website is "https://www1.fmovies.se/film/daddys-home-2.kk29w". Now The problem is that iframe is loaded dynamically. So this is my code from selenium import webdriver driver=webdriver.Chrome('C:\\Users\\aman krishna\Desktop\\New folder(3)\chromedriver.exe') driver.get("https://bmovies.to/film/daddys-home-2.kk29w/78vp5j") driver.find_element_by_xpath("//iframe[contains(@src,'&lt;https://openload.co/embed/qe3n5GZGyGo/?autostart=true')]")
score: 0
type: Question

http://stackoverflow.com/comment/85123368
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49059108
has text: The code above returns a different error, please _verify_ the code.

http://stackoverflow.com/q/49078434
has title: does spark have the ability to parallise regular python function
score: 0
tagged with: apache-spark
has body: can I use spark to do a regular python job in parallel? for example: def my_f(mylist1, mylist2): #sophisticated stuff return map(lambda x: x + 1, mylist1) mylist3 = my_f(xrange(10), xrange(5)) #pass my list to a spark rdd for further processing The reason im asking is because in my pipeline I need to use a sklearn model on 2 arrays and I want to take those output for further manipulation in spark
has comment: http://stackoverflow.com/comment/85166301
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85173601
answer count: 0
type: Question
tagged with: pyspark

http://stackoverflow.com/q/49046501
upvote count: 2
has answer: http://stackoverflow.com/a/49046779
has body: I want to find an instance of a class, where an attribute has a certain value: import numpy as np import inspect import matplotlib.pyplot as plt class Frame(): def __init__(self, img, idx): self.image = img self.idx = idx for i in range(10): img = np.random.randint(0, high=255, size=(720, 1280, 3), dtype=np.uint8) # generate a random, noisy image Frame(img, i) # Pseudo Code below: frame = inspect.getmembers(Frame, idx=5) # find an instance of a class where the index is equal to 5 plt.imshow(frame.img)
type: Question
has comment: http://stackoverflow.com/comment/85097558
has comment: http://stackoverflow.com/comment/85097526
possible better answer: http://stackoverflow.com/a/49046779
has comment: http://stackoverflow.com/comment/85097501
tagged with: class
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85097497
has comment: http://stackoverflow.com/comment/85097555
favorite count: 0
has answer: http://stackoverflow.com/a/49046596
has title: Python - Find an instance of a class, based on a value of an attribute
tagged with: python
has comment: http://stackoverflow.com/comment/85097638
accepted answer: http://stackoverflow.com/a/49046596
linked to: http://stackoverflow.com/q/328851
has comment: http://stackoverflow.com/comment/85097572
type: AnsweredQuestion
score: 2
tagged with: instance

http://stackoverflow.com/a/49102974
has comment: http://stackoverflow.com/comment/85216706
type: Answer
has comment: http://stackoverflow.com/comment/85216762
has body: No. CV is just for checking the performance of model on a data (or rather different parts of it) When you call fit(), it will fit the whole data supplied at the time whereas cross-validation only uses parts of the data (leaving 1 fold in each iteration). So this data difference may cause the estimator to perform better or worse.
answers question: http://stackoverflow.com/q/49098155
score: 0
has comment: http://stackoverflow.com/comment/85216432

http://stackoverflow.com/comment/85061007
type: QuestionComment
has text: Is there a way to attach the .csv file here?
score: 0
comment on: http://stackoverflow.com/q/49028239
type: Comment

http://stackoverflow.com/a/49112166
answers question: http://stackoverflow.com/q/49111696
accepted answer of: http://stackoverflow.com/q/49111696
score: 0
has body: You could replace this part : fields = data["fields"] sentence="create table "+data["name"]+" if not exist(" for field in fields: if isinstance(field["type"],list): sentence += str(field["name"])+" "+ str(field["type"][-1])+" ," else: sentence += str(field["name"])+" "+ str(field["type"])+" ," sentence=sentence[0:-1]+")" With something a little bit more python like : sentence="create table {name} if not exist({fields})".format( name = data["name"], fields = ', '.join(i["name"]+" "+i["type"] if not isinstance(i["type"],list) else i["name"]+" "+i["type"][-1] for i in data["fields"]) )
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49002506
favorite count: 0
has body: I am looking to plot a network graph using the networkx package in python. The problem I am facing is that the customizations that I'm making are not taking place and the defaults values(probably) are getting used instead. The code I am using is below. It looks lengthy but it most of it setting up the data. import pandas as pd import networkx as NX from matplotlib import pyplot as plt import numpy as np import pygraphviz as PG # the dataframeI'm using corr_mat_2 = pd.DataFrame.from_dict({'clump_thickness': {'clump_thickness': 0.0, 'cell_size_uniformity': 0.0, 'cell_shape_uniformity': 0.0, 'marginal_adhesion': 0.0, 'epithelial_cell_size': 0.0, 'bare_nuclei': 0.0, 'bland_chromatin': 0.0, 'normal_nucleoli': 0.0, 'mitoses': -0.5790403219346321}, 'cell_size_uniformity': {'clump_thickness': 0.0, 'cell_size_uniformity': 0.0, 'cell_shape_uniformity': 0.9490385801487778, 'marginal_adhesion': 0.0, 'epithelial_cell_size': 0.5726586033292179, 'bare_nuclei': 0.0, 'bland_chromatin': 0.6533249167391942, 'normal_nucleoli': 0.5106708697857533, 'mitoses': -0.5473028893162575}, 'cell_shape_uniformity': {'clump_thickness': 0.0, 'cell_size_uniformity': 0.9490385801487778, 'cell_shape_uniformity': 0.0, 'marginal_adhesion': 0.0, 'epithelial_cell_size': 0.502767944815973, 'bare_nuclei': 0.5261228487320817, 'bland_chromatin': 0.631017333346977, 'normal_nucleoli': 0.5115973333620983, 'mitoses': -0.5850744184472585}, 'marginal_adhesion': {'clump_thickness': 0.0, 'cell_size_uniformity': 0.0, 'cell_shape_uniformity': 0.0, 'marginal_adhesion': 0.0, 'epithelial_cell_size': 0.0, 'bare_nuclei': 0.0, 'bland_chromatin': 0.0, 'normal_nucleoli': 0.0, 'mitoses': 0.0}, 'epithelial_cell_size': {'clump_thickness': 0.0, 'cell_size_uniformity': 0.5726586033292179, 'cell_shape_uniformity': 0.502767944815973, 'marginal_adhesion': 0.0, 'epithelial_cell_size': 0.0, 'bare_nuclei': 0.0, 'bland_chromatin': 0.0, 'normal_nucleoli': 0.0, 'mitoses': 0.0}, 'bare_nuclei': {'clump_thickness': 0.0, 'cell_size_uniformity': …
has answer: http://stackoverflow.com/a/49005713
accepted answer: http://stackoverflow.com/a/49005713
tagged with: python
has comment: http://stackoverflow.com/comment/85012209
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85011376
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/28533111
type: Question
tagged with: networkx
has title: Networkx customizations not working
has comment: http://stackoverflow.com/comment/85011393
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/84942603
type: Comment
comment on: http://stackoverflow.com/a/48968153
score: 0
type: AnswerComment
has text: quadratic algorithm here... Note, avoiding that is precisely the reason that `sum(['a','b','c'], '')` raises an error: `TypeError: sum() can't sum strings [use ''.join(seq) instead]`

http://stackoverflow.com/comment/85014396
comment on: http://stackoverflow.com/q/49003764
score: 0
type: Comment
type: QuestionComment
has text: That site seems to be using cookies to select the city, you will need to send more POST requests specifying the cookie parameter

http://stackoverflow.com/q/48986387
score: 1
favorite count: 0
type: Question
tagged with: python
has title: Right margin seaborn joint plot disappears when adding regression line
linked to: http://stackoverflow.com/q/48947656
has comment: http://stackoverflow.com/comment/84977667
has comment: http://stackoverflow.com/comment/84978364
tagged with: seaborn
has comment: http://stackoverflow.com/comment/84977858
upvote count: 1
has comment: http://stackoverflow.com/comment/85097428
has comment: http://stackoverflow.com/comment/84978590
tagged with: matplotlib
type: UnansweredQuestion
has body: Using the tips I got from this question, I'm able to put a regression line on top of a seaborn jointplot. The following snippet creates the plot below: Code 1 import numpy as np import pandas as pd import seaborn as sns sns.set(style="white") # Generate a random correlated bivariate dataset rs = np.random.RandomState(5) mean = [0, 0] cov = [(1, .5), (.5, 1)] x1, x2 = rs.multivariate_normal(mean, cov, 500).T x1 = pd.Series(x1, name="$X_1$") x2 = pd.Series(x2, name="$X_2$") # Show the joint distribution using kernel density estimation g = sns.jointplot(x1, x2, kind="kde", size=7, space=0) sns.regplot(x1,x2, scatter=False, ax=g.ax_joint) Plot 1a Adding sns.regplot(x1,x2, scatter=False, ax=g.ax_joint) to the mix will render this plot: Plot 1b And that is exactly what I'm trying to accomplish. However, when I'm using the same code on some real world data, I'm getting some really weird results with regards to the distribution plot in the right margin. Let's just call the two series A and B. Code 2: A = pd.Series([2197.0,2207.0,2016.0,1993.0,2126.0,2507.0,3123.0,3632.0,3504.0,3515.0,3394.0,3222.0,3167.0,3071.0,2847.0,2776.0,2878.0,2946.0,3051.0,3021.0,2983.0,3044.0,2951.0,2781.0,2434.0]) B = pd.Series([34.0,159.0,-48.0,-134.0,-229.0,-73.0,31.0,-65.0,261.0,616.0,481.0,544.0,360.0,414.0,359.0,142.0,117.0,173.0,115.0,-36.0,-15.0,105.0,316.0,-30.0,-137.0]) g = sns.jointplot(A, B, kind="kde", size=7, space=0) sns.regplot(A,B, scatter=False, ax=g.ax_joint) Plot 2 I think this is pretty strange in itself, bacuse there's nothing about the properties of the B series that could explain this result. You can verify this by changing the order of the series like this: Code 3: g = sns.jointplot(B, A, kind="kde", size=7, space=0) sns.regplot(B, A, scatter=False, ax=g.ax_joint) Plot 3: As you can see, it's still the distribution plot in the right margin that's the problem here, and not the data in itself. And just to double check, you can see that you would still get the correct margin plo…
answer count: 0
downvote count: 0

http://stackoverflow.com/q/49040487
has body: I am writing a function that takes 3 inputs, if all 3 inputs are floats and/or integers it returns the average of the 3, otherwise it returns them as a list. This is what I have: def list3(a,b,c): """if all inputs are int/float return average""" l = [a, b, c] for t in l: if t is int or t is float: s = sum(l) y = len(l) x = float(s/y) return x else: return(l) when I input 3 integers it returns the list, how can I get it to recognize the input as integers? Thanks
tagged with: list
has comment: http://stackoverflow.com/comment/85086374
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/55365929
tagged with: numbers
has title: Python function not recognizing integers
tagged with: int
upvote count: 2
score: 0
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/49040554
has comment: http://stackoverflow.com/comment/85087805
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49040511

http://stackoverflow.com/q/49075760
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85157537
tagged with: tensorflow
type: Question
tagged with: conv-neural-network
has title: Keras does not work when using 10 epochs
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85157613
has body: This is absolutely bizarre, but when I run my Keras CNN model using 10 epochs, each epoch (including the first one) gives me a .333 accuracy (I have 3 categorical classes.) Using any other number of epochs seems to work fine, giving me ~.55 accuracy after the first epoch and continuing to grow to ~.9 accuracy. The model is defined as follows: import os from keras.models import Sequential from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten, Activation, GlobalMaxPooling2D, PReLU, LeakyReLU from keras.layers.core import Flatten, Dense, Dropout from keras.layers.convolutional import MaxPooling2D from keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt input_shape = (405, 270, 3) batch_size = 16 epochs = 15 # training_directory = os.getcwd() + '\DataSubset\TrainImages' # test_directory = os.getcwd() + '\DataSubset\TestImages' # num_classes = 70 # train_samples = 27992 # test_samples = 7000 training_directory = os.getcwd() + '\SmallDataSubset\TrainImages' test_directory = os.getcwd() + '\SmallDataSubset\TestImages' num_classes = 3 train_samples = 9578 test_samples = 2415 target_shape = (405, 270) train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) train_generator = train_datagen.flow_from_directory(training_directory, target_size=target_shape, batch_size=batch_size) test_generator = ImageDataGenerator(rescale=1./255).flow_from_directory(test_directory, target_size=target_shape, batch_size=batch_size) def create_short_model(): model = Sequential() model.add(Conv2D(128, (3, 3), padding='same', activation='relu', input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (3, 3), padding='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(256, (3, 3), padding='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(256, (3, 3), padding='same', activation='relu')) model.add(Ma…
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/q/49063951
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85133169
tagged with: python
has answer: http://stackoverflow.com/a/49063973
score: 2
upvote count: 2
has title: Printing index from a Pandas series
type: AnsweredQuestion
has body: How to print index of a series using particular variable from any column? I have a Olympic dataset where index is country name and a column named Gold, I have to print country name where the value of Gold is 947.
accepted answer: http://stackoverflow.com/a/49063973

http://stackoverflow.com/q/49081752
linked to: http://stackoverflow.com/q/30648236
answer count: 2
has answer: http://stackoverflow.com/a/49081973
favorite count: 0
linked to: http://stackoverflow.com/q/28115250
type: UnansweredQuestion
tagged with: python
has title: When I use python boto connect to aws ec2 , it show SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)
has comment: http://stackoverflow.com/comment/85169944
tagged with: boto
upvote count: 2
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/57465870
type: Question
has comment: http://stackoverflow.com/comment/85171415
tagged with: amazon-web-services
has body: I'm using Windows 10 OS. I want to count the number of IP Address of AWS. I use python 2.7.14 and boto 2.6.0 I add a file which name is boto.config locate C:\Users\Administrator folder The content of the boto.config is: [Credentials] aws_access_key_id=****** aws_secret_access_key=***** The script is : #!/usr/bin/env python # -*- encoding: utf8 -*- import boto.ec2 from pprint import pprint import ssh import requests import urllib3 import certifi import ssl conn = boto.ec2.connect_to_region('cn-north-1') reservations = conn.get_all_instances() InstanceMap=[] for reservation in reservations: for instance in reservation.instances: if 'env' in instance.tags and instance.tags['env'] == 'test': InstanceMap.append(instance.ip_address) f = open('F:\ip.txt','w') pprint(InstanceMap, f) When I run this script, it show the error formation: SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) What's the method can I solve this problem ?

http://stackoverflow.com/a/49028827
answers question: http://stackoverflow.com/q/49028675
type: Answer
upvote count: 1
has body: Try this, temp=df[df.duplicated(subset=['Individual'],keep=False)] print temp.groupby(['Individual'])['Company'].unique() &gt;&gt;&gt;1 [A, B] &gt;&gt;&gt;3 [A, C]
score: 1
downvote count: 0

http://stackoverflow.com/comment/85149207
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49048124
has text: @JessicaChambers I edited my answer, take a look at the thread I mention in the end.
type: Comment

http://stackoverflow.com/a/49062650
has comment: http://stackoverflow.com/comment/85132485
has comment: http://stackoverflow.com/comment/85945261
accepted answer of: http://stackoverflow.com/q/49062324
has comment: http://stackoverflow.com/comment/85945339
score: 1
answers question: http://stackoverflow.com/q/49062324
upvote count: 1
has comment: http://stackoverflow.com/comment/85945343
has body: I would structure the problem as follows: integer_regex = r"^...$" float_regex = r"^...$" string_regex = r"^...$" def processToken(token): if re.search(integer_regex, token): print(token, 'matches INT') elif re.search(float_regex, token): print(token, 'matches FLOAT') elif re.search(string_regex, token): print(token, 'matches STR') else: print(token, 'unknown') Filling your patterns into the *_regex variables above. Also note, your float pattern is no good, as it also matches int: r'^[0-9]+\.?[0-9]+$' Since the decimal point is optional. You might be better off breaking the pattern into an alternation with three options, starts with '.', ends with '.' or contains a '.' between numbers. Also, in your integer pattern, the '?' in the octal section is incorrect: 0[oO]?[0-7]+ at this point we're trying to commit to octal so the prefix is not optional: 0[oO][0-7]+ You got this correct for hex and binary.
has comment: http://stackoverflow.com/comment/85151339
has comment: http://stackoverflow.com/comment/85132477
has comment: http://stackoverflow.com/comment/85161208
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85945315
has comment: http://stackoverflow.com/comment/85945331
has comment: http://stackoverflow.com/comment/85164757
type: Answer
has comment: http://stackoverflow.com/comment/85161224

http://stackoverflow.com/comment/118156108
has text: self.ranks is missing 10 get_size(self) len method needs parenthesis len(self.available_cards)
comment on: http://stackoverflow.com/a/49012086
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49084210
has body: I think found the most simple solution. It turns out that I had this problem because I used a Jupyter notebook, in which all variables stay alive as long as I don't restart the kernel. My solution is to simply re-initialise all variables before calling anything: tf.reset_default_graph()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49058510
score: 1
upvote count: 1

http://stackoverflow.com/q/49036162
has body: I am trying to click "OK" on my localhost for a popup window that is generated with Jquery. I tried switching to the window that didn't work handleName = driver.window_handles driver.switch_to.window(handleName) then I also tried doing a javascript popup but its a Jquery so it wouldn't work alert = browser.switch_to_alert() alert.accept() browser.close() what are my other options?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49048095
type: Question
answer count: 1
tagged with: javascript
tagged with: jquery
has title: Selenium/Python Jquery popup
score: 0
has answer: http://stackoverflow.com/a/49048095
tagged with: selenium
tagged with: python

http://stackoverflow.com/q/49042433
answer count: 1
downvote count: 0
tagged with: pandas
has title: Barplot after grouping data using seaborn
has answer: http://stackoverflow.com/a/49042625
accepted answer: http://stackoverflow.com/a/49042625
favorite count: 0
tagged with: seaborn
tagged with: python
type: AnsweredQuestion
has body: I am trying to use seaborn.barplot to plot data after grouping. My first approach is to generate a new data frame using the following approach: g_data = g_frame.groupby(["STG","GRP"])["HRE"].mean() g_data Here is the output: STG GRP S1 Control 0.561871 OSA 0.589858 S2 Control 0.595950 OSA 0.629775 S3 Control 0.629906 OSA 0.674118 S4 Control 0.578875 OSA 0.568370 S5 Control 0.557712 OSA 0.569524 Name: HRE, dtype: float64 Next, I defined a plot function called plot_v1(data) as follows: def plot_v2(data): # Create the bar plot ax = sns.barplot( x="STG", y="HRE", hue="GRP", order=["S1", "S2", "S3", "S4", "S5"], hue_order=["Control", "OSA"], data=data) # Return the figure object and axis return plt.gcf(), ax plot_v2(g_data); This throws up an error saying: 149 if isinstance(input, string_types): 150 err = "Could not interpret input '{}'".format(input) --&gt; 151 raise ValueError(err) 152 153 # Figure out the plotting orientation ValueError: Could not interpret input 'STG' I am not sure what am I doing wrong. When I check the index values, it looks fine. g_data.index MultiIndex(levels=[['S1', 'S2', 'S3', 'S4', 'S5'], ['Control', 'OSA']], labels=[[0, 0, 1, 1, 2, 2, 3, 3, 4, 4], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]], names=['STG', 'GRP'])
tagged with: group-by
upvote count: 5
tagged with: matplotlib
type: Question
score: 5

http://stackoverflow.com/a/49060814
type: Answer
answers question: http://stackoverflow.com/q/49060489
score: 1
upvote count: 1
has body: I would've done it pretty similarly. The only differences shown here: result = [] for k, l in dict1.items(): for ll in l: ll.insert(2, k) result.append(ll) No need to do list unpacking or doing [] accessing on dict1. items() returns a list of tuples containing each key and value of the dict.
downvote count: 0
has comment: http://stackoverflow.com/comment/85143483

http://stackoverflow.com/comment/94691095
type: Comment
type: QuestionComment
score: 0
has text: I'm voting to close this question as off-topic because this is not a homework crowdsourcing platform.
comment on: http://stackoverflow.com/q/49093373

http://stackoverflow.com/comment/85030558
type: Comment
comment on: http://stackoverflow.com/q/49011791
has text: As in, there is nothing to learn from the data? nothing correlates with the boxoffice? Wouldn't I at worst be able to overfit my model for my data and get some sort of accuracy?
score: 0
type: QuestionComment

http://stackoverflow.com/a/49039879
has body: Instead of trying to work around the already installed package, why not building a distribution from source yourself? After all, you've already done the hardest part setting up the C compiler, the rest is just a sequence of commands you have to type. This is what you can do: Clone bitarray's repository: $ git clone https://github.com/ilanschnell/bitarray Navigate into the cloned repository: $ cd bitarray Checkout the version tag you want to build (the latest one is 0.8.1): $ git checkout 0.8.1 Ensure you have wheel installed to be able to build a static wheel: $ pip install wheel Build the static wheel: $ python setup.py bdist_wheel A new directory dist was created in the current one, check what's inside: $ ls dist bitarray-0.8.1-cp36-cp36m-macosx_10_6_intel.whl (Note: This is what I would enter on my system, list the directory with dir on Windows, also your file should be either bitarray-0.8.1-cp36-cp36m-win_amd64.whl if you are building on a 64 bit system, or bitarray-0.8.1-cp36-cp36m-win32.whl on a 32 bit one). Now you have built a static wheel that contains the C extensions compiled for Python 3.6 on Windows. It can be installed on Windows without needing to setup the C compiler on the target machine. Just enter $ pip install bitarray-0.8.1-cp36-cp36m-win_amd64.whl Note, however, that this wheel file can be installed only on Windows and only with Python 3.6. Should you need to provide a wheel for another setup (like Python 3.5 on Windows 32 bit), you would need to build another wheel file using the correct Python version on a correct target system, but the steps would be just the same. Building without Git If you don't have Git installed and you can't/don't want to install it, just download the zipped repository from Github, unzip it, navigate to the extracted directory and perform steps 4-6.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49036741
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49036741
type: Answer
has comment: http://stackoverflow.com/comment/85086219
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85175993
has comment: http://stackoverflow.com/comment/85086524

http://stackoverflow.com/q/49097281
has body: So I am able to print out a full column from within a CSV easily with this code: with open("compsci_questions.csv","r") as f: if difficulty=="easy": csv_reader=csv.reader(f) for line in csv_reader: print(line[0]) Which in turn returns: What is the fastest type of storage? Which register stores the results of calculations carried out by the ALU? Which bus sends data to the CPU from the RAM? What is 10110110 in denary? What is 7D in denary? In which topology is each computer connected individually to a central point? What is half a byte known as? What is 142 in binary? What is each column known as in a record? What is a variable which is available anywhere in a program known as? How would I get it to randomly select just one of those questions as well as selecting the column?
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/49097330
answer count: 1
tagged with: random
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/85199667
favorite count: 0
accepted answer: http://stackoverflow.com/a/49097330
upvote count: 1
tagged with: python
has title: How to select a random value from a column in a CSV file in python?
has comment: http://stackoverflow.com/comment/85199665
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22827806

http://stackoverflow.com/comment/85051362
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49023218
has text: won't that need to import slug from some where in the views.py file ??
type: AnswerComment

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/48999393
tags question: http://stackoverflow.com/q/49008122
tags question: http://stackoverflow.com/q/48988707
tags question: http://stackoverflow.com/q/49021736
type: Tag
tag name: pdf
tags question: http://stackoverflow.com/q/49064193
tags question: http://stackoverflow.com/q/49117172

http://stackoverflow.com/comment/85078365
type: QuestionComment
comment on: http://stackoverflow.com/q/49036317
type: Comment
has text: @PDUY The words "river discharge tree" makes me think you don't actually want all possible combinations of an input list. Are you really working with a tree, and have things like a branch where 1->2,3, but you wouldn't want (2,3) as an output?
score: 0

http://stackoverflow.com/q/49078973
type: AnsweredQuestion
downvote count: 0
tagged with: pyqt5
type: Question
score: 3
tagged with: qml
has answer: http://stackoverflow.com/a/49079068
accepted answer: http://stackoverflow.com/a/49079068
has title: findChild returns None
upvote count: 3
tagged with: pyqt
answer count: 1
favorite count: 0
has body: I saw other people asking this question but none of what I tried worked. I am using PyQt 5.10.1. Here is python code: app = QGuiApplication(sys.argv) view = QQuickView() view.setSource(QUrl("module/Layout.qml")) print(view.rootContext()) print(view.findChild(QObject, 'launcherComponent')) import pdb; pdb.set_trace() sys.exit(app.exec()) And here is the QML code: import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Window 2.2 import "calendar/resources" as CalendarComponent import "weather/resources" as WeatherComponent import "launcher/resources" as LauncherComponent import Test 1.0 import Weather 1.0 import Calendar 1.0 import Launcher 1.0 ApplicationWindow { id: appId width: Screen.desktopAvailableWidth height: Screen.desktopAvailableHeight visible: true modality: Qt.ApplicationModal flags: Qt.Dialog title: qsTr("NarcisseOS") color: "black" LauncherComponent.LauncherComponent { id: launcherComponentId objectName: launcherComponent height: parent.height width: parent.width anchors.centerIn: parent } } I tried everything I thought about. But this findChild function is only returning None. I tried to reinstall PyQt5. And I tried to put the objectName property in a Rectangle object, I thought maybe a more generic one would be working. None of it worked.
tagged with: python

http://stackoverflow.com/q/49062845
type: Question
has title: Python RoboBrowser error
accepted answer: http://stackoverflow.com/a/49063026
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49063026
has body: I'm using RoboBrowser to login to a website using this code: import re from robobrowser import RoboBrowser bra=RoboBrowser() bra=open("http://webpage.com") form=bra.get_form() form['user']='test' form['password']='pass' bra.submit_form(form) But I get this error: OSError: [Errno 22] Invalid argument:'http://webpage.com' I'v tried all urls related to the site but I always get the same error. Maybe I can use another library or something. I'm using Windows 10 and use Python 3.6
tagged with: python
type: AnsweredQuestion
tagged with: web-scraping
tagged with: robobrowser

http://stackoverflow.com/comment/85122205
comment on: http://stackoverflow.com/q/49058313
has text: @roganjosh I know, that's why it might be a fun experiment to implement it with csvs
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/49050166
has comment: http://stackoverflow.com/comment/85104771
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/49051606
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85104948
score: 1
has comment: http://stackoverflow.com/comment/85106660
upvote count: 1
has title: Keep row indices of DataFrame at Variance Threshold transformation
type: Question
tagged with: numpy
tagged with: feature-selection
has body: I'm doing a variance threshold feature selection with sklearn on a pandas DataFrame. In order to avoid a bias from feature selection - VarianceThreshold is only the first step - I've divided the original dataset into a part for feature selection (X_selection, y_selection) and a part for modeling (X_model, y_model). Nevertheless, they contain the same columns in the same order. So, I've started by defining the selector and fit the data afterwards: # get column names X_columns = X_selection.columns # doing the variance threshold feature selection selector = VarianceThreshold() selector.fit(X_selection) # filtering the selected column names X_columns = X_columns[selector.get_support()] # transform original data according to selector X_selection = pd.DataFrame(selector.transform(X_selection), columns = X_columns) X_model = pd.DataFrame(selector.transform(X_model), columns = X_columns) Unfortunately, I've encountered that the rows in the resulting X_selection and X_model are jumbled. For example, prior to the transformation I've got for some, exemplary rows out of X_model: COL_X 0 0.000000 1 0.000000 2 0.000000 10 0.000000 25 0.185185 150 0.037037 3333 0.000000 16000 0.000000 After the transformation, calling the same row indices of X_model gives me: COL_X 0 0.000000 1 0.000000 2 0.111111 10 0.000000 25 0.000000 150 0.000000 3333 0.000000 16000 0.111111 In my understanding transform has shuffled the rows in a for me unknown manner. Though the relations to the y_model array with class labels is broken, because the order of rows is unchanged here. Thank you for any comments how to fix it or where my mistakes are hidden.
has comment: http://stackoverflow.com/comment/85105410
has answer: http://stackoverflow.com/a/49051606

http://stackoverflow.com/comment/85149379
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49071319
has text: It would be awesome to have the column titles not have review/ before every entry.
type: AnswerComment

http://stackoverflow.com/comment/84961939
type: QuestionComment
comment on: http://stackoverflow.com/q/48978237
score: 1
has text: @mw-b, ...because they're empty. See ie. [empty list boolean value](https://stackoverflow.com/questions/12997305/empty-list-boolean-value), or [How do I check if a list is empty?](https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty).
type: Comment

http://stackoverflow.com/comment/85006011
type: Comment
has text: Interestingly, all eigenvalues are real up to the size 64 by 64. At size 65 by 65 imaginary parts appear, and they are not very small: about 0.01. Quite a sudden change, which makes me suspicious. If the eigenvalues are correct, and you don't want complex one, then the only way is to filter out those with imaginary part over some threshold (1e-16 or so).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48999970

http://stackoverflow.com/q/49028756
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49029456
accepted answer: http://stackoverflow.com/a/49029456
downvote count: 0
has comment: http://stackoverflow.com/comment/85065627
type: Question
possible better answer: http://stackoverflow.com/a/51660399
answer count: 2
upvote count: 3
has title: How to get frame name of notebook widget in tkinter
has comment: http://stackoverflow.com/comment/85064792
has body: If we have label than we have an option to get it's text as l = tk.Label(text="hello, world") ... print("the label is", l.cget("text")) But I am unable to find a name of frame added in notebook by the same way is there any other approach available? ttk.Notebook sample: import tkinter from tkinter import * from tkinter.ttk import * root = tkinter.Tk() note = Notebook(root) tab2 = Frame(note) tab3 = Frame(note) note.add(tab2, text = "Tab Two") note.add(tab3, text = "Tab Three") note.pack() root.mainloop() exit()
has comment: http://stackoverflow.com/comment/85065439
favorite count: 0
has answer: http://stackoverflow.com/a/51660399

http://stackoverflow.com/comment/84997545
type: Comment
has text: @suchait Updated the question.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48995922

http://stackoverflow.com/a/48997358
answers question: http://stackoverflow.com/q/48997218
type: Answer
has comment: http://stackoverflow.com/comment/85000295
upvote count: 2
has body: As pointed out by the stack trace this is where the problem arises. deal_detail = Deal.objects.get(slug=slug) The exception DoesNotExist arises when use get and the object does not exist. So that means that the slug you're trying to use does not exist in the database. As you wanted to get category view and not the detail view the error actually lies in the regex (as you rightfully suspected). The error lies in you using .* which is greedy and uses all of the rest remaining characters. If you instead change your regex to the following. r'^s/(?P&lt;slug&gt;\w+)/$', note the s in the beginning that helps with keeping the url different from other urls as well \w+ that only uses alphanumeric characters.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85000284

http://stackoverflow.com/comment/85128931
type: Comment
has text: Thanks for your answer! I can collect the data now.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49043043

http://stackoverflow.com/comment/85176084
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49085201
has text: Worth to note that for some reason this approach runs much faster than ```apply```!

http://stackoverflow.com/a/49086079
accepted answer of: http://stackoverflow.com/q/49085832
answers question: http://stackoverflow.com/q/49085832
upvote count: 17
score: 17
has comment: http://stackoverflow.com/comment/85180939
has comment: http://stackoverflow.com/comment/85182137
type: AcceptedAnswer
downvote count: 0
has body: You can use the ppf method (i.e. the quantile function) of scipy.stats.t: In [129]: from scipy.stats import t In [130]: alpha = 0.025 In [131]: t.ppf(1 - alpha, df=9) Out[131]: 2.2621571627409915 t.ppf() ultimately calls scipy.special.stdtrit, so you could also use that function and avoid the slight overhead of going through t.ppf(): In [141]: from scipy.special import stdtrit In [142]: alpha = 0.025 In [143]: stdtrit(9, 1 - alpha) Out[143]: 2.2621571627409915 (If you are wondering how the function ended up with the name stdtrit, it is the Student T DisTRibution function Inverse with respect to T. Clear, right?)
has comment: http://stackoverflow.com/comment/85180592
type: Answer

medical
tags question: http://stackoverflow.com/q/49094535
type: Tag
tag name: medical

http://stackoverflow.com/q/49112256
has comment: http://stackoverflow.com/comment/85230811
downvote count: 1
type: Question
tagged with: frameworks
upvote count: 0
tagged with: pep8
accepted answer: http://stackoverflow.com/a/49112459
answer count: 1
score: -1
tagged with: sentence-synthesis
has title: Sentence variations in python3
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49112459
has body: A few months ago I found something with this kind of syntax: {Hello|Dear} {Customer|client|person}, xxxx This will generate sentences like: Hello Customer, or Dear person, How is it called? Is there a framework which parses this? If not, how would I do this? I am planning to use this in an automation script which builds sentences. Any further idea's on which frameworks I should use for building sentences in python? It makes ugly code when long blocks of text are embedded in python scripts.
type: AnsweredQuestion

http://stackoverflow.com/comment/85133734
type: QuestionComment
has text: Have you restarted the jupyter notebook after reinstalling the numpy and pandas library?
score: 0
comment on: http://stackoverflow.com/q/49064113
type: Comment

http://stackoverflow.com/a/48979874
has body: FOUND THE ANSWER: Had to exit the fork processes with: os._exit(0) not with sys.exit()
type: Answer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/48979460
upvote count: 3

http://stackoverflow.com/comment/84985481
type: QuestionComment
comment on: http://stackoverflow.com/q/48990432
type: Comment
score: 0
has text: Yes, like `df['BStrategy'] = df['Breturn'][(df['SELL'] == True) & (df['BUY'] == False)]`

http://stackoverflow.com/q/48972492
type: Question
has body: A B 0 2002-01-16 0 1 2002-01-16 4 2 2002-01-16 -2 3 2002-01-16 11 4 2002-01-16 12 5 2002-01-17 0 6 2002-01-17 -18 7 2002-01-17 16 8 2002-01-18 0 9 2002-01-18 -1 10 2002-01-18 4 results = {} grouped = df.groupby("A") for name, group in grouped: if (df["B"] &gt;= 10).any(): results[name] = df.loc[df["B"] &gt;= 10].head(1) print(results[name]) elif (df["B"] &lt;= -10).any(): results[name] = df.loc[df["B"] &lt;= -10].head(1) print(results[name]) else: results[name] = df.loc[df["B"] &gt; -10, :].tail(1) print(results[name]) Output: A B 3 2002-01-16 11 A B 3 2002-01-16 11 A B 3 2002-01-16 11 I want to iterate and get one result per each A group, with the next conditions: If any B column value is >= 10 or &lt;= -10, add just the first to "results" and skip to the next group to continue iterating. If there is not any B column value >= 10 or &lt;= -10, add the last value to "results" and skip to the next group to continue iterating. The desired output would be: A B 3 2002-01-16 11 A B 6 2002-01-17 -18 A B 10 2002-01-18 4
has answer: http://stackoverflow.com/a/48973306
answer count: 3
tagged with: pandas
score: 2
possible better answer: http://stackoverflow.com/a/48973499
downvote count: 0
has answer: http://stackoverflow.com/a/48976027
has answer: http://stackoverflow.com/a/48973499
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/48976027
tagged with: python
type: AnsweredQuestion
has title: Iterating over groups into a dataframe

http://stackoverflow.com/comment/85234328
type: AnswerComment
has text: I have to agree that the chapter on Unification is one of the most authoritative references on Unification if not the most authoritative, but as one who has implemented the unification algorithm in languages such as OCaml, F#, etc, and seen it implemented in languages such as C, C#, etc. That is one of the [denses](https://en.oxforddictionaries.com/definition/dense) reads on the topic.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/49114348

http://stackoverflow.com/q/49096695
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/85201758
has answer: http://stackoverflow.com/a/49097329
has comment: http://stackoverflow.com/comment/85200752
has body: I have the following problem. I have several parameters, all integers or floats, and I want to stack them in a for loop. I tried different thinks like: for i in range(0,19000): parameterCombinationsResults = np.array([]).reshape(0,12) parameterCombinationsResults = np.r_[parameterCombinationsResults,[[self.cR,self.fD,s[0]+1,s[1]+1,self.cI,self.cO,self.fI,self.fO,maxJC,maxSensitivity,maxSpecifity,numberOfCells]]] The problem is, that in every loop iteration the old values are stacked as well of course, so I have in every loop the old results+the new results which will result in an array with thousands of copies of the old results. Is there a way like list append. I know arrays are immutable but maybe there is a workaround? In the end I want to save all this parametercombination results in a csv. It dont have to be arrays I would also be itnerested in a list approach, the important thing is to save them in a csv and that it has to be very fast.
has comment: http://stackoverflow.com/comment/85198478
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85198521
has title: Python: Append array columns in a for loop
accepted answer: http://stackoverflow.com/a/49097329
tagged with: numpy

http://stackoverflow.com/a/49115047
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85238465
has comment: http://stackoverflow.com/comment/85622236
answers question: http://stackoverflow.com/q/49114921
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85240124
accepted answer of: http://stackoverflow.com/q/49114921
has body: You can use regex: import re data = [map(float, re.findall('(?&lt;=:)[\d\.]+|^\d+', i.strip('\n'))) for i in open('filename.txt')] Output: [[10.0, 0.870137474304, 0.722354071782, 0.671913562758], [11.0, 0.764133072717, 0.4893616821, 0.332713609364], [20.0, 0.531732713984, 0.0967819558321, 0.169802773309]] Edit: to create a numpy array with data: import numpy as np import re data = [map(float, re.findall('(?&lt;=:)[\d\.]+|^\d+', i.strip('\n'))) for i in open('filename.txt')] new_data = np.array(data) Output: array([[ 10. , 0.87013747, 0.72235407, 0.67191356], [ 11. , 0.76413307, 0.48936168, 0.33271361], [ 20. , 0.53173271, 0.09678196, 0.16980277]])

http://stackoverflow.com/a/48996538
score: 0
answers question: http://stackoverflow.com/q/48993468
has body: It appears that your intent is for your program to pause, and wait for the user to click before continuing. That is, you want the flow to be this: imageDisp = imageLabel(UsrInp) imageDisp.select_ROI() (wait for the user to click) alpha = (imageDisp.bound[0]+ imageDisp.bound[2])/2 That is not normally how GUIs work. Usually you set events and then respond to events, rather than explicitly waiting for a specific event. However, what you want to do is possible. You just need to cause select_ROI to not return until the clicks happen. The simplest way is to have your program wait on a variable, then make sure that your event bindings causes that variable to be set. First, create a flag in imageLabel.__init__ that can be used later: class imageLabel(Tk.Label): def __init__(self, parent): ... self.var = Tk.BooleanVar() ... Next, in select_ROI, wait for that variable to be set before returning: def select_ROI (self): ... self.wait_variable(self.var) return Finally, make sure that your bindings set this flag: def on_click(self, event): ... if len(self.bound)==4: ... self.var.set(True) That will cause select_ROI to wait for the user to click and release before returning. Be aware that this can lead to a very confusing user experience if you don't give the user sufficient feedback on what they are supposed to do, and you don't take steps to prevent them from doing anything else before they do the clicks.
has comment: http://stackoverflow.com/comment/85035362
type: Answer

http://stackoverflow.com/comment/84995683
type: QuestionComment
type: Comment
score: 0
has text: Can't you check the length of the list or am I missing something?
comment on: http://stackoverflow.com/q/48994941

http://stackoverflow.com/comment/87963376
type: Comment
type: QuestionComment
has text: Have you solved this? You could specify which device you're using. Seems to me you're using a B&W Series device because of the `SetUserInfo()` function you're using. If you're using a TFT Series device you should use the `SSR_SetUserInfo()` function. You'll get the same error message if you call on a function with the device disconnected (not saying this is the case because it's clearly connected, just saying the error messages are vague). Another possibility is that the device's firmware is different than expected by the SDK (it has happened to me).
comment on: http://stackoverflow.com/q/49066638
score: 0

http://stackoverflow.com/comment/85016413
has text: I also don't claim anything. Just saying. You can do whatever you want.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49005853
type: QuestionComment

http://stackoverflow.com/q/49059089
has body: Given a list of word embedding vectors I'm trying to calculate an average word embedding where some words are more meaningful than others. In other words, I want to calculate a semantically weighted word embedding. All the stuff I found is on just finding the mean vector (which is quite trivial of course) which represents the average meaning of the list OR some kind of weighted average of words for document representation, however that is not what I want. For example, given word vectors for ['sunglasses', 'jeans', 'hats'] I would like to calculate such a vector which represents the semantics of those words BUT with 'sunglasses' having a bigger semantic impact. So, when comparing similarity, the word 'glasses' should be more similar to the list than 'pants'. I hope the question is clear and thank you very much in advance!
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85148021
tagged with: vector
answer count: 1
has title: Semantically weighted mean of word embeddings
tagged with: python
tagged with: semantics
favorite count: 0
score: 2
downvote count: 0
type: UnansweredQuestion
tagged with: word-embedding
tagged with: word2vec
has answer: http://stackoverflow.com/a/49081754
has comment: http://stackoverflow.com/comment/85125234
has comment: http://stackoverflow.com/comment/85140108

identifier
tag name: identifier
tags question: http://stackoverflow.com/q/49067980
type: Tag

http://stackoverflow.com/a/48998730
upvote count: 2
answers question: http://stackoverflow.com/q/48998640
has comment: http://stackoverflow.com/comment/85024424
has comment: http://stackoverflow.com/comment/85004405
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85004382
accepted answer of: http://stackoverflow.com/q/48998640
has comment: http://stackoverflow.com/comment/85004414
has body: I think the %b should be %m? %b Month as locale’s abbreviated name. %m Month as a zero-padded decimal number. &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; d = datetime.strptime('12/31/2015 7:00:00 PM', '%b/%d/%Y %H:%M:%S %p') ValueError: time data '12/31/2015 7:00:00 PM' does not match format '%b/%d/%Y %H:%M:%S %p' &gt;&gt;&gt; d = datetime.strptime('12/31/2015 7:00:00 PM', '%m/%d/%Y %I:%M:%S %p') &gt;&gt;&gt; d datetime.datetime(2015, 12, 31, 19, 0) I find myself going back to this site frequently: http://strftime.org/ Or just the Python docs: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior Example import pandas as pd df = pd.DataFrame({'time': {0: '12/31/2015 7:00:00 PM', 1: '12/31/2015 7:00:02 PM', 2: '12/31/2015 7:00:10 PM', 3: '12/31/2015 7:00:12 PM'}, 'value': {0: 275.9271, 1: 278.559, 2: 277.5949, 3: 270.0564}}) df['time'] = pd.to_datetime(df['time'], format='%m/%d/%Y %I:%M:%S %p') # time value # 0 2015-12-31 19:00:00 275.9271 # 1 2015-12-31 19:00:02 278.5590 # 2 2015-12-31 19:00:10 277.5949 # 3 2015-12-31 19:00:12 270.0564
type: Answer
score: 2

http://stackoverflow.com/q/48970040
has title: lxml ElementMaker Attribute formatting
score: 3
accepted answer: http://stackoverflow.com/a/48971388
answer count: 1
downvote count: 0
favorite count: 0
tagged with: lxml
linked to: http://stackoverflow.com/q/15369329
tagged with: python
tagged with: attributes
has answer: http://stackoverflow.com/a/48971388
has body: Thanks to this question/answer, I was able to get a namespace attribute added to a root element. So now I have this: Code from lxml.builder import ElementMaker foo = 'http://www.foo.org/XMLSchema/bar' xsi = 'http://www.w3.org/2001/XMLSchema-instance' E = ElementMaker(namespace=foo, nsmap={'foo': foo, 'xsi': xsi}) fooroot = E.component() fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd' bars = E.bars(label='why?', validates='required') fooroot.append(bars) bars.append(E.bar(label='Image1')) bars.append(E.bar(label='Image2')) etree.dump(fooroot) This give me the desired output: Output &lt;foo:component xmlns:foo="http://www.foo.org/XMLSchema/bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd"&gt; &lt;foo:bars label="why?" validates="required"&gt; &lt;foo:bar label="Image1"/&gt; &lt;foo:bar label="Image2"/&gt; &lt;/foo:bars&gt; &lt;/foo:component&gt; The question Why does the fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] require 3 braces around the pre? 1 brace: {pre} causes a ValueError BAD 2 braces: {{pre}} produces ns0:schemaLocation on the output BAD 3 braces: {{{pre}}} produces xsi:schemaLocation on the output GOOD I understand the .format usage for the string, but I'd like to understand why I need 3 braces.
type: AnsweredQuestion
upvote count: 3
type: Question

http://stackoverflow.com/comment/84944471
type: QuestionComment
comment on: http://stackoverflow.com/q/48968549
score: 0
has text: I posted the data in the Answer box, please take a look
type: Comment

http://stackoverflow.com/a/49052580
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49052446
has body: This might help. Removes all string which has ":" in it. a = ":raining, raining:, rai:ning aaaaaaa" def removeStr(val): if ":" not in val: return val each_line = " ".join(filter(removeStr, a.split())) print each_line Output: aaaaaaa
answers question: http://stackoverflow.com/q/49052446
type: Answer
has comment: http://stackoverflow.com/comment/85109935
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48966200
score: 1
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48966222
accepted answer: http://stackoverflow.com/a/48966222
answer count: 1
downvote count: 1
tagged with: flask
has title: Calling a Python function from HTML is not working
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: In my HTML page, I have a button. When I click on the button it should call a Python function that takes a screenshot and save it in the same directory. I tried my Python method and it is working correctly on local. But when I used Flask to call the function from a HTML button, it does nothing and there are no errors. How to get the screenshot image ? Python Flask: @app.route('/') def index(): return render_template('index.html') # Function to take the screenshot and save it def takesc(): with mss() as sct: sct.shot() @app.route('/takeScreenshot') def takeScreenshot(): return takesc() My HTML ScreenShoot I also tried to use 'url_for' as following, but still nothing happened: ScreenShoot
type: AnsweredQuestion

http://stackoverflow.com/q/48984567
type: Question
tagged with: dataframe
answer count: 1
accepted answer: http://stackoverflow.com/a/48984757
tagged with: series
score: 0
has title: Why does giving a type to the apply method on Series does what it does?
tagged with: pandas
tagged with: python
has body: I had this problem recently, where you have a pandas.Series of tuples, e.g. my_series = [(a, b), (c, d), (e, f) … ], and you want to make a DataFrame out of it, of the following form: col1 col2 a b c d e f … Now, I found a solution, but I don’t understand why it works. It is simply my_series.apply(pandas.Series). The doc doesn’t really help in that regard. Whey does giving a type to the apply method yield such a result?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48984757

http://stackoverflow.com/q/48989858
type: UnansweredQuestion
has title: Creating tfrecord with audio sample, extracted from video in python
tagged with: python
upvote count: 2
score: 1
downvote count: 1
type: Question
has body: This code is for creating tfrecords which is tensorflows standard input format for keeping audios and labels taken from video samples.This file is given as input for training in neural network. #!/usr/bin/env python2 # -*- coding: utf-8 -*- import menpo import tensorflow as tf import numpy as np import os from io import BytesIO from pathlib import Path from moviepy.editor import VideoFileClip from menpo.visualize import progress_bar_str, print_progress from moviepy.audio.AudioClip import AudioArrayClip root_dir = Path('/home/user/Desktop/PROJECT/Multimodal-Emotion-Recognition-master/RECOLA') #Where RECOLA is located portion_to_id = dict( train = [1], # 25 valid = [70, 71], test = [80, 81] # 54, 53 ) #samples taken def get_samples(subject_id): #location of arousal and valence files and appropriate video sample arousal_label_path = root_dir / 'ratings_individual/arousal/{}.csv'.format(subject_id) valence_label_path = root_dir / 'ratings_individual/valence/{}.csv'.format(subject_id) clip = VideoFileClip(str(root_dir /"Video_recordings_MP4/{}.mp4".format(subject_id))) subsampled_audio = clip.audio.set_fps(16000) audio_frames = [] for i in range(1, 7501): #extract audio sample try: time = 0.04 * i audio = np.array(list(subsampled_audio.subclip(time - 0.04, time).iter_frames())) audio = audio.mean(1)[:640] audio_frames.append(audio.astype(np.float32)) except ValueError: print('Not float') quit() try: arousal = np.loadtxt(str(arousal_label_path), delimiter=',')[:+1][1:] valence = np.loadtxt(str(valence_label_path), delimiter=',')[:+1][1:] return audio_frames, np.dstack([arousal, valence])[0].astype(np.float32) #return audio frames except ValueError: print('problem') def get_jpg_string(im): # Gets the serialized jpg from a menpo `Image`. fp = BytesIO() menpo.io.export_image(im, fp, extension='jpg') fp.seek(0) return fp.read() def _int_feauture(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feauture(value): return tf.train.Feature(by…
answer count: 1
has answer: http://stackoverflow.com/a/49134594
favorite count: 0

http://stackoverflow.com/comment/85114116
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49042132
score: 0
has text: Here's the result when I use this:

http://stackoverflow.com/q/49062365
favorite count: 0
has comment: http://stackoverflow.com/comment/85130526
possible better answer: http://stackoverflow.com/a/49062489
type: Question
has answer: http://stackoverflow.com/a/49062489
has body: There appears to be an almost philosophical difference in the meaning of "equality" between C++ and Python. I became aware of this distinction through an attempt to do in Python something that is quite difficult in C++: distinguishing between two enum types when they are both just a wrapper for a set of integers, but the issue is broader than enums, hence the present question. If I write in C++ code such as the following #include &lt;iostream&gt; struct Foo { bool operator==(const Foo&amp; foo) const { return this == &amp;foo; } }; struct Bar {}; int main() { Foo foo = Foo(); Bar bar = Bar(); if (foo == bar) std::cout &lt;&lt; "ok" &lt;&lt; std::endl; } I fully expect that the equality comparison will fail. Indeed, it's a compilation error. You can't even compare two objects unless they're, just to get going, of the same type. And yet it appears that "there is little (no?) precedent in Python for equality comparisons raising errors". and "if [an object] raises every time it is compared to a [object of a different type], it will break any container it is added to". Indeed, writing class Foo(object): pass class Bar(object): pass foo = Foo() bar = Bar() if (foo == bar): print("equal") reveals that there is no problem in comparing objects that should otherwise be incomparable. What, philosophically, is the root of this distinction in the meaning of equality between the two languages? Update Part of my puzzlement at finding this out about Python is that so far every feature appears to have been designed with the intent of being "natural", "intuitive", even "human"—not that these can be defined in the first place. But consider that you are at the fruit section of a grocery shop and ask one of the aproned chaps: "Could you tell me whether these oranges are Fuji or Red Delicious?" Surely no one could make sense of the question to venture an answer one way or the other. So the question is how to provide a response of "incredulous" in bits and bytes. Update 2 (Too long to be …
has comment: http://stackoverflow.com/comment/85129872
has comment: http://stackoverflow.com/comment/85130479
tagged with: python
has title: What is the root of the distinction in the meaning of equality between C++ and Python?
tagged with: c++
upvote count: 19
score: 15
accepted answer: http://stackoverflow.com/a/49062478
linked to: http://stackoverflow.com/q/49060812
has comment: http://stackoverflow.com/comment/85131224
answer count: 3
has comment: http://stackoverflow.com/comment/85159725
has answer: http://stackoverflow.com/a/49069179
has comment: http://stackoverflow.com/comment/85142805
has comment: http://stackoverflow.com/comment/85141369
has comment: http://stackoverflow.com/comment/85132194
downvote count: 4
has comment: http://stackoverflow.com/comment/85137094
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49062478

http://stackoverflow.com/a/49070017
has body: You need to define constructor of Resource. Here an example: import logging class SomeEndpoint(Resource): def __init__(self, **kwargs): self.logger = kwargs.get('logger') def get(self): # self.logger - 'logger' from resource_class_kwargs return self.logger.name api.add_resource(SomeEndpoint, '/', resource_class_kwargs={ # any logger here... 'logger': logging.getLogger('my_custom_logger') }) Open your endpoint. You will see my_custom_logger. Hope this helps.
has comment: http://stackoverflow.com/comment/85174967
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49053741
score: 6
answers question: http://stackoverflow.com/q/49053741
type: Answer
upvote count: 6

http://stackoverflow.com/a/49017273
score: 2
answers question: http://stackoverflow.com/q/49013804
type: AcceptedAnswer
downvote count: 0
has body: You can specify the image used with the --image-name flag (docs). The Ubuntu image can be retrieved from Docker Hub, for example. You can see an example here where they tag an image and push it to GCR (Google Container Registry): docker tag datalab gcr.io/PROJECT_ID/datalab And then you can specify that image upon Datalab instance creation with the aforementioned flag: datalab create --image-name=gcr.io/PROJECT_ID/datalab INSTANCE_NAME
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49013804

http://stackoverflow.com/comment/85023908
has text: indent your code properly please.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49009656
score: 0

http://stackoverflow.com/comment/85077929
has text: the more important question, is what is the N in your function, why why would it ever be set as a float.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49036097

http://stackoverflow.com/q/49048874
type: Question
answer count: 2
downvote count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/49048946
has answer: http://stackoverflow.com/a/49048946
accepted answer: http://stackoverflow.com/a/49048954
has comment: http://stackoverflow.com/comment/85101809
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85101799
has answer: http://stackoverflow.com/a/49048954
has title: Variable not defined (Python)
type: AnsweredQuestion
score: -1
has body: FlightType=input("Which flight would you like to fly? Type '2 Seater', '4 Seater', or 'Historic'.") # No validation included for the input FlightLen=input("Would you like to book the '30' minutes flight or the '60'") # No validation included for the input if (FlightLen==30): MaxSlots=(600/FlightLen) elif (FlightLen==60): MaxSlots=(600//FlightLen) print (MaxSlots) When I run the code, why does the following error message appear? NameError: name 'MaxSlots' is not defined

http://stackoverflow.com/q/49051262
tagged with: python
tagged with: kivy
has body: As the title suggest, apart from the text in the center on the button I want to put text in any of the corners of the button. One possible way to do so is to use a background image. But I want to know, can it really be done? import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.lang import Builder Builder.load_string(""" &lt;ButtonGridLayout&gt;: rows: 2 padding: 10 spacing: 10 Button: text: 'Hello' Button: text: 'Hellow' """) class ButtonGridLayout(GridLayout): pass class ButtonApp(App): def build(self): return ButtonGridLayout() if __name__=='__main__': ButtonApp().run() Right there inside the blue circle in this image ButtonApp
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49087118
has answer: http://stackoverflow.com/a/49060152
possible better answer: http://stackoverflow.com/a/49060152
has title: Kivy- Is it possible to add superscript or subscript text to button
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49087118
downvote count: 0
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85098653
type: Comment
has text: @VeyselKo Check the new edited solution, i used different library for german lemmatization textblob-de
comment on: http://stackoverflow.com/a/49046649
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85206816
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49100734
has text: Can you please add the output from `ls -l /dev/gpiomem` and the result from `system('id');`? I thing I've got an idea
score: 0

http://stackoverflow.com/a/48980095
type: Answer
upvote count: 13
score: 13
has body: A heappop() rearranges log(n) elements in the list so that it doesn't have to shift every element. This is easy to see: &gt;&gt;&gt; from random import randrange &gt;&gt;&gt; from heapq import heapify, heappop &gt;&gt;&gt; h = [randrange(1000) for i in range(15)] &gt;&gt;&gt; heapify(h) &gt;&gt;&gt; h [80, 126, 248, 336, 335, 413, 595, 405, 470, 592, 540, 566, 484, 970, 963] &gt;&gt;&gt; heappop(h) 80 &gt;&gt;&gt; h [126, 335, 248, 336, 540, 413, 595, 405, 470, 592, 963, 566, 484, 970] &gt;&gt;&gt; # ^----^---------^----^----^----^----^---------^----^----^--- elements that didn't move Note that the popping operation didn't move most of the elements (for example 248 is in the same position before and after the heappop).
answers question: http://stackoverflow.com/q/48978388
downvote count: 0

http://stackoverflow.com/a/51442969
upvote count: 20
score: 20
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49085673
answers question: http://stackoverflow.com/q/49085673
type: Answer
has body: I reached this page When I faced same problem. I can use "popular" with this code at google colab. import nltk nltk.download("popular")

arrays
tags question: http://stackoverflow.com/q/49119431
tags question: http://stackoverflow.com/q/49032767
tags question: http://stackoverflow.com/q/48972758
tags question: http://stackoverflow.com/q/49050666
tags question: http://stackoverflow.com/q/48978272
type: Tag
tags question: http://stackoverflow.com/q/49090643
tags question: http://stackoverflow.com/q/49019371
tags question: http://stackoverflow.com/q/49060790
tags question: http://stackoverflow.com/q/49054126
tags question: http://stackoverflow.com/q/49020080
tags question: http://stackoverflow.com/q/49061441
tags question: http://stackoverflow.com/q/49032948
tags question: http://stackoverflow.com/q/49092467
tags question: http://stackoverflow.com/q/49059917
tags question: http://stackoverflow.com/q/49070594
tags question: http://stackoverflow.com/q/49036075
tags question: http://stackoverflow.com/q/49057495
tags question: http://stackoverflow.com/q/49096537
tags question: http://stackoverflow.com/q/48968633
tags question: http://stackoverflow.com/q/48996006
tags question: http://stackoverflow.com/q/48971233
tags question: http://stackoverflow.com/q/48998086
tags question: http://stackoverflow.com/q/49012613
tags question: http://stackoverflow.com/q/48968285
tags question: http://stackoverflow.com/q/49109920
tags question: http://stackoverflow.com/q/49015697
tags question: http://stackoverflow.com/q/48980605
tags question: http://stackoverflow.com/q/49010686
tags question: http://stackoverflow.com/q/49096695
tags question: http://stackoverflow.com/q/49075560
tags question: http://stackoverflow.com/q/49061066
tags question: http://stackoverflow.com/q/49087282
tags question: http://stackoverflow.com/q/48973026
tags question: http://stackoverflow.com/q/49096654
tags question: http://stackoverflow.com/q/49039113
tags question: http://stackoverflow.com/q/49056343
tags question: http://stackoverflow.com/q/48997071
tags question: http://stackoverflow.com/q/49095192
tags question: http://stackoverflow.com/q/49077128
tags question: http://stackoverflow.com/q/49064548
tags question: http://stackoverflow.com/q/49066690
tags question: http://stackoverflow.com/q/49038401
tags question: http://stackoverflow.com/q/48991077
tags question: http://stackoverflow.com/q/49071248
tags question: http://stackoverflow.com/q/49093168
tags question: http://stackoverflow.com/q/49073355
tags question: http://stackoverflow.com/q/49085469
tags question: http://stackoverflow.com/q/49095047
tags question: http://stackoverflow.com/q/48996653
tags question: http://stackoverflow.com/q/49054927
tags question: http://stackoverflow.com/q/49019694
tag name: arrays
tags question: http://stackoverflow.com/q/48990111
tags question: http://stackoverflow.com/q/48968054
tags question: http://stackoverflow.com/q/49096771
tags question: http://stackoverflow.com/q/49080273
tags question: http://stackoverflow.com/q/49097887
tags question: http://stackoverflow.com/q/49021027
tags question: http://stackoverflow.com/q/49049535
tags question: http://stackoverflow.com/q/49094098
tags question: http://stackoverflow.com/q/48988038
tags question: http://stackoverflow.com/q/49079102
tags question: http://stackoverflow.com/q/49116676
tags question: http://stackoverflow.com/q/49068615
tags question: http://stackoverflow.com/q/49065627
tags question: http://stackoverflow.com/q/49061865
tags question: http://stackoverflow.com/q/48979860
tags question: http://stackoverflow.com/q/49045804
tags question: http://stackoverflow.com/q/49054538
tags question: http://stackoverflow.com/q/49015558
tags question: http://stackoverflow.com/q/49050500
tags question: http://stackoverflow.com/q/49009159
tags question: http://stackoverflow.com/q/49056388
tags question: http://stackoverflow.com/q/49020628
tags question: http://stackoverflow.com/q/49041110
tags question: http://stackoverflow.com/q/49018980
tags question: http://stackoverflow.com/q/48966289
tags question: http://stackoverflow.com/q/48995089
tags question: http://stackoverflow.com/q/49114921

http://stackoverflow.com/a/49089007
downvote count: 0
has comment: http://stackoverflow.com/comment/85193078
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49088759
has comment: http://stackoverflow.com/comment/85191974
has body: Have a look at pandas.DataFrame.rolling df.rolling(window=3).apply(min).dropna() will give the expected result: datetime price 2017-10-02 08:05:00 12877.0 2017-10-02 08:06:00 12875.5 2017-10-02 08:07:00 12875.5 2017-10-02 08:08:00 12875.5 2017-10-02 08:09:00 12875.5 2017-10-02 08:10:00 12878.0 2017-10-02 08:11:00 12878.0 2017-10-02 08:12:00 12878.0 2017-10-02 08:13:00 12881.0 2017-10-02 08:14:00 12882.0 2017-10-02 08:15:00 12880.5 2017-10-02 08:16:00 12880.5 2017-10-02 08:17:00 12879.0 2017-10-02 08:18:00 12879.0 2017-10-02 08:19:00 12879.0 2017-10-02 08:20:00 12878.5
answers question: http://stackoverflow.com/q/49088759
type: Answer
score: 2

http://stackoverflow.com/comment/84954447
has text: [`protobuf_generate_python`](https://github.com/Kitware/CMake/blob/master/Modules/FindProtobuf.cmake#L213) does exist in `FindProtobuf.cmake`, so perhaps you aren't using it correctly?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48967021
score: 0

http://stackoverflow.com/q/49090296
answer count: 1
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49095766
accepted answer: http://stackoverflow.com/a/49095766
type: Question
has comment: http://stackoverflow.com/comment/85186181
has body: I'm trying to create a regex which will return TWO matches from either side of an OR like so: def parse_description(description): regex = r"^(Created by CreateImage\((.*?)\) for (.*?) |Copied for (DestinationAmi) (.*?) from SourceAmi (.*?))" matches = re.finditer(regex, description, re.MULTILINE) for matchNum, match in enumerate(matches): return match.groups() return '', '' with example string: Copied for DestinationAmi ami-33dfxxx from SourceAmi ami-9dd6xxx for SourceSnapshot snap-02f5xxx. Task created on 1,518,952,817,897. The problem I have is that this returns 4 matches, None, None, ami-33dfxxx, ami-9dd6xxx Having tried various things at https://pythex.org/ I cannot make this not return 4 matches even though, to my understanding, it shouldn't be. What am I doing wrong?
has comment: http://stackoverflow.com/comment/85194260
has title: Python Regex returning None from non-matching side of OR operator
score: 0

http://stackoverflow.com/q/49067258
accepted answer: http://stackoverflow.com/a/49067299
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/49067667
type: AnsweredQuestion
score: 1
has title: Calculating average from raw_input data in a while loop
downvote count: 1
has answer: http://stackoverflow.com/a/49067750
possible better answer: http://stackoverflow.com/a/49067406
has answer: http://stackoverflow.com/a/49067707
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/49067406
has answer: http://stackoverflow.com/a/49067299
has answer: http://stackoverflow.com/a/49067721
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85139541
has comment: http://stackoverflow.com/comment/85139686
has body: Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to: Constantly ask the user to enter any random positive integer using int(raw_input()) Once the user enters -1 the program needs to end the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out. this what I have so far: num = -1 counter = 1 anyNumber = int(raw_input("Enter any number: ")) while anyNumber &gt; num: anyNumber = int(raw_input("Enter another number: ")) counter += anyNumber answer = counter + anyNumber print answer print "Good bye!"
has answer: http://stackoverflow.com/a/49068218
has answer: http://stackoverflow.com/a/49067371
favorite count: 0

http://stackoverflow.com/a/49223023
type: Answer
answers question: http://stackoverflow.com/q/49041313
has comment: http://stackoverflow.com/comment/86730486
score: 1
upvote count: 1
downvote count: 0
has body: This fixed it for me: pip3 install google-assistant-library==0.1.0

http://stackoverflow.com/comment/85232614
type: QuestionComment
comment on: http://stackoverflow.com/q/49113243
score: 1
has text: @Calvin Have you read the help page on formatting? https://stackoverflow.com/help/formatting
type: Comment

http://stackoverflow.com/comment/84959633
has text: You're not calling `vignere(key, letter)` anywhere in your example... do you just need to call it with `key` and `letter` params?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48977023

strftime
type: Tag
tags question: http://stackoverflow.com/q/48992179
tag name: strftime

http://stackoverflow.com/comment/84971682
type: QuestionComment
has text: What error are you getting?
score: 0
comment on: http://stackoverflow.com/q/48983468
type: Comment

http://stackoverflow.com/comment/116464874
score: 0
type: Comment
has text: Just checking - Isn't that data_dict only a single row?
type: AnswerComment
comment on: http://stackoverflow.com/a/49112389

http://stackoverflow.com/comment/85161612
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49077802
has text: Could you do two assignments? Ie `A={"a": 1}; A["b"]=4*A["a"];`. At this point, A exists, and contains a `"a"` key with a value.
score: 0

http://stackoverflow.com/a/49077636
has body: You can run a script from a package using the -m switch and the fully qualified package path python -m subwayclock.subwayclock
answers question: http://stackoverflow.com/q/49077539
score: 0
type: Answer

http://stackoverflow.com/a/49088122
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49088078
score: 2
has comment: http://stackoverflow.com/comment/85182013
has body: When instantiating an Area pass it a reference to province like: Code: class Province: def __init__(self, stuff="spam"): self.stuff = stuff self.areas = list() def makeareas(self, area): self.areas.append(Areas(area, self)) class Areas: def __init__(self, area, province): self.area = area self.province = province def access_stuff(self): # access stuff of the Province where it is in its list return '%s - %s ' %(self.area, self.province.stuff) Test Code: p = Province('This is stuff') # Examples p.makeareas('area1') p.makeareas('area2') for area in p.areas: print(area.access_stuff()) Results: area1 - This is stuff area2 - This is stuff
accepted answer of: http://stackoverflow.com/q/49088078
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85577709
comment on: http://stackoverflow.com/a/49120336
score: 0
type: AnswerComment
type: Comment
has text: Ah - just played around with it a bit and got it to work. Cheers.

http://stackoverflow.com/comment/85155853
score: 0
type: Comment
type: QuestionComment
has text: Please let us know if you are actually struggling at a particular point. _Suggestion_: avoid loops when using _dataframes_ for such tasks.
comment on: http://stackoverflow.com/q/49074101

http://stackoverflow.com/comment/85102420
type: Comment
type: QuestionComment
has text: @OdatNurd I added the `sublime-build` file.
comment on: http://stackoverflow.com/q/48975692
score: 0

http://stackoverflow.com/a/49038783
has comment: http://stackoverflow.com/comment/85083249
has comment: http://stackoverflow.com/comment/85085250
has comment: http://stackoverflow.com/comment/85083633
score: 0
has body: Inside your child template (which extends base template) there is should be something like this: {% extends "base.html" %} {% load cms_tags %} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} {% placeholder "feature" %} {% placeholder "content" %} {% placeholder "splashbox" %} {% endblock content %} And base template should looks like this: {% load cms_tags menu_tags sekizai_tags %} {% block title %}This is my new project home page{% endblock title %} {% cms_toolbar %} {% show_menu 0 100 100 100 %} {% block content %}{% endblock content %}
has comment: http://stackoverflow.com/comment/85085451
answers question: http://stackoverflow.com/q/49038422
type: Answer

http://stackoverflow.com/comment/84954071
comment on: http://stackoverflow.com/a/48967247
has text: @AntonvBR Your updated answer added the clarity I needed. Thank you
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84954760
comment on: http://stackoverflow.com/q/48974747
score: 0
has text: You might seed a cdef in the loop. Add one for you subtracted variable.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85006557
comment on: http://stackoverflow.com/a/48999460
type: AnswerComment
type: Comment
has text: @rishijd since you only need the *first not-buy*, this will be the solution only target the firs not buy to the backward 1st buy time, that is why iloc[0] and iloc[-1]
score: 1

http://stackoverflow.com/q/49101325
answer count: 1
score: -1
tagged with: tkinter
has answer: http://stackoverflow.com/a/49101345
tagged with: file
has comment: http://stackoverflow.com/comment/85213333
has comment: http://stackoverflow.com/comment/85213266
downvote count: 1
has title: No file or Directory exist, but it does
upvote count: 0
linked to: http://stackoverflow.com/q/12201928
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85213296
linked to: http://stackoverflow.com/q/23901168
has body: I am trying to use tkinter module to open a window to show a picture and was previously having trouble with: _tkinter.TclError: couldn&#39;t recognize data in image I have since used the following this question to restructured my code to the following: How do I insert a JPEG image into a python Tkinter window? I have made a few changes to the code as I am using python 3. When I have tried to execute the code: I get an error saying no file or directory exist. However i have used the following code to check: python open() method IOError: [Errno 2] No such file or directory: Below are the result of checking the files: &gt;&gt;&gt; os.listdir() ['comments.py', 'Conan.txt', 'conditions.py', 'dateandtime.py', 'desktop.ini', 'dictionaries.py', 'exceptions.py', 'forging_functions.py', 'formatting.py', 'graphics.py', 'Hello.py', 'leapdays.py', 'logging.py', 'loop.py', 'modules.py', 'months.py', 'numbers.py.py', 'Opening_files.py', 'Picture.jpg', 'print_hello.py.py', 'tkintercode1.py', 'tkintercode2.py', 'user_input.py', 'Writing_file.py', '__pycache__'] &gt;&gt;&gt; os.getcwd() 'C:\\Users\\Draco\\OneDrive\\Documents\\Programming' &gt;&gt;&gt; os.chdir(r'C:\\Users\\Draco\\OneDrive\\Documents\\Programming') &gt;&gt;&gt; open('Picture.jpg') &lt;_io.TextIOWrapper name='Picture.jpg' mode='r' encoding='cp1252'&gt; Below is the code I am working with: import tkinter as tk from tkinter import * window = tk.Tk() window.title("Random Image") window.geometry("300x300") window.configure(background='grey') path = "C:\Draco\OneDrive\Documents\Programming\Picture.jpg" img = tkinter.PhotoImage(Image.open(path)) panel = tk.Label(window, image = img) panel.pack(side = "bottom", fill = "both", expand = "yes") window.mainloop() Many thanks for any help
has comment: http://stackoverflow.com/comment/85208111
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/49083318
has answer: http://stackoverflow.com/a/49094145
tagged with: transcrypt
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: magnifier.js
has body: I have tried to port a Javascript program for a magnifier via Transcrypt to Python code. Unfortunately I can not get rid of the frame of the magnifier which completely overrides the complete image. The orginal code was located here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_image_zoom The Python code I did out of it is: class Magnifier(): def __init__(self): self.img = document.getElementById("myimage") self.saved_src = self.img.src print(self.saved_src) self.resultat = document.getElementById("myresult"); # create lens: self.lens = document.createElement("DIV"); self.lens.setAttribute("class", "img-zoom-lens"); # insert lens: self.img.parentElement.insertBefore(self.lens, self.img); # calculate the ratio between result DIV and lens: self.cx = self.resultat.offsetWidth / self.lens.offsetWidth; self.cy = self.resultat.offsetHeight / self.lens.offsetHeight; # set background properties for the result DIV: self.resultat.style.backgroundImage = "url('" + self.img.src + "')"; self.resultat.style.backgroundSize = (self.img.width * self.cx) + "px " + (self.img.height * self.cy) + "px"; # execute a function when someone moves the cursor over the image, or the lens: window.addEventListener("mousemove", self.moveLens); self.img.addEventListener("mousemove", self.moveLens); # and also for touch screens: self.lens.addEventListener("touchmove", self.moveLens); self.img.addEventListener("touchmove", self.moveLens); console.log("run") self.counter = 0 def moveLens(self, e): # console.log("moveLens") self.img.src = self.saved_src + "?" + __new__(Date().getTime()) if (not e): e = window.event # only for IE which has window.event a = self.img.getBoundingClientRect(); # e.preventDefault() # get the cursor's x and y positions: # calculate the cursor's x and y coordinates, relative to the image: x = e.pageX - a.left; y = e.pageY - a.top; # print (a, e.pageX, e.pageY) # consider any page scrolling: x = x - window.pageXOffset; y = y - window.pageYOffset; # print (x, y) #…
has title: transcrypt and magnifier code
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/85064882
score: 0
type: QuestionComment
type: Comment
has text: You forgot to raw-ify the replacement string: `r",\1"`.
comment on: http://stackoverflow.com/q/49030188

http://stackoverflow.com/comment/84986968
type: QuestionComment
comment on: http://stackoverflow.com/q/48990631
has text: `window.location.reload` will refetch `/refresh`. It doesn't look like you're using websockets, which means each fetch is stateless, so your client-side timeout does nothing (chrome will timeout waiting for a response since your timeout just reloads the uri).
score: 0
type: Comment

http://stackoverflow.com/comment/85134536
comment on: http://stackoverflow.com/a/49064734
score: 0
type: AnswerComment
type: Comment
has text: But as i said, in my example, the timestep can be very small, which means the input data, will have so many more rows than the number of rows i have.

http://stackoverflow.com/a/49068395
score: 1
answers question: http://stackoverflow.com/q/49066933
has body: Another way is to use argparse: import argparse parser = argparse.ArgumentParser() parser.add_argument('--list1', nargs='*', required=True) parser.add_argument('--list2', nargs='*', required=True) args = vars(parser.parse_args()) print(args['list1']) print(args['list2']) Usage: python module_name.py --list1 x y z --list2 1 2 3 ['x', 'y', 'z'] ['1', '2', '3'] UPDATE I've noticed your comment for the previous answer. If you want to distinguish between strings and numbers you can do as following: import sys import json lists_str = '[' + ' '.join(sys.argv[1:]).replace('] [', '],[') + ']' lists = json.loads(lists_str) print(lists[0]) print(lists[1]) So now your input should be of form: python module_name.py [\"a\", \"b\", \"c\"] [1, 2, 3, \"a\"] and you will get: ['a', 'b', 'c'] [1, 2, 3, 'a'] Note that now your input lists can be of mixed types.
has comment: http://stackoverflow.com/comment/85147145
accepted answer of: http://stackoverflow.com/q/49066933
has comment: http://stackoverflow.com/comment/85145130
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85145966
type: Answer
has comment: http://stackoverflow.com/comment/85176219
downvote count: 0

http://stackoverflow.com/q/49095860
has comment: http://stackoverflow.com/comment/85196729
has answer: http://stackoverflow.com/a/52140724
has comment: http://stackoverflow.com/comment/85196696
has body: I'm trying to install Rasa Core so I installed pip install rasa_core ...and then I tried to install the development dependencies: pip install -r dev-requirements.txt pip install -e ...but I get this error: (base) C:\Users\\\rasa_core&gt;pip install -r requirements.txt Collecting apscheduler==3.5.0 (from -r requirements.txt (line 2)) Using cached APScheduler-3.5.0-py2.py3-none-any.whl Collecting fakeredis==0.9.0 (from -r requirements.txt (line 3)) Using cached fakeredis-0.9.0-py2.py3-none-any.whl Collecting future==0.16.0 (from -r requirements.txt (line 4)) Collecting graphviz==0.7.1 (from -r requirements.txt (line 5)) Using cached graphviz-0.7.1-py2.py3-none-any.whl Collecting h5py==2.7.0 (from -r requirements.txt (line 6)) Downloading h5py-2.7.0-cp36-cp36m-win_amd64.whl (1.9MB) 100% |████████████████████████████████| 1.9MB 3.9MB/s Collecting jsonpickle==0.9.4 (from -r requirements.txt (line 7)) Using cached jsonpickle-0.9.4.tar.gz Collecting keras==2.0.8 (from -r requirements.txt (line 8)) Using cached Keras-2.0.8-py2.py3-none-any.whl Requirement already satisfied: numpy==1.14.0 in f:\anaconda\lib\site-packages (from -r requirements.txt (line 9)) Collecting pandoc==1.0.0b2 (from -r requirements.txt (line 10)) Using cached pandoc-1.0.0b2.tar.gz Collecting redis==2.10.5 (from -r requirements.txt (line 11)) Using cached redis-2.10.5-py2.py3-none-any.whl Requirement already satisfied: six==1.11.0 in f:\anaconda\lib\site-packages (from -r requirements.txt (line 12)) Collecting tensorflow==1.4.1 (from -r requirements.txt (line 13)) Could not find a version that satisfies the requirement tensorflow==1.4.1 (from -r requirements.txt (line 13)) (from versions: 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.6.0rc0, 1.6.0rc1, 1.6.0) No matching distribution found for tensorflow==1.4.1 (from -r requirements.txt (line 13)) How can I fix this error?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85214347
upvote count: 1
tagged with: tensorflow
type: Question
score: 1
tagged with: rasa-nlu
linked to: http://stackoverflow.com/q/38896424
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85201062
answer count: 2
has answer: http://stackoverflow.com/a/50933238
downvote count: 0
has title: No matching distribution found for tensorflow==1.4.1
has comment: http://stackoverflow.com/comment/85257189
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/85197481

http://stackoverflow.com/q/49000893
tagged with: validation
has answer: http://stackoverflow.com/a/49000944
favorite count: 0
has body: I'm trying to validate if a directory received as user input exists using the os module This is how I'm accepting the input: directory = input("Hi ! \n please type a directory, thanks !") The idea is that I want to make sure the user will type an existing directory and nothing else
tagged with: python-3.x
upvote count: 8
has title: Python: Check if a directory exists using os module
has comment: http://stackoverflow.com/comment/85006980
downvote count: 2
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/85007743
has comment: http://stackoverflow.com/comment/85006992
has answer: http://stackoverflow.com/a/49001005
tagged with: python-os
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49001005
linked to: http://stackoverflow.com/q/8933237
type: Question
has comment: http://stackoverflow.com/comment/85006922
has comment: http://stackoverflow.com/comment/85006948
score: 6
answer count: 2
possible better answer: http://stackoverflow.com/a/49000944

http://stackoverflow.com/q/49033311
has body: import pandas as pd import numpy as np df = pd.DataFrame({'year': np.repeat(2018,12), 'month': range(1,13)}) In this data frame, I am interested in creating a field called 'year_month' such that each value looks like so: datetime.date(df['year'][0], df['month'][0], 1).strftime("%Y%m") I'm stuck on how to apply this operation to the entire data frame and would appreciate any help.
tagged with: python
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/49033732
upvote count: 1
has answer: http://stackoverflow.com/a/49033732
has answer: http://stackoverflow.com/a/49033493
accepted answer: http://stackoverflow.com/a/49033342
type: Question
answer count: 3
tagged with: pandas
downvote count: 0
has title: Applying Date Operation to Entire Data Frame
favorite count: 0
has answer: http://stackoverflow.com/a/49033342

http://stackoverflow.com/q/49018551
has answer: http://stackoverflow.com/a/49038287
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/85081096
has comment: http://stackoverflow.com/comment/85081005
type: Question
has answer: http://stackoverflow.com/a/49039403
has comment: http://stackoverflow.com/comment/85077259
answer count: 2
has body: I want to merge different files based on the conditions of the file names. For example, Name1_Stuff1_A.csv Name1_Stuff1_B.csv Name1_Stuff2_A.csv Name1_Stuff2_B.csv Name1_Stuff3_A.csv Name1_Stuff3_B.csv Merging: Name1_Stuff1_A + Name1_Stuff2_A + Name1_Stuff3_A -&gt; Name1_Total_A Name1_Stuff1_B + Name1_Stuff2_B + Name1_Stuff3_B -&gt; Name1_Total_B Then move on to another name, e.g., Name2, and so on I tried: for name in names: with open('{}_Total_A.csv'.format(name), 'a') as merged_file: for file in glob.glob('*.csv'): for line in open(file, 'r'): merged_file.write(line) But it only returned A (no B): Name1_Total_A.csv Name2_Total_A.csv And the A files are merged with all files. How can I do this: Name1_Total_A.csv Name2_Total_B.csv Name1_Total_A.csv Name2_Total_B.csv where Name1_Total_A.csv is merged in the order of Name1_Stuff1_A.csv, Name1_Stuff2_A.csv, and Name1_Stuff3_A.csv, and so are the other files Thanks!
has comment: http://stackoverflow.com/comment/85042325
tagged with: concatenation
upvote count: 0
favorite count: 0
has title: Merging different CSV files
has comment: http://stackoverflow.com/comment/85042351
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/49039403
has comment: http://stackoverflow.com/comment/85045632
has comment: http://stackoverflow.com/comment/85059582
tagged with: python
score: -2
tagged with: merge
possible better answer: http://stackoverflow.com/a/49038287
tagged with: append

http://stackoverflow.com/q/48970636
has body: I'm using: Raspberry Pi3 OS : Raspbian language : python 3.5 Geckodriver : geckodriver-v0.19.1-arm7hf (usr/local/bin/geckodriver) browser firefox esr (52.6.0 (32-bit)) Code: from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.python.org') Opening the browser is OK, but why did it fail to get URL? I don't know how to solve it.
type: Question
tagged with: python
tagged with: selenium-webdriver
upvote count: 1
has title: How can I use selenium in Raspbian python3?
answer count: 1
has answer: http://stackoverflow.com/a/48974602
tagged with: raspbian
tagged with: firefox
type: UnansweredQuestion
downvote count: 0
tagged with: raspberry-pi3
score: 1
favorite count: 0

http://stackoverflow.com/q/49080538
has answer: http://stackoverflow.com/a/49080943
score: 0
answer count: 2
tagged with: django
accepted answer: http://stackoverflow.com/a/49081456
has comment: http://stackoverflow.com/comment/85167097
tagged with: database
has title: Matching query does not exist error
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85166994
has answer: http://stackoverflow.com/a/49081456
has body: There are a bunch of people on this site have had a similar questions to mine, but I can't seem to find one that has solved it the way I want it to. I'm trying to get a password out of a database so that I can send an email automatically. To do this, I am calling Credential.objects.get(username='foo').password. This is where I get the error. What's really weird about this is I already had access to this database in a python console, and I've created a row in it. I have no clue why it's not showing up! Other people seem to recommend doing the following: try: Credential.objects.get(username='foo').password except Exception as e: return None All that this is doing is making sure the program doesn't return an error. This doesn't help me because this can't fail. An email must be sent and this call must get it. I'm almost certain I'm calling the right function for this, but I've been wrong before. Any help on this would be greatly appreciated. credential.py (not putting up max_length for security reasons): import d_models as models class Credential(models.Model): username = models.CharField() password = EncryptedCharField()
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/49080943

http://stackoverflow.com/comment/85197471
comment on: http://stackoverflow.com/q/49095720
type: Comment
type: QuestionComment
score: 1
has text: Look closely at the error message. It's telling you there's no such file named `"path"`. Pay attention to the last part -- it's looking for a file with the literal name `"path"` (_not_ with the name _stored_ in the variasble `path`). Though, fix that and you have two more problems: the backslashes don't do what you think they do, and `PhotoImage` doesn't support .jpg.

http://stackoverflow.com/comment/85009566
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49002399
has text: *Why did you make a copy* if you *don't want separate objects*?
score: 2

http://stackoverflow.com/q/49079115
favorite count: 0
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60426634
linked to: http://stackoverflow.com/q/48793510
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/68222970
type: Question
has title: ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_6/MaxPool' (op: 'MaxPool') with input shapes: [?,1,1,64]
upvote count: 22
has answer: http://stackoverflow.com/a/61770571
tagged with: neural-network
downvote count: 0
score: 22
has answer: http://stackoverflow.com/a/58498450
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49089027
has body: I am getting an error of Negative dimension size when I am keeping height and width of the input image anything below 362X362. I am surprised because this error is generally caused because of wrong input dimensions. I did not find any reason why number or rows and columns can cause an error. Below is my code- batch_size = 32 num_classes = 7 epochs=50 height = 362 width = 362 train_datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( 'train', target_size=(height, width), batch_size=batch_size, class_mode='categorical') validation_generator = test_datagen.flow_from_directory( 'validation', target_size=(height, width), batch_size=batch_size, class_mode='categorical') base_model = InceptionV3(weights='imagenet', include_top=False, input_shape= (height,width,3)) x = base_model.output x = Conv2D(32, (3, 3), use_bias=True, activation='relu') (x) #line2 x = MaxPooling2D(pool_size=(2, 2))(x) x = Conv2D(64, (3, 3), activation='relu') (x) #line3 x = MaxPooling2D(pool_size=(2, 2))(x) x = Flatten()(x) x = Dense(batch_size, activation='relu')(x) #line1 x = (Dropout(0.5))(x) predictions = Dense(num_classes, activation='softmax')(x) model = Model(inputs=base_model.input, outputs=predictions) for layer in base_model.layers: layer.trainable = False model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics= ['accuracy']) model.fit_generator( train_generator, samples_per_epoch=128, nb_epoch=epochs, validation_data=validation_generator, verbose=2) for i, layer in enumerate(base_model.layers): print(i, layer.name) for layer in model.layers[:309]: layer.trainable = False for layer in model.layers[309:]: layer.trainable = True from keras.optimizers import SGD model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossent…
tagged with: keras

http://stackoverflow.com/a/49011076
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/49007469
answers question: http://stackoverflow.com/q/49007469
has body: You need to use this url to filter: http://localhost:8000/Api/Identification/search/?NumeroIdentification=NUA_value. With requests library try to pass it with params argument: response = requests.get(url, params={'NumeroIdentification': NIU}, headers={'Authorization': 'JWT {}'.format(mytoken)}).
type: AcceptedAnswer
upvote count: 1
type: Answer

http://stackoverflow.com/q/48969483
has body: I have below code on toy data which works the day i want. Last 2 columns provide how many times value in column Jan was found in column URL and in how many distinct rows value in column Jan was found in column URL sales = [{'account': '3', 'Jan': 'xxx', 'Feb': '200 .jones', 'URL': 'ea2018-001.pdf try bbbbb why try'}, {'account': '1', 'Jan': 'try', 'Feb': '210', 'URL': ''}, {'account': '2', 'Jan': 'bbbbb', 'Feb': '90', 'URL': 'ea2017-104.pdf bbbbb cc for why try' }] df = pd.DataFrame(sales) df df['found_in_column'] = df['Jan'].apply(lambda x: ''.join(df['URL'].tolist()).count(x)) df['distinct_finds'] = df['Jan'].apply(lambda x: sum(df['URL'].str.contains(x))) why does the same code fails in the last case? How could i change my code to avoid the error. In case of my last example there are special characters in the first column, I felt that they are causing the problem. But when i look at row where index is 3 and 4, they have special characters too and code runs fine answer2=answer'Value','non_repeat_pdf'.iloc[0:11] print(answer2) Value non_repeat_pdf 0 effect\nive Initials: __\nDL_ -1- Date: __\n8/14/2017\n... 1 closing @@@@ 2 executing @@@@ 3 order, @@@@ 4 waives: @@@@ 5 right @@@@ 6 notice @@@@ 7 intention @@@@ 8 prohibit @@@@ 9 further @@@@ 10 participation @@@@ answer2['Value'].apply(lambda x: sum(answer2['non_repeat_pdf'].str.contains(x))) Out[220]: 0 1 1 0 2 1 3 0 4 1 5 1 6 0 7 0 8 1 9 0 10 0 Name: Value, dtype: int64 answer2=answer'Value','non_repeat_pdf'.iloc[10:11] print(answer2) Value non_repeat_pdf 10 participation @@@@ answer2['Value'].apply(lambda x: sum(answer2['non_repeat_pdf'].str.contains(x))) Out[212]: 10 0 Name: Value, dtype: int64 answer2=answer'Value','non_repeat_pdf'.iloc[11:12] print(answer2) Value non_repeat_pdf 11 1818(e); @@@@ answer2['Value'].apply(lambda x: sum(answer2['non_repeat_pdf'].str.contains(x))) Traceback (most recent call last): File "&lt;ipython-input-215-2df7f4b2de41&gt;", line 1, in &lt;module&gt; answer2['Value'].a…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84956318
has comment: http://stackoverflow.com/comment/84945247
tagged with: python
has answer: http://stackoverflow.com/a/48969715
has comment: http://stackoverflow.com/comment/84957673
has comment: http://stackoverflow.com/comment/84945559
type: Question
has comment: http://stackoverflow.com/comment/84945397
tagged with: contains
answer count: 1
has comment: http://stackoverflow.com/comment/84945226
tagged with: string
has comment: http://stackoverflow.com/comment/84945650
has comment: http://stackoverflow.com/comment/84945849
has title: python error when finding count of cells where value was found
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84950882
has comment: http://stackoverflow.com/comment/84945315

http://stackoverflow.com/q/49117784
tagged with: python
has comment: http://stackoverflow.com/comment/85240995
has comment: http://stackoverflow.com/comment/85240982
linked to: http://stackoverflow.com/q/19158339
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85240893
has title: Accessing global variable dynamically across modules
score: 1
has comment: http://stackoverflow.com/comment/85241145
has body: Using something from on another page on this site, I've managed to create global variables that are accessible across modules by doing something along the lines of-- Mod1.py-- def init(): global testVar mod2.py-- import mod1 mod1.init() print(mod1.testVar) How, though, in mod2.py, can I dynamically access global variables in mod1? Something like-- nameOfVarThatIWant = 'testVar' print(mod1.globals()[nameOfVarThatIWant])
type: Question
has answer: http://stackoverflow.com/a/49118000
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85241082
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85241057
has comment: http://stackoverflow.com/comment/85241219
has comment: http://stackoverflow.com/comment/85240862

http://stackoverflow.com/a/49080977
accepted answer of: http://stackoverflow.com/q/49080919
score: 1
upvote count: 1
downvote count: 0
has body: label_name is a local variable within the on_enter function, and local variables can only be accessed within the function or scope where they were created. If you want to be accessible a possible solution is to make it a property of the widget: from kivy.properties import StringProperty class FlashDisplayPage(Screen): label_name = StringProperty("") def on_enter(self): [...] self.label_name='Flash Card {}'.format(Num) [...]
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49080919

http://stackoverflow.com/a/49000944
score: 7
downvote count: 0
has body: from pathlib import Path def is_valid_directory(filename): p = Path(filename) return p.exists() and p.is_dir() pathlib is an enormously convenient module for working with file paths of any sort. The p.exists() call is redundant since p.is_dir() returns False for nonexistent paths, but checking both would allow you to e.g. give better error messages. EDIT: Note that pathlib was added in Python 3.4. If you're still using an old version for whatever reason, you can use the older os.path.isdir(filename) function.
type: Answer
answers question: http://stackoverflow.com/q/49000893
upvote count: 7

http://stackoverflow.com/comment/84993762
has text: Hi @Vladimir F, I have edited my question and put complete fortran and python codes. Let me know if you have any idea of what's going on. Thank you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48979197
score: 0

http://stackoverflow.com/q/49093856
tagged with: python-3.x
linked to: http://stackoverflow.com/q/240178
has title: Function append in python 3
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/240178
accepted answer: http://stackoverflow.com/a/49093893
score: 0
upvote count: 1
downvote count: 1
type: Question
has body: I wonder why append add a number to every list that I have in my list. Not only to that one ([0]) that I have choosen. What's the difference between writing [0] or any other number next to append? j = [[]] * 5 j[0].append(5) # add 5 to every list on list j[1].append(4) # what's the diffrence? [1] or [0]; it adds number to every element anyway print (j) j.append(0) # add 0 to the main list print (j)
tagged with: function
answer count: 2
possible better answer: http://stackoverflow.com/a/49093872
has answer: http://stackoverflow.com/a/49093893
has answer: http://stackoverflow.com/a/49093872
favorite count: 0

http://stackoverflow.com/comment/85238887
type: QuestionComment
comment on: http://stackoverflow.com/q/49116476
has text: It is a programming question; I just don't understand how to generalize a 3-unknown solving on python
score: 0
type: Comment

http://stackoverflow.com/a/49077917
has body: Use a lambda function, then call A["b"] when you want the proper value: &gt;&gt;&gt; A={"a": 1} &gt;&gt;&gt; A["b"]= lambda: 4*A["a"] &gt;&gt;&gt; A["b"]() 4 &gt;&gt;&gt; A["a"] = 5 &gt;&gt;&gt; A["b"]() 20 Updated for the case where A["a"] is a list: &gt;&gt;&gt; A={"a": [1,2,3,4,5]} &gt;&gt;&gt; A["b"]= lambda: [4*i for i in A["a"]] &gt;&gt;&gt; A["b"]() [4, 8, 12, 16, 20]
score: 3
answers question: http://stackoverflow.com/q/49077802
downvote count: 0
has comment: http://stackoverflow.com/comment/85163307
type: Answer
has comment: http://stackoverflow.com/comment/85163439
upvote count: 3

http://stackoverflow.com/q/49108795
tagged with: multiple-columns
has comment: http://stackoverflow.com/comment/85228804
has comment: http://stackoverflow.com/comment/85223152
has title: Merging a column from one file to another based on unique pair combination
has body: I need to merge the "value" column of the File 2 to the File 1 in such a way that the col1-col2 unique pair combination remains intact.unmatched ones can be skipped. I am a newbie to python/awk. So, I need guidelines or ideas to solve the problem. I don't have permission to use python pandas package, so would appreciate other alternative solutions. Thanks in advance for kind support. File 1 col1 col2 559 1 558 1 559 0 558 0 558 1 557 1 558 0 557 0 504 2 255 0 504 1 192 0 504 0 367 0 255 0 187 1 227 0 185 0 192 0 187 0 187 0 185 1 185 0 183 1 183 0 171 1 171 0 9 0 1236 1 766 0 1236 0 903 0 File 2 col1 col2 value 559 1 91987224 2400000000 559 0 91987224 100000000 558 1 64064811 2400000000 558 0 91987224 100000000 557 1 59966218 2400000000 557 0 64064811 100000000 555 0 59966218 2500000000 533 0 87947477 5000000000 504 2 53048833 1000000000 504 1 19225707 100000000 504 0 35811624 5000000000 255 0 1687416 2800000000 227 0 101635574 100000000 192 0 7894664 100000000 187 0 1687416 2900000000 185 0 1687416 3000000000 183 0 1687416 4000000000 171 0 1687416 5000000000 desired output : 559 1 2400000000 559 0 100000000 558 1 2400000000 558 0 100000000 557 1 2400000000 557 0 100000000 555 0 2500000000 533 0 5000000000 504 2 1000000000 504 1 100000000 504 0 5000000000 255 0 2800000000 227 0 100000000 192 0 100000000 187 0 2900000000 185 0 3000000000 183 0 4000000000 171 0 5000000000 1236 1 - 1236 0 -
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/49115115
accepted answer: http://stackoverflow.com/a/49115115
tagged with: unix
has comment: http://stackoverflow.com/comment/85222869
type: AnsweredQuestion
type: Question
score: 0
answer count: 1
tagged with: awk

http://stackoverflow.com/a/49004442
has body: Use stack + rename_axis + reset_index: df1 = df.stack().rename_axis(('from','to')).reset_index(name='value') print (df1) from to value 0 A A 1.0 1 A B 0.2 2 A C 0.4 3 B A 0.2 4 B B 1.0 5 B C 0.6 6 C A 0.4 7 C B 0.6 8 C C 1.0 Another numpy solution: a = np.repeat(df.columns, len(df.index)) b = np.tile(df.index, len(df.columns)) c = df.values.ravel() df1 = pd.DataFrame({'from':a, 'to':b, 'value':c}) print (df1) from to value 0 A A 1.0 1 A B 0.2 2 A C 0.4 3 B A 0.2 4 B B 1.0 5 B C 0.6 6 C A 0.4 7 C B 0.6 8 C C 1.0 EDIT: Another solution for remove duplicates: df = pd.DataFrame([[1,0.2,0.4],[0.2,1,0.6],[0.4,0.6,1]]) df.columns = list('ACC') df.index= list('ABC') print (df) A C C A 1.0 0.2 0.4 B 0.2 1.0 0.6 C 0.4 0.6 1.0 a = np.repeat(df.columns, len(df.index)) b = np.tile(df.index, len(df.columns)) c = df.values.ravel() df1 = pd.DataFrame({'from':a, 'to':b, 'value':c}) df1 = (pd.DataFrame(np.sort(df1'from','to', axis=1), columns=['from','to']) .drop_duplicates()) print (df1) from to 0 A A 1 A B 2 A C 4 B C 5 C C
has comment: http://stackoverflow.com/comment/85013480
upvote count: 4
has comment: http://stackoverflow.com/comment/85014008
score: 4
has comment: http://stackoverflow.com/comment/85013524
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49004398
type: Answer
accepted answer of: http://stackoverflow.com/q/49004398

http://stackoverflow.com/a/49085201
accepted answer of: http://stackoverflow.com/q/49084795
score: 1
has comment: http://stackoverflow.com/comment/85176103
upvote count: 1
has comment: http://stackoverflow.com/comment/85176262
has comment: http://stackoverflow.com/comment/85176084
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49084795
has body: Use loc with mean: dataset['new measure'] = dataset.loc[:, 'Feature 1':'Feature 12'].mean(axis=1) Sample: dataset = pd.DataFrame({'A':list('abcdef'), 'Feature 1':[4,5,4,5,5,4], 'Feature 2':[7,8,9,4,2,3], 'Feature 3':[1,3,5,7,1,0], 'Feature 4':[5,3,6,9,2,4], 'F':list('aaabbb')}) #print (dataset) dataset['new measure'] = dataset.loc[:, 'Feature 1':'Feature 4'].mean(axis=1) print (dataset) A F Feature 1 Feature 2 Feature 3 Feature 4 new measure 0 a a 4 7 1 5 4.25 1 b a 5 8 3 3 4.75 2 c a 4 9 5 6 6.00 3 d b 5 4 7 9 6.25 4 e b 5 2 1 2 2.50 5 f b 4 3 0 4 2.75
type: Answer

http://stackoverflow.com/a/49547095
has comment: http://stackoverflow.com/comment/86141156
score: 0
has body: Since the model was trained after 100 epochs, you can infer the model and find the accuracy on CPU itself because it is not computationally heavy. But if you want to observe the accuracy while training, then it can be hard to find accuracy from each GPUs and averaging, which might not tell how good is the model that is being trained.
type: Answer
answers question: http://stackoverflow.com/q/49068425

http://stackoverflow.com/q/49004349
has comment: http://stackoverflow.com/comment/85023108
tagged with: python
has answer: http://stackoverflow.com/a/49010212
has title: Python/Simulink/MATLAB: How to properly read single-type 4bytes data from Simulink in Python?
tagged with: simulink
type: AnsweredQuestion
tagged with: data-conversion
accepted answer: http://stackoverflow.com/a/49010212
type: Question
tagged with: python-2.7
score: 0
answer count: 1
tagged with: type-conversion
has body: I have a program in Simulink to send some values through TCP-IP and to read them in Python 2.7. The data is sent as "single" values. The code in Python reads that as 4 strings as its 32 bits long (string of length 4). print "x0:", ord(data[0]) print "x1:", ord(data[1]) print "x2:", ord(data[2]) print "x3:", ord(data[3]) The problem is, I get some different values in Python than that being sent. 0.125 is read as x0: 62, x1: 0, x2: 0, x3: 0 13.65 is read as x0:65, x1=90, x2: 96, x3: 0 51.79 is read as x0:66, x1=79, x2: 42, x3: 128 113.4 is read as x0:66, x1=226, x2: 200, x3: 220 So how to get these values... 0.125, 13.65, 51.79, 113.4, ... as proper numbers on the receive side (Python)?

http://stackoverflow.com/comment/85062179
type: AnswerComment
comment on: http://stackoverflow.com/a/49028656
score: 0
type: Comment
has text: I should have learned some more about how Python handles inheritance. I was a bit unaware of super(). Thanks.

http://stackoverflow.com/a/49056869
has comment: http://stackoverflow.com/comment/85119819
has comment: http://stackoverflow.com/comment/85123088
has comment: http://stackoverflow.com/comment/85119796
score: 1
has comment: http://stackoverflow.com/comment/85132473
has comment: http://stackoverflow.com/comment/85124528
has comment: http://stackoverflow.com/comment/85123197
answers question: http://stackoverflow.com/q/49056755
has comment: http://stackoverflow.com/comment/85123232
upvote count: 1
has body: Try to use below XPath: //td[contains(., "Fiscal Yr")]/following-sibling::td/a[img[@title="Edit Filter"]] You might need to use ExplicitWait for dynamic nodes: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait as wait from selenium.webdriver.support import expected_conditions as EC wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//td[contains(., "Fiscal Yr")]/following-sibling::td/a[img[@title="Edit Filter"]]'))).click()
has comment: http://stackoverflow.com/comment/85121385
has comment: http://stackoverflow.com/comment/85121289
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85120289
has comment: http://stackoverflow.com/comment/85123266

http://stackoverflow.com/comment/85204205
has text: Thank you so much for your support it helped me a lot. btw what is built-in list ? I got idea of actual list - like in abbove explanation it is my_list.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49099216

http://stackoverflow.com/q/49084526
answer count: 1
downvote count: 0
tagged with: units-of-measurement
favorite count: 0
has title: Why doesn't sympy support units with 0 magnitude?
upvote count: 2
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: sympy
has comment: http://stackoverflow.com/comment/85184001
has answer: http://stackoverflow.com/a/49087253
score: 2
has body: The title says it all... why does sympy have the following behavior? import sympy.physics.units as u print(0*u.meter) # &gt;&gt;&gt; 0 And Pint has this behavior: import pint u = pint.UnitRegistry() print(0*u.meter) # &gt;&gt;&gt; 0 meter I think I prefer pint's behavior, because it allows for dimensional consistency. 0 is a proper magnitude of some unit. For instance, 0 degrees kelvin has a definitive meaning... it's not just the absence of anything... So I realize the contributors of sympy probably chose this implementation for some reason. Can you help me see the light?

http://stackoverflow.com/comment/85178006
score: 1
comment on: http://stackoverflow.com/q/49086222
has text: how this string `O1A2 text IEFF text 1A` should be treated?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49093732
answer count: 1
tagged with: python
has body: I am a new user for python and I know there are a few discussions about this; however, I still cannot fix it. I execute my homework as the following code: How to fix the error in my code? please advise, thanks!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85194164
type: Question
tagged with: numpy
has title: numpy.ndarray is object is not callable in my case
score: 0
has answer: http://stackoverflow.com/a/49093787
accepted answer: http://stackoverflow.com/a/49093787

http://stackoverflow.com/comment/85046029
score: 0
comment on: http://stackoverflow.com/q/49019609
type: Comment
type: QuestionComment
has text: That does not work

http://stackoverflow.com/comment/85127712
type: AnswerComment
score: 0
type: Comment
has text: This does not seem to work unless i just do it on one of the datapoints i.e. t[1] or t[0]
comment on: http://stackoverflow.com/a/49058328

http://stackoverflow.com/q/49022470
has answer: http://stackoverflow.com/a/49697714
has answer: http://stackoverflow.com/a/49069599
tagged with: python
tagged with: psycopg2
has answer: http://stackoverflow.com/a/49584678
accepted answer: http://stackoverflow.com/a/49584678
type: AnsweredQuestion
has body: When I create database from pgadmin 4, it always show error popup: Error saving properties. My computer info: Linux Mint 18.3 pgAdmin 4 2.1 from https://wiki.postgresql.org/wiki/Apt Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] My error in pgadmin4.log: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/werkzeug/serving.py", line 180, in run_wsgi execute(self.server.app) File "/usr/lib/python3/dist-packages/werkzeug/serving.py", line 168, in execute application_iter = app(environ, start_response) File "/usr/lib/python3/dist-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/usr/lib/python3/dist-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/usr/lib/python3/dist-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/lib/python3/dist-packages/flask/_compat.py", line 33, in reraise raise value File "/usr/lib/python3/dist-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/usr/lib/python3/dist-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/lib/python3/dist-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/lib/python3/dist-packages/flask/_compat.py", line 33, in reraise raise value File "/usr/lib/python3/dist-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/usr/lib/python3/dist-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/usr/lib/python3/dist-packages/flask/views.py", line 84, in view return self.dispatch_request(*args, **kwargs) File "/usr/share/pgadmin4/web/pgadmin/browser/utils.py", line 242, in dispatch_request return method(*args, **kwargs) File "/usr/share/pgadmin4/web/pgadmin/browser/server_groups…
has title: Error when create database from pgadmin4
type: Question
possible better answer: http://stackoverflow.com/a/49069599
has comment: http://stackoverflow.com/comment/85079716
score: 0
answer count: 3
tagged with: pgadmin-4

http://stackoverflow.com/comment/85176964
score: 1
type: Comment
type: QuestionComment
has text: `[i() for i in l]`?
comment on: http://stackoverflow.com/q/49085821

http://stackoverflow.com/comment/85086848
type: AnswerComment
has text: @KenY-N Sure. Added.
type: Comment
comment on: http://stackoverflow.com/a/49040681
score: 2

http://stackoverflow.com/comment/85221803
score: 0
type: Comment
type: QuestionComment
has text: Hey! why you need links working for that? Its just a simple question.
comment on: http://stackoverflow.com/q/49108465

http://stackoverflow.com/a/49056975
upvote count: 20
downvote count: 0
has body: Simply because the socketC, being the instance of a REQ archetype, cannot ever send another message ( as was coded inside the implementation of the .send() class-method above ), without a prior call to socketC.recv() instance-method. Both REQ and REP archetypes are well documented to have to obey a two-step dance of .send()-.recv()-.send()-.recv()-... resp. .recv()-.send()-.recv()-... using their native instance-methods. This is how the ZeroMQ REQ / REP sockets were designed and documented.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85118780
type: Answer
answers question: http://stackoverflow.com/q/49056602
accepted answer of: http://stackoverflow.com/q/49056602
score: 20

http://stackoverflow.com/comment/85031082
type: AnswerComment
comment on: http://stackoverflow.com/a/49011930
type: Comment
has text: Thanks! But it can't download the image...:(
score: 0

http://stackoverflow.com/q/49111440
has body: I have a list of dictionaries: [ defaultdict(&lt;class 'dict'&gt;, { 'account_id': '', 'address': { 'address_country': 'ZM', 'city': 'North Matthewland', 'state': 'Nevada', 'street_name': 'Cabrera Extensions', 'street_number': 197, 'zip_code': '81431'}, 'affiliate_id': 12, 'brand': 'TTT', 'country': 'ZM', 'email': 'rosariojohn@TTT.zed', 'first_name': 'Peter', 'last_name': 'Green', 'leadsource': 559, 'password': 'test385', 'phone_number': '052839601'},)] In my situation, I need to put all this data to CSV file, so via csv module, I try to write all this data to CSV file but I receive every time error message: ValueError: dict contains fields not in fieldnames: 'address' So I add to 'fieldnames' address, but the problem is that I receive all data in one column of address. with open('test_file.csv', 'w') as csvfile: filed_names = ['first_name', 'last_name', 'email', 'phone_number', 'password', 'country', 'leadsource', 'affiliate_id', 'account_id', 'brand', 'street_number', 'street_name', 'city', 'state', 'address_country', 'zip_code', ] writer = csv.DictWriter(csvfile, fieldnames=filed_names) writer.writeheader() writer.writerows(list_user_details)
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
possible better answer: http://stackoverflow.com/a/49112267
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49112267
score: 1
type: Question
has answer: http://stackoverflow.com/a/49111622
accepted answer: http://stackoverflow.com/a/49111622
answer count: 2
has title: List of dictionaries to CSV file
downvote count: 0

http://stackoverflow.com/q/49118273
answer count: 0
type: UnansweredQuestion
type: Question
has title: Keras ImageDataGenerator.flow filenames
tagged with: image-processing
has body: I have a folder full of 2500 numbered images and a labels.txt file with comma separated labels in the order of the image filename numbers. I'd like to generate random rotations (10x the number of original training samples, 25000 total), save the new images with numbered names from 1 to 25000, then create a new labels.txt file with comma separated label values in the order of the numbered images. The main problem I am having with this approach is that I can't seem to either set batch_size to be larger than the total number of images (ideally), or set save_prefix to an iterator that counts images disregarding batch number (since if I do 10 batches of 2500 I think the names will get messed up). Is there any way to do this? Here's my code so far: n_images = 2500 datagen = ImageDataGenerator(rotation_range=180) # fit parameters from data datagen.fit(X_train) # configure batch size and retrieve one batch of images for X_batch, y_batch in datagen.flow(X_train, y_train, seed=42, batch_size=10*n_images, save_to_dir=augment_path, save_prefix='aug', save_format='png', shuffle=False): # convert labels back and write to file nums = y_batch.argmax(axis=1)+1 write_labels = ','.join([str(i) for i in nums.tolist()])+',' f = open(augment_path+"/labels.txt", "a+") f.write(write_labels) f.close() break Also, what does the last number added to the saved images indicate? For example, aug_0_1685.png.
upvote count: 2
tagged with: keras
favorite count: 0
tagged with: saving-data
tagged with: python
tagged with: generator
score: 2
downvote count: 0

http://stackoverflow.com/q/49103877
tagged with: attributes
has body: I have a set of code that looks like this: class DataFilter: def __init__(self, csvData): # converts csv string data to float lists, if possible data = [] for line in csvData: try: line = line.split(',') except: print(line) return for i in range( len(line) ): try: line[i] = float(line[i]) except ValueError: pass data.append(line) self.data = data def find_depth_index(self, depth): for index, line in enumerate( self.data ): if line[1] &gt; depth: return index def remove_above_depth(self, depth): index = self.find_depth_index( depth ) return self.data[ index: ] def remove_beyond_depth(self, depth): index = self.find_depth_index(depth) return self.data[ :index ] data = DataFilter(data).remove_above_depth(SURF_CASING_DEPTH) print('-----------------------') data = DataFilter(data).remove_beyond_depth(VERTICAL_SEC_DEPTH) Then it give me an error: File "C:/Users/Eric Soobin Kim/PycharmProjects/untitled/RAPID_use_filtered_data.py", line 35, in remove_beyond_depth def remove_beyond_depth(self, depth): File "C:/Users/Eric Soobin Kim/PycharmProjects/untitled/RAPID_use_filtered_data.py", line 26, in find_depth_index def find_depth_index(self, depth): AttributeError: 'DataFilter' object has no attribute 'data' The thing that I don't understand is that, it ran without a problem for the line: data = DataFilter(data).remove_above_depth(SURF_CASING_DEPTH) but its not working for, data = DataFilter(data).remove_beyond_depth(VERTICAL_SEC_DEPTH) I think my first filtering somehow alters elements in __ini__(), but i don't know what's going on. Why is this happening, and how can i fix it?
has answer: http://stackoverflow.com/a/49103909
accepted answer: http://stackoverflow.com/a/49103909
has comment: http://stackoverflow.com/comment/85213523
possible better answer: http://stackoverflow.com/a/49103950
has title: Python, class attribute error
tagged with: object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85213419
score: 1
type: Question
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49103950
downvote count: 0
has comment: http://stackoverflow.com/comment/85213068
favorite count: 0
tagged with: class
tagged with: python

http://stackoverflow.com/a/50888765
has comment: http://stackoverflow.com/comment/101087536
has comment: http://stackoverflow.com/comment/96627075
type: Answer
has comment: http://stackoverflow.com/comment/91261430
has body: I use Linux distros and face the problem since the new installation of Python 3.6. I tried a couple of solution and finally solved the problem. The steps I followed are as below. On Debian like distros sudo apt-get install build-essential checkinstall libreadline-gplv2-dev ibncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev Change the directory to the Python3.6 location cd /path/to/Python3.6/Module/ In the module directory, open the Setup file with your preferred text editor vi Setup Search for SSL and uncomment the related lines. ssl _ssl.c \ -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ -L$(SSL)/lib -lssl -lcrypto Save the file and on the root folder of your Python package, run the following command. make sudo make install And finally, run the pip3 to install your required module(s).
score: 10
upvote count: 10
answers question: http://stackoverflow.com/q/49094768
has comment: http://stackoverflow.com/comment/99263324
downvote count: 0

http://stackoverflow.com/comment/84960856
type: QuestionComment
type: Comment
has text: Do you have to choose options on the dialog or just OK? If no options why not use osx notification Center?
comment on: http://stackoverflow.com/q/48976791
score: 0

http://stackoverflow.com/comment/85077179
type: QuestionComment
comment on: http://stackoverflow.com/q/49036075
score: 0
has text: example of data variable output would be helpful
type: Comment

http://stackoverflow.com/a/49175487
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49095668
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49095668
type: Answer
has body: For those who are looking for more information / guidelines: Mike Bayer wrote a pretty detailed response to my question at https://groups.google.com/forum/#!topic/sqlalchemy/u9Igta1CYdo .
has comment: http://stackoverflow.com/comment/90724154

http://stackoverflow.com/comment/85044942
type: Comment
has text: basically u are trying to get NewList as ur output right ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49019876

http://stackoverflow.com/q/49058134
has body: I have written a small python program to help me find all .mp3 files in a definite directory and then copy them to a desired directory. I have executed the program from the Administrator Command Promt but this has not worked for me. Do you have any suggestions? This is the error I get: Traceback (most recent call last): File "D:\Users\Martin\Desktop\copyMusic.py", line 11, in &lt;module&gt; copyfile(datoteka, destination) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\shutil.py", line 121, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: 'Desired Location To Copy The Files To' Here is the code: # import glob from shutil import copyfile import time destination = "Desired Location To Copy The Files To" files = glob.glob("FolderWithTheMusicFiles/*.mp3") for file in files: copyfile(file, destination) # Thank you all for your time and effort!
answer count: 0
type: UnansweredQuestion
has title: Python program to copy files from one folder to another; PermissionError [Errno 13]
type: Question
has comment: http://stackoverflow.com/comment/85122689
has comment: http://stackoverflow.com/comment/85121484
score: 0
has comment: http://stackoverflow.com/comment/85121363
tagged with: windows
tagged with: python

http://stackoverflow.com/q/49100945
tagged with: boto3
has comment: http://stackoverflow.com/comment/85207213
score: 0
has title: TypeError: cannot convert the series to <class 'float'> iterrows
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/53941011
has body: I'm trying to get python to read a row from a csv, and then place the contents into DynamoDB, then do the same with each subsequent row, until the end. I've modified Amazon's example code so that it reads like this: from __future__ import print_function # Python 2/3 compatibility import boto3 import decimal import pandas as pd dynamodb = boto3.resource('dynamodb', region_name='us-west-2', aws_access_key_id='123456789', aws_secret_access_key='987654321') table = dynamodb.Table('Loyalty_One') data = pd.read_csv('testdb.csv') data'collector_key' = data'collector_key'.astype(float) for i, rows in data.iterrows(): collector_key = float(data['collector_key']) sales = float(data['sales']) print("Adding data:", collector_key, sales) table.put_item( Item={ 'collector_key': collector_key, 'sales': sales, } ) When I do, I get the error: TypeError: cannot convert the series to You can see the file here, it's nothing out of the ordinary: https://s3.amazonaws.com/vshideler-data/testdb.csv It seems to me that line 16 (and 17) should be extracting the contents of each row in the column. I thought that it might be possible that the header is interfering but doing pd.read_csv with "header=None" just gets me a different error altogether. (although it occurs to me that I can probably just use the original dataframe instead of a csv file)
type: UnansweredQuestion
tagged with: amazon-dynamodb
has comment: http://stackoverflow.com/comment/85207286
tagged with: python
has comment: http://stackoverflow.com/comment/85207131
has comment: http://stackoverflow.com/comment/85207589
type: Question
tagged with: dataframe

http://stackoverflow.com/q/49010606
has answer: http://stackoverflow.com/a/49010948
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/85026744
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49011035
type: Question
score: 3
has comment: http://stackoverflow.com/comment/85028650
has title: Change Spyder's error colors
has comment: http://stackoverflow.com/comment/85029119
tagged with: ipython
answer count: 2
has body: I would like to change the Error colors in the IPython console in Spyder. Is that possible? I use Spyder 3.6 (if it matters). The error message is a mix of green and yellow... I have no know issues with my vision and I find it quite hard to read. Here is an example:
favorite count: 0
upvote count: 3

http://stackoverflow.com/q/49102662
type: Question
tagged with: sql
answer count: 1
has body: I have one sql table that contains keywords and occurrences likes so (though the occurrences are not important): ____________ dog | 3 | ____________ rat | 7 | ____________ cat | 9 | ____________ rat | 2 | ____________ and what I want to do is create a new table where each column is a unique keyword from the first table as well as an id. Like so _______________________ randomID|rat |cat |dog| ______________________ I'm not too sure how to go about doing this. I am writing to the first table using python, but if I can do this in MySQL workbench with a create Table that would be preferable! Thank you!
tagged with: python
has comment: http://stackoverflow.com/comment/85210532
type: UnansweredQuestion
score: 0
tagged with: mysql
has answer: http://stackoverflow.com/a/49103085
has title: Creating a new sql table where columns are derived from another sql table

http://stackoverflow.com/comment/85040682
score: 0
type: AnswerComment
has text: I have tried to implement what you suggested but it wont enable the button. I have updated the code to show what I have been trying to do with flags.
type: Comment
comment on: http://stackoverflow.com/a/49013222

http://stackoverflow.com/comment/85165665
type: Comment
score: 2
has text: yeah, but too late.
type: AnswerComment
comment on: http://stackoverflow.com/a/49079911

http://stackoverflow.com/comment/137056290
score: 0
has text: No, it won't make an inplace change.
type: AnswerComment
comment on: http://stackoverflow.com/a/65304855
type: Comment

http://stackoverflow.com/comment/85071641
type: QuestionComment
type: Comment
score: 1
has text: Google's APIs have quotas and rate limits. To use the `next_page_token` some delay is required.
comment on: http://stackoverflow.com/q/49033243

http://stackoverflow.com/q/49101482
has answer: http://stackoverflow.com/a/49102134
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/85208481
upvote count: 3
tagged with: math
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49102134
has body: Given a spherical shell volume (i.e. one sphere subtracted by a smaller sphere of same center) I need to calculate all integral positions within this volume. I can do this easily by calculating all integral points within the outer radius (by a cartesian product of all integers up to the outer diameter) and subsequently removing the points within the inner radius. However, in some situations the radii can be rather large, such that generating all the points within the outer radius can be more time consuming than I would like. So I would like to eliminate the processing time wasted calculating the points within the inner radius (or at least minimize the number necessary), if possible. Here is some current code, however the radii can be larger. import numpy as n import numpy.linalg as la def cartesian_product(*arrays): la = len(arrays) dtype = n.result_type(*arrays) arr = n.empty([len(a) for a in arrays] + [la], dtype=dtype) for i, a in enumerate(n.ix_(*arrays)): arr[..., i] = a return arr.reshape(-1, la) def points_in_shell(inner_radius, outer_radius): cutoff = int(n.ceil(outer_radius)) int_range = n.arange(-cutoff, cutoff+1) pos_initial = cartesian_product(int_range, int_range, int_range) pos_norm = la.norm(pos_initial, axis=1) valid_idx = n.where((pos_norm &gt;= inner_radius) &amp; (pos_norm &lt;= outer_radius)) pos_final = pos_initial[valid_idx] return pos_final vals = points_in_shell(89.634, 95.254) Any thoughts?
has comment: http://stackoverflow.com/comment/85209081
has answer: http://stackoverflow.com/a/49101937
has title: Generating integral points within a spherical shell
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/49101937
favorite count: 0
type: Question

http://stackoverflow.com/q/49032571
has answer: http://stackoverflow.com/a/49847138
downvote count: 0
has answer: http://stackoverflow.com/a/49987669
favorite count: 0
upvote count: 8
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49071910
answer count: 4
score: 8
has comment: http://stackoverflow.com/comment/85128948
has title: Import tensorflow error: terminate called after throwing an instance of 'Xbyak::Error'
has comment: http://stackoverflow.com/comment/85148816
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49162426
has body: I am trying to debug an error with tensorflow. When I import tensorflow I get the following error import tensorflow as tf terminate called after throwing an instance of 'Xbyak::Error' what(): internal error Aborted (core dumped) Here are the install details OS &gt;&gt; Ubuntu 14.04 Install Method Anaconda &gt;&gt; conda 4.4.11 (conda install tensorflow) python3 --version &gt;&gt; Python 3.6.4 :: Anaconda, Inc. If anyone has experience or knowledge on how to fix this issue, I would be most grateful. A search here, on google and on github yielded suggested the issue is likely with MKL-DNN, has anyone found a work around?

http://stackoverflow.com/comment/84992495
comment on: http://stackoverflow.com/q/48992680
score: 0
type: Comment
type: QuestionComment
has text: I found the code, ran it, and, ecept for an indentation error, everything worked fine. Try copying and pasting the code you posted, as well as the code from http://mcsp.wartburg.edu/zelle/python/ppics1/code/chapter12/button.py into a separate file called button.py, and try again

http://stackoverflow.com/comment/85122335
type: Comment
type: QuestionComment
has text: One thing I see: with the data structured as it is in `rec` the dataframe will have only the data for John.
comment on: http://stackoverflow.com/q/49058366
score: 0

http://stackoverflow.com/q/49096001
score: 0
accepted answer: http://stackoverflow.com/a/49096255
tagged with: urllib
has comment: http://stackoverflow.com/comment/85197304
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49096255
tagged with: beautifulsoup
has title: Wrong parsing with BeautifulSoup
type: Question
tagged with: python
has body: I want to access to the title of this website: https://zenodo.org/search?page=1&amp;size=20&amp;q=broma Actualy, I use BeautifulSoup, but when I access with this code results are empty ([]): from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup def generateSoup(my_url): uClient = uReq(my_url) page_html = uClient.read() uClient.close() return soup(page_html,"lxml") page_soup = generateSoup('https://zenodo.org/search?page=1&amp;size=20&amp;q=broma') containers = page_soup.findAll('a',{'class':'ng-binding'}) print(containers) If you could correct my code or give me another library that I can work with, I would be very grateful for your help. Thanks for all. Edit: The problem is that the HTML WebSite not have this element: Element
answer count: 1

http://stackoverflow.com/comment/85229597
comment on: http://stackoverflow.com/q/49112152
type: Comment
has text: i dont know how to do brother can you help me
score: 0
type: QuestionComment

http://stackoverflow.com/a/49100960
type: AcceptedAnswer
has body: import requests, json, pprint r = requests.get('https://deathsnacks.com/wf/data/voidtraders.json').text data = json.loads(r) pprint.pprint(data) [{'Activation': {'sec': 1520604000, 'usec': 0}, 'Character': "Baro'Ki Teel", 'Config': None, 'Expiry': {'sec': 1520773200, 'usec': 0}, 'Manifest': None, 'ManifestIndex': 0, 'NextRotation': None, 'Node': 'Kronia Relay (Saturn)', 'NodeIndex': 0, '_id': {'id': '5967933ca351963d1cd7faa5'}}] You can also iterate over the dictionary items: for key,value in data.items(): print('{}: {}'.format(key, value))
type: Answer
has comment: http://stackoverflow.com/comment/85249325
score: 0
accepted answer of: http://stackoverflow.com/q/49100662
has comment: http://stackoverflow.com/comment/85233625
answers question: http://stackoverflow.com/q/49100662
has comment: http://stackoverflow.com/comment/85380720

http://stackoverflow.com/comment/84991009
score: 0
type: Comment
type: QuestionComment
has text: There should just be an area in the GUI frame which is static upon tab switching, where widgets can be added.
comment on: http://stackoverflow.com/q/48992583

http://stackoverflow.com/comment/134117729
comment on: http://stackoverflow.com/a/49028792
has text: This can even be improved to a one-line recursive function: `def all_children(widget): return [widget] + [subchild for child in widget.winfo_children() for subchild in all_children(child)]` to get all the children of 'widget', and the widget itself.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49058664
has body: You need to instantiate the class MATRIX like so, before you can use its instance methods: m = MATRIX() z = m.add(X, Y) But if there is no instance data, then there is not much point in having instance methods. In this case you can make the methods static, and not have to instantiate the class to make use of its methods: class MATRIX: # Note that `self` parameter is removed, as it's no longer an # instance method. @staticmethod def add(M1,M2): return M1 + M2 z = MATRIX.add(X, Y)
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/49058586
answers question: http://stackoverflow.com/q/49058586
has comment: http://stackoverflow.com/comment/85122354
upvote count: 4

http://stackoverflow.com/q/49113243
has comment: http://stackoverflow.com/comment/85232199
has comment: http://stackoverflow.com/comment/85231546
type: Question
has comment: http://stackoverflow.com/comment/85231558
score: 0
has comment: http://stackoverflow.com/comment/85232310
has comment: http://stackoverflow.com/comment/85231780
answer count: 1
has answer: http://stackoverflow.com/a/49113382
has title: Some items are not removed
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85237453
has comment: http://stackoverflow.com/comment/85231812
tagged with: python
has body: I'm have a problem with remove(). I have to read a string and it convert to a list, then this list I must remove item "", but the last items are not removed. I show you the code: def telegrama(texto): c_aux = texto.split(" ") print(c_aux) for i in c_aux: if i == "": c_aux.remove(i) print(c_aux) texto = " Llego mañana alrededor del mediodía " telegrama(texto) I show the result
has comment: http://stackoverflow.com/comment/85232614
type: AnsweredQuestion
tagged with: items
accepted answer: http://stackoverflow.com/a/49113382

http://stackoverflow.com/q/48991236
has comment: http://stackoverflow.com/comment/84987246
type: Question
has comment: http://stackoverflow.com/comment/84987241
score: 0
answer count: 3
type: UnansweredQuestion
tagged with: python
has title: Return value, use in other function
has answer: http://stackoverflow.com/a/48991324
has body: I feel like I am misunderstanding something really fundamental. I wrote a program to do some math: import math def func1(a, b, c): print (f"We will now square {a}, {b}, {c} and add them") y = (a**2) + (b**2) + (c**2) print (f"y = ", y) x = y/3 print ("x = ", x) z = math.sqrt(x) print ("z = ", z) return z func1(1, 5, 1) This works, I get the desired output, which is Z. But in my mind, I should be able to write a function, return a value, then use that value in another function. I'd like to break up the steps in the above script to see them more clearly. I was unable to do this, but succeeded in putting all the math in one step, seen above. Ideally I'd write something and it would look like this... Func1(a, b, c) Square numbers a,b,c. Add them then return value Func2 Take value I returned from Func1, divide by 3. Return value. Func3 Get square root of value from Func2 Thanks for any help.
has answer: http://stackoverflow.com/a/48991408
has answer: http://stackoverflow.com/a/48991397

http://stackoverflow.com/comment/85073207
comment on: http://stackoverflow.com/q/49034230
score: 0
type: Comment
type: QuestionComment
has text: Do you still want the blank strings to be included?

http://stackoverflow.com/comment/85094433
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49044440
has text: The solution is correct but this code is in a different package and I am not allowed to edit that package (Even if I edit now, future updates of that package will break the workflow anyway). Is there any other way I can safely import without any exceptions?
type: AnswerComment

http://stackoverflow.com/comment/85255495
has text: Thanks @TomDalton, I checked and it looks interesting - ruby receives the sequence of `str` type from the database. Is there a way to convert it to unicode?
comment on: http://stackoverflow.com/q/49114119
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48992373
accepted answer: http://stackoverflow.com/a/48992494
has comment: http://stackoverflow.com/comment/84991409
answer count: 1
has comment: http://stackoverflow.com/comment/84990774
tagged with: python
has comment: http://stackoverflow.com/comment/84990480
favorite count: 0
linked to: http://stackoverflow.com/q/1014503
has comment: http://stackoverflow.com/comment/84990620
downvote count: 7
has comment: http://stackoverflow.com/comment/84991060
has comment: http://stackoverflow.com/comment/84989760
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84990960
has title: python，typeerror：cannot concatenate 'str 'and 'float' objects
has comment: http://stackoverflow.com/comment/84990671
has body: import easygui fahrenheit = easygui.integerbox("Please input fahrenheit: ") celsius = (fahrenheit -32) *5.0 / 9 easygui.msgbox("celsius is :" + celsius )
has answer: http://stackoverflow.com/a/48992494
has comment: http://stackoverflow.com/comment/84992136
has comment: http://stackoverflow.com/comment/84990217
type: Question
has comment: http://stackoverflow.com/comment/84989887
has comment: http://stackoverflow.com/comment/84989770
upvote count: 0
score: -7
has comment: http://stackoverflow.com/comment/84990139
has comment: http://stackoverflow.com/comment/84990726
has comment: http://stackoverflow.com/comment/84989916
has comment: http://stackoverflow.com/comment/84990489
has comment: http://stackoverflow.com/comment/84990304
has comment: http://stackoverflow.com/comment/84990571

http://stackoverflow.com/comment/139579445
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49006295
has text: This question is similar to: [Run Python Script from MSSQL](https://stackoverflow.com/questions/44464928/run-python-script-from-mssql). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.

http://stackoverflow.com/q/49016589
upvote count: 0
has answer: http://stackoverflow.com/a/49016789
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85038302
tagged with: scikit-image
downvote count: 6
has comment: http://stackoverflow.com/comment/85038212
has body: So, I have grayscale image as 3 RGB channels. I take the difference between two channels and see, that a take different results, when I take difference between images[0] and images[1] and when I take difference between images[1] and images[0]. What am I doing wrong?
has comment: http://stackoverflow.com/comment/85038264
answer count: 1
tagged with: scikit-learn
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/85038340
has comment: http://stackoverflow.com/comment/85038140
type: UnansweredQuestion
has title: difference between arrays in numpy
tagged with: python

http://stackoverflow.com/q/49105282
has title: python networkx import error: cannot import name release
tagged with: python-2.7
linked to: http://stackoverflow.com/q/66174862
has answer: http://stackoverflow.com/a/49685320
tagged with: release
has comment: http://stackoverflow.com/comment/85245747
has body: I'm on macOS, using another program needs to run python script contains networkx module. My networkx2.1 is installed using: pip install networkx --user The error raised is that: File "/Users/myname/Library/Python/2.7/lib/python/site-packages/networkx/__init__.py", line 43, in &lt;module&gt; import networkx as nx ImportError from networkx import release cannot import name release I've done some search on this error, and those seem working is by using the networkx of another version, or install/uninstall. I've already tried uninstall and reinstall networkx of version 1.9, 1.5, 1.1, however this error continues. Anyone also encounterd this issue?
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/76317296
has comment: http://stackoverflow.com/comment/85216228
type: Question
has comment: http://stackoverflow.com/comment/85215679
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/66653870
has comment: http://stackoverflow.com/comment/85216194
has comment: http://stackoverflow.com/comment/85215607
has answer: http://stackoverflow.com/a/68444095
tagged with: networkx
has comment: http://stackoverflow.com/comment/85216278
answer count: 4
has comment: http://stackoverflow.com/comment/120961666
downvote count: 0
has comment: http://stackoverflow.com/comment/120961403
type: UnansweredQuestion

http://stackoverflow.com/comment/85163399
type: AnswerComment
comment on: http://stackoverflow.com/a/49077918
score: 0
type: Comment
has text: I did that and got a new error. Traceback: ValueError: invalid literal for int() with base 10: 'Greatsword'

http://stackoverflow.com/q/49015162
linked to: http://stackoverflow.com/q/17582975
linked to: http://stackoverflow.com/q/29523246
linked to: http://stackoverflow.com/q/33784665
has title: pythonw subprocess can't call another version of python
linked to: http://stackoverflow.com/q/26049778
downvote count: 0
linked to: http://stackoverflow.com/q/2231227
favorite count: 0
type: UnansweredQuestion
tagged with: pythonw
tagged with: python
score: 2
has body: Before I start, some notes on my environment: python 2.7.14 installed through miniconda, macOS 10.13.3. The Problem I'm trying to write a data processing pipeline (call it analyze.py) in python which calls several different programs. One of those programs, EMAN2 uses its own python environment to run (located, say, ~/EMAN2/bin/python). From the command line, a call to eman2 might look something like this: ~/EMAN2/bin/e2buildstacks.py <args> where e2buildstacks.py specifies its own python environment using the standard #!/Users/<username>/EMAN2/bin/python type formulation at the top of the file (note, there's a lot of these different .py files to run, I'm just using one name as an example). In python, I'm using a subprocess.Popen construction for these calls. A very simple example would be: import subprocess stacks_cmd = '/Users/<username>/EMAN2/bin/e2buildstacks.py <args>' process = subprocess.Popen(stacks_cmd, shell=True, stdout=subprocess.PIPE) stacks_output, stacks_error = process.communicate() Where I've replaced the actual args and username, for simplicity. If this is all I'm doing, it works fine. I can run python analyze.py from the command line and it runs EMAN2 without problem. However, this pipeline is getting wrapped up in a GUI (wxpython based). So I have to use pythonw to run my program. When I try to do: pythonw analyze.py It can't run the EMAN2 scripts correctly, I get an error: Traceback (most recent call last): File "/Users/<username>/EMAN2/bin/e2buildstacks.py", line 34, in <module> from EMAN2 import * ImportError: No module named EMAN2 This indicates to me that it's using my miniconda python rather than the ~/EMAN2/bin/python to run the script. (Note: if anyone uses EMAN2, I can provide you with the full argument list and the input files. But rest assured that's not the issue, I can run the command I'm using just fine from the command line) What I've tried I've tried several different things to fix this problem. The simplest was specifying the pyth…
answer count: 0
tagged with: subprocess
upvote count: 2
tagged with: miniconda
type: Question

http://stackoverflow.com/comment/85162307
comment on: http://stackoverflow.com/a/49078083
score: 0
type: AnswerComment
type: Comment
has text: cpython's 'list` is basically an array, so calling `append` will trigger (re-)allocations. Haven't looked into what `list(iterable)` does under the hood, yet.

http://stackoverflow.com/a/49083844
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/49083766
answers question: http://stackoverflow.com/q/49083766
upvote count: 3
has body: Since you want to use pandas anyways this should be quite convenient: import pandas as pd df=pd.DataFrame(carving_skis) new=df[df["Brand"]=="Atomic"]
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49003637
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85012029
has answer: http://stackoverflow.com/a/61023741
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85012286
type: Question
has body: I have a BSON document of 62,292,248 bytes size that I want to analyze. I am using the following: import bson f = open('mybson.bson','rb') s = f.read() b = bson.loads(s) f.close() On the console, when I enter b and hit enter, I can see only one document even though s has read all of the bytes. I tried with f.read(62292248) too; but, b seems to have only one document! What am I missing?
tagged with: bson
has comment: http://stackoverflow.com/comment/85021863
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85019669
type: UnansweredQuestion
has title: Python - BSON document parsed for one document only

http://stackoverflow.com/a/49067371
type: Answer
has comment: http://stackoverflow.com/comment/85139836
score: 0
has comment: http://stackoverflow.com/comment/85139874
has body: There's another issue I think: anyNumber = int(raw_input("Enter any number: ")) while anyNumber &gt; num: anyNumber = int(raw_input("Enter another number: ")) The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
answers question: http://stackoverflow.com/q/49067258

http://stackoverflow.com/q/49019784
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has title: timed out message using python install command
tagged with: spacy
tagged with: pip
upvote count: 1
answer count: 1
tagged with: tensorflow
has body: i am trying to install spacy 'en_core_web_md' model but i get timed out message every time i try to download it using this python command : 'python -m spacy download en_core_web_md' error message: File "C:\ProgramData\Anaconda2\envs\tensorflow\lib\site-packages\pip\_vendor\r equests\packages\urllib3\response.py", line 237, in _error_catcher raise ReadTimeoutError(self._pool, None, 'Read timed out.') pip._vendor.requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnecti onPool(host='github-production-release-asset-2e65be.s3.amazonaws.com', port=443) : Read timed out.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49027627
downvote count: 0

http://stackoverflow.com/comment/136745916
comment on: http://stackoverflow.com/a/51177895
type: AnswerComment
score: 0
has text: thanks for the explanation, the gradual build up is super helpful to understand.
type: Comment

http://stackoverflow.com/comment/85087265
comment on: http://stackoverflow.com/a/49040672
type: AnswerComment
score: 0
type: Comment
has text: I decided to add an option to my answer that was inspired this. Great answer!

http://stackoverflow.com/q/49023893
tagged with: apache-spark-sql
tagged with: pyspark
upvote count: 4
has answer: http://stackoverflow.com/a/49031573
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85058534
favorite count: 0
has comment: http://stackoverflow.com/comment/85053702
has title: replace for loop to parallel process in pyspark
type: Question
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85055109
tagged with: python
accepted answer: http://stackoverflow.com/a/49031573
score: 4
has comment: http://stackoverflow.com/comment/85063628
has comment: http://stackoverflow.com/comment/85055433
answer count: 1
has body: I am using for loop in my script to call a function for each element of size_DF(data frame) but it is taking lot of time. I tried by removing the for loop by map but i am not getting any output. size_DF is list of around 300 element which i am fetching from a table. Using For: import call_functions newObject = call_functions.call_functions_class() size_RDD = sc.parallelize(size_DF) if len(size_DF) == 0: print "No record present in the truncated list" else: for row in size_DF: length = row[0] print "length: ", length insertDF = newObject.full_item(sc, dataBase, length, end_date) Using Map if len(size_DF) == 0: print "No record present in the list" else: size_RDD.mapPartition(lambda l: newObject.full_item(sc, dataBase, len(l[0]), end_date)) newObject.full_item(sc, dataBase, len(l[0]), end_date) In full_item() -- I am doing some select ope and joining 2 tables and inserting the data into a table. Please help me and let me know what i am doing wrong.

http://stackoverflow.com/comment/85079928
type: AnswerComment
has text: It wasn't my doing (I upvoted but it didn't count as I don't have enough reputation points), I think it was the person giving the second answer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49036892

http://stackoverflow.com/comment/85166242
type: Comment
has text: Thanks for the help. When I run this it looks like columns with matching names are repeating. For example, if there's another Value1 column in a later DataFrame then the value won't slot into it's relevant A index in the first Value1 column, rather it will make a new column called Value1.
comment on: http://stackoverflow.com/a/49074923
score: 0
type: AnswerComment

http://stackoverflow.com/a/49069691
type: Answer
has comment: http://stackoverflow.com/comment/85169777
answers question: http://stackoverflow.com/q/49023717
has body: These calls may block the thread they're being executed in. sendto will block if the outbound buffer of your OS kernel is full and it needs time to become able to accommodate the message you are willing to send. sendto won't block because the remote application haven't called recvfrom yet. recvfrom will block until there's something to read from the inbound buffer of your OS kernel. recvfrom will block if the remote peer hasn't sent anything or the message has not arrived yet. Also, there's probably some misconfiguration happening on your side. ConnectionResetError may happen because there's a firewall somewhere. Latency is not related to the issue since UDP has no connections and timeouts.
has comment: http://stackoverflow.com/comment/85173515
score: 0
has comment: http://stackoverflow.com/comment/85158170

http://stackoverflow.com/comment/85140937
type: QuestionComment
comment on: http://stackoverflow.com/q/49067980
type: Comment
score: 5
has text: It is not clear what the function should do. Can you explain?

http://stackoverflow.com/q/49116172
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/49117194
tagged with: group-by
tagged with: dataframe
has title: Pulling a specific value from a Pandas GroupBy Object
tagged with: typeerror
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49117194
has body: Running Python 3.6.4, pandas 0.22 and numpy 1.14.1 I am looking to pull a specific value from a Pandas GroupBy object. I am taking my initial dataset, opening into a dataframe filtering out unnecessary columns. Then I am doing a groupby, where Columns D, E, F, G and H are each summed based on columns A, B and C. This gives me the data-set that I need to pull values from. First here's an example of the type of group by I am using. (Maybe this can be corrected) output = df.groupby(['A', 'B', 'C'], as_index=False).agg({'D': [np.sum], 'E': [np.sum],'F': [np.sum],'G': [np.sum],'H': [np.sum]}) If it helps, Columns A, B and C are all strings, where D through H are all converted to numbers using the to_numeric method. Next, I am looking to pull a specific value out of this new data-set using the maximum value of Column A. I can pull a series using loc, but I want to pull the value of a certain position and then insert that into another dataframe. Maybe loc does this, I just want to be certain that whatever I pull from this group by object, gets put into the new dataframe. So is the value is 4, I get a variable = 4, and then can put that into another dataframe. value = output.at[output.A.idxmax(), 'D'] The error I am getting is TypeError: only integer scalar arrays can be converted to a scalar index My best guess is that this is based on the fact that groupby returns a groupby object? Or should this work with a groupby object as well? What are my options here? Maybe my groupby is wrong? Maybe I don't need a groupby? Maybe I can convert my groupby object to a dataframe and then run the df.at? Any help is appreciated. Also - if I've done something wrong, please help me understand the 'why?' along with the fixed scripting. I am very interested in learning as much as I can vs. having everyone do my work for me. I love python and the capabilities, but am very much a novice at this point. Cheers
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/85035638
type: QuestionComment
has text: @Montmons why do you think you aren't taking the best approach? Again, you haven't really articulated *what the problem is*.
comment on: http://stackoverflow.com/q/49014601
score: 0
type: Comment

http://stackoverflow.com/q/48986755
accepted answer: http://stackoverflow.com/a/48987997
type: AnsweredQuestion
tagged with: list
type: Question
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48987997
has title: how to get index range for zero and non-zero value from list in python?
tagged with: python
possible better answer: http://stackoverflow.com/a/48987071
favorite count: 0
has answer: http://stackoverflow.com/a/48986919
has answer: http://stackoverflow.com/a/48987926
has answer: http://stackoverflow.com/a/48987071
upvote count: 2
answer count: 5
has body: I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g. a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12, 12, 12, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17, 25, 42, 54, 61, 61, 68, 73, 103, 115, 138, 147, 170, 187, 192, 197, 201, 208, 210, 214, 216, 217, 217, 218, 219, 220, 221, 222, 222, 219, 220, 220, 221, 220, 216, 216, 217, 217, 217, 217, 216, 216, 216, 209, 204, 193, 185, 177, 161, 156, 143, 110, 103, 89, 82, 62, 62, 62, 60, 56, 55, 50, 49, 48, 47, 47, 45, 44, 43, 42, 40, 37, 23, 22, 14, 12, 6, 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, 5, 6, 6, 6, 7, 7, 7, 13, 29, 31, 32, 33, 41, 42, 43, 43, 44, 44, 44, 44, 44, 60, 70, 71, 72, 88, 95, 104, 105, 111, 124, 125, 131, 145, 157, 169, 174, 186, 190, 190, 191, 192, 192, 193, 193, 193, 194, 198, 201, 202, 203, 202, 203, 203, 203, 203, 203, 203, 197, 195, 186, 177, 171, 154, 153, 148, 141, 140, 135, 132, 120, 108, 94, 86, 78, 73, 60, 53, 46, 46, 45, 44, 43, 37, 35, 29, 26, 19, 11, 0]] Output: idx = [(0,9),(10,101),(102,128),...]
has answer: http://stackoverflow.com/a/48988020

http://stackoverflow.com/a/51798109
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49073429
has body: MySQLdb turns MySQL warnings into python warnings and for some reason the default in EPFIngester.py is to treat warnings as errors. You can get around this by commenting out line 56 in EPFImporter.py. warnings.filterwarnings('error') # warnings.filterwarnings('error')

http://stackoverflow.com/a/49025451
type: Answer
answers question: http://stackoverflow.com/q/49025275
score: 0
has body: Codes as the following: def main(): dic = {"a": "Blue Jacket with buttons", "b": "Green Jacket with a buttons", "c": "Blue jacket"} keywords = "Blue, Jacket, Buttons" keyword_items = [keyword.strip().lower() for keyword in keywords.split(",")] for key, value in dic.items(): if all(keyword in value.lower() for keyword in keyword_items): print(key)

http://stackoverflow.com/a/49037649
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85114374
accepted answer of: http://stackoverflow.com/q/49036421
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49036421
has body: In your code ax2 does not know that it should behave exactly as ax1, just with different labels. So you need to tell it, ax2.set_xlim(ax1.get_xlim()) Then just use the same tick locations for both axes, ax1.set_xticks(X1) ax2.set_xticks(X1) and label the ticks of ax2 with values from X2 ax2.set_xticklabels(["%.2f" % i for i in X2]) Complete code: import numpy as np import matplotlib.pyplot as plt X1 = np.array([10., 30.1, 50.2, 70.3, 90.4, 110.510, 130.610, 150.710, 170.810, 190.910, 211.010, 231.110, 251.210, 271.310, 291.410, 311.52, 331.62]) Y = np.array([-0.00000087, -0.0000149, -0.0000326, -0.0000513, -0.00006523, -0.0000842, -0.0001003, -0.0001214, -0.00013769, -0.0001572, -0.0001971, -0.0002203, -0.00027470, -0.0003217, -0.0003764, -0.0004657, -0.00062320]) X2 = np.array([1.997, 2.0109, 2.0372, 2.0665, 2.099, 2.1392, 2.1789, 2.2290, 2.287, 2.3180, 2.4100, 2.4826, 2.579, 2.6764, 2.7963, 2.9740, 3.310]) ##### Plotting: fig, ax1 = plt.subplots() ax1.grid() ax2 = ax1.twiny() ax1.plot(X1, Y, linestyle='--', marker="o", markersize=6, color='blue') ax1.set_ylabel('Y', fontsize=20) ax1.set_xlabel('X1', fontsize=20, color='blue') plt.setp(ax1.get_xticklabels(), rotation='45') # rotate them ax2.set_xlabel('X2', fontsize=20, color='red') plt.setp(ax2.get_xticklabels(), rotation='45', color='red') # Set xlimits of ax2 the same as ax1 ax2.set_xlim(ax1.get_xlim()) # Set ticks at desired position ax1.set_xticks(X1) ax2.set_xticks(X1) # Label ticks of ax2 with values from X2 ax2.set_xticklabels(["%.2f" % i for i in X2]) fig.tight_layout() plt.show()

termcolor
tags question: http://stackoverflow.com/q/49011150
tag name: termcolor
type: Tag

http://stackoverflow.com/comment/85045634
type: AnswerComment
comment on: http://stackoverflow.com/a/49020231
score: 0
type: Comment
has text: I think Brian wants the output to be integers

http://stackoverflow.com/a/48982128
answers question: http://stackoverflow.com/q/48981815
type: AcceptedAnswer
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/48981815
downvote count: 1
has body: You can use plt.xticks(range(len(values)), keys,rotation=90) to rotate. more info in docs
upvote count: 4

http://stackoverflow.com/comment/85243990
type: Comment
comment on: http://stackoverflow.com/a/49119211
has text: You are invincible sir. Much appreciated. I would request you to obfuscate the link like i tried above. Thankssssss a lot.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85183620
has text: Yes sir, which shows `powered by google` or something but it doesn't stay when i try to inspect.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49088642

http://stackoverflow.com/comment/84967449
type: QuestionComment
comment on: http://stackoverflow.com/q/48980725
has text: This is the code I have so far : df['result'] = df['var'].str.extract('/^(.*?)\\r /', expand=True) I get all NaN as a result
score: 0
type: Comment

http://stackoverflow.com/a/49102680
has body: If r is a compiled regular expression and line is a line of text, the way to apply the regex is r.match(line) to find a match at the beginning of line, or r.search(line) to find a match anywhere. In your particular case, you simply need line = r.sub(replacement, line) though in addition, you'll need to add a backslash before the round parentheses in your regex in order to match them literally (except in a few places where you apparently put in grouping parentheses around the \d+ for no particular reason; maybe just take those out). Your example input string contains three digits, and the replacement string contains six digits, so \d+\.\d+ will never match either of those. I'm guessing you want something like \d+(?:\.\d+)+ or perhaps very bluntly [\d.]+ if the periods can be adjacent. Furthermore, a single backslash in a string will be interpreted by Python, before it gets passed to the regex engine. You'll want to use raw strings around regexes, nearly always. For improved legibility, perhaps also prefer single quotes or triple double quotes over regular double quotes, so you don't have to backslash the double quotes within the regex. Finally, your usage of fileinput is wrong. You can't use it as a context manager. Just loop over the lines which fileinput.input() returns. import fileinput, re filename = 'epivers.h' text_to_search = re.compile(r'#define EPI_VERSION_STR "\d+(?:\.\d+)+ \(TOB\) \(r\d+ ASSRT\)"') replacement_text = '#define EPI_VERSION_STR "9.130.27.50.1.2.3 (r749679 ASSRT)"' for line in fileinput.input(filename, inplace=True, backup='.bak'): print(text_to_search.sub(replacement_text, line)) In your first attempt, line.replace() was a good start, but it doesn't accept a regex argument (and of course, you don't close() a file you opened with with ...). In your second attempt, you are checking whether the line is identical to the regex, which of course it isn't (just like the string "two" isn't equivalent to the numeric constant 2).
has comment: http://stackoverflow.com/comment/85210593
has comment: http://stackoverflow.com/comment/85212173
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85210702
accepted answer of: http://stackoverflow.com/q/49102116
has comment: http://stackoverflow.com/comment/85212002
has comment: http://stackoverflow.com/comment/85210929
has comment: http://stackoverflow.com/comment/85211373
type: Answer
has comment: http://stackoverflow.com/comment/85211319
has comment: http://stackoverflow.com/comment/85211061
has comment: http://stackoverflow.com/comment/85211290
has comment: http://stackoverflow.com/comment/85212543
has comment: http://stackoverflow.com/comment/85212276
score: 2
has comment: http://stackoverflow.com/comment/85211100
upvote count: 2
has comment: http://stackoverflow.com/comment/85210882
has comment: http://stackoverflow.com/comment/85210839
has comment: http://stackoverflow.com/comment/85212164
answers question: http://stackoverflow.com/q/49102116
has comment: http://stackoverflow.com/comment/85211402
has comment: http://stackoverflow.com/comment/85211554
has comment: http://stackoverflow.com/comment/85211793
has comment: http://stackoverflow.com/comment/85210604
has comment: http://stackoverflow.com/comment/85211030

http://stackoverflow.com/comment/85210869
has text: Every line you loop through you reinitialize your "array" as `array=[]` so it will only contain the last line
comment on: http://stackoverflow.com/q/49102858
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85189919
type: Comment
has text: @tomh1012 Just import what is needed in a module within that module. You want modules to be as standalone as possible. Definitely do not create one module that imports all the others, that's exactly the wrong way to go about it.
comment on: http://stackoverflow.com/a/49067400
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85186383
comment on: http://stackoverflow.com/q/49090339
type: Comment
type: QuestionComment
score: 0
has text: It seems like you are passing the xpath to `find_element_by_css_selector` (instead of the css selector above)?

http://stackoverflow.com/q/49015192
has comment: http://stackoverflow.com/comment/85035934
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49016204
upvote count: 1
has body: I am running some simulations using RandomForestClassifier to classify between 2 categories, and I am using the function below to debug: def predict_proba(self, X): print(X.shape) pred = self.clf.predict_proba(X) print(pred.shape) pred = pred.T[1] print(pred.shape) return pred This routine runs several times as I have split my data, and I get the follow outputs for the printing .shape routine I've coded above. (62, 93) (62, 2) (62,) (62, 93) (62, 2) (62,) (62, 93) (62, 2) (62,) (62, 93) (62, 1) IndexError: index 1 is out of bounds for axis 0 with size 1 My question is why does prediction_proba(X) most of the times output a shape of (62, 2) (as expected) and other time outputs a shape of (62, 1)? EDIT I think I understood it, it seems like that classifier was trained with only one category, as I wasn't using Stratified KFold or something like it.
answer count: 1
downvote count: 1
has title: RandomForestClassifier prediction_proba(X) outputs results only for one category
tagged with: random-forest
accepted answer: http://stackoverflow.com/a/49016204
type: AnsweredQuestion
tagged with: scikit-learn
favorite count: 0
type: Question

installation
tags question: http://stackoverflow.com/q/48972666
tags question: http://stackoverflow.com/q/49035257
tags question: http://stackoverflow.com/q/49118277
tag name: installation
tags question: http://stackoverflow.com/q/49018135
type: Tag
tags question: http://stackoverflow.com/q/49115628
tags question: http://stackoverflow.com/q/49120965
tags question: http://stackoverflow.com/q/49119453
tags question: http://stackoverflow.com/q/48970914
tags question: http://stackoverflow.com/q/49097952
tags question: http://stackoverflow.com/q/49007742
tags question: http://stackoverflow.com/q/49121012
tags question: http://stackoverflow.com/q/48981214
tags question: http://stackoverflow.com/q/49101890
tags question: http://stackoverflow.com/q/49001065

http://stackoverflow.com/q/49058334
tagged with: mysql
upvote count: 1
linked to: http://stackoverflow.com/q/372885
type: Question
has comment: http://stackoverflow.com/comment/85121932
tagged with: cron-task
has comment: http://stackoverflow.com/comment/85126392
tagged with: mysql-python
downvote count: 0
score: 1
tagged with: redhat
favorite count: 0
has comment: http://stackoverflow.com/comment/85124570
has comment: http://stackoverflow.com/comment/85123316
has title: How do you connect to a database, get results to delete files in file system in Python?
tagged with: python
has body: I am learning Python on my own and running on RedHat linux 6.6 so please bear with me. I wish to try and use Python to delete certain files in our file system whose filenames and type are stored as hash values and the path to these files in a database (MySQL 5.5). For example, I have 5 files and I wish to delete the automated ones and their hash filenames &amp; types are: 52c62e759abfb47ec0fae3e9f1525b3b8e347054 | manual aa91f74f2028d254a700300a8a012f64f9535b3b | automated ffa9c58f7231caab6836ed4baaf61c95e9763af2 | automated 71c3251aba5848e4188c0f542ea0b91be224d750 | manual a214f7be544d0e73307e7abff9327226cca30e35 | automated and so forth ... The files are located in the root prefixed "/srv/ourfiles/data" We take the first 2 characters in the string and that is the top folder and the subfolder, are the next 2 characters and that is where the files are stored. The 1st file is located at: "/srv/ourfiles/data/52/c6" The 2nd file is located at: "/srv/ourfiles/data/aa/91" The 3rd file is located at: "/srv/ourfiles/data/ff/a9" The 4th file is located at: "/srv/ourfiles/data/71/c3" The 5th file is located at: "/srv/ourfiles/data/a2/14" and so forth ... How do I connect query against the database (I know what the query is so its just how to connect)? Get the result set and iterate through each of the 3 automated files I wish to delete and compare the filename stored in the database with the actual filename in the path that they match?, and finally delete the file itself? I want to run this as cron job if possible. Thank you!
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85215309
type: Comment
has text: Maybe you can state your definition of group. Then we can help you finding them.
comment on: http://stackoverflow.com/a/49081304
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85148130
type: Comment
type: QuestionComment
has text: I want to have exactly a result that can be mapped to the entity representing that table. for that reason I need to discard the max value. so I want the maximum column_1 per each unique column_2 (which is an ID, foreign key). I was able to get the SQL query but I wanted an `SQLAlchemy` idiom with proper mapped result for the ORM.
comment on: http://stackoverflow.com/q/49066529
score: 0

http://stackoverflow.com/q/49036709
has comment: http://stackoverflow.com/comment/85086770
downvote count: 0
has comment: http://stackoverflow.com/comment/113533234
has comment: http://stackoverflow.com/comment/85079053
linked to: http://stackoverflow.com/q/3227180
has comment: http://stackoverflow.com/comment/85081325
score: 3
has body: I'm trying to use catch the Django user in the Middleware but without success. Using Python 3.6 and Django 1.11. from threading import local _user = local() class CurrentUserMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): _user.value = request.user return self.get_response(request) def get_current_user(): return _user.value I need to save the request.user outside the class, in the get_current_user(), but it is not working. Can someone give me a clue why I can't have the _user.value in the get_current_user() ? The reason I'm doing this is to import to a model from current_user import get_current_user Thanks,
has comment: http://stackoverflow.com/comment/85079229
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85079286
answer count: 0
type: UnansweredQuestion
tagged with: django-middleware
tagged with: django
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/85078400
has comment: http://stackoverflow.com/comment/85080833
has title: Django Middleware and threading to catch the current user
tagged with: middleware
type: Question

http://stackoverflow.com/q/49114180
type: Question
tagged with: python-import
answer count: 2
has answer: http://stackoverflow.com/a/49121026
score: 0
linked to: http://stackoverflow.com/q/49033015
has answer: http://stackoverflow.com/a/49114575
linked to: http://stackoverflow.com/q/14132789
has title: Python/PyCharm: Differences when running subpackage modules
linked to: http://stackoverflow.com/q/47499730
possible better answer: http://stackoverflow.com/a/49114575
accepted answer: http://stackoverflow.com/a/49121026
tagged with: python
tagged with: module
type: AnsweredQuestion
tagged with: pycharm
has body: I have a project subdivided into packages, in the following structure: /project /pkg __init__.py engine.y ai.py __init__.py test_script.py engine.py has an import statement to use ai.py which looks like import pkg.ai as ai This means that test_script.py can be run in the command line as python test_script.py and it has no issues. However for debugging purposes, engine.py is also often run. When running in PyCharm it has no problems but when using python engine.py I get errors saying No module named pkg. Is there any way I can run engine.py in the command line so that it does not have import errors the way PyCharm does it? Interestingly the way PyCharm works is that if I do not put that pkg. in front of the import module, it underlines it in red saying it can't find the module (but still runs). I've looked everywhere for a solution to this but have only got more confused.

http://stackoverflow.com/q/49004671
tagged with: salt-project
has answer: http://stackoverflow.com/a/49018716
type: Question
tagged with: testing
answer count: 1
downvote count: 0
has title: Set a variable based on a py.test (testinfra) check output
accepted answer: http://stackoverflow.com/a/49018716
favorite count: 0
upvote count: 2
has body: I am trying to make a testinfra test file more portable, I'd like to use a single file to handle tests for either a prod / dev or test env. For this I need to get a value from the remote tested machine, which I get by : def test_ACD_GRAIN(host): grain = host.salt("grains.item", "client_NAME") assert grain['client_NAME'] == "test" I'd need to use this grain['client_NAME'] value in different part of the test file, therefore I'd like to store it in a variable. Anyway to do this ?
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pytest

http://stackoverflow.com/a/63943456
score: 0
has body: I have found that some packages force pip to reinstall numpy. The safest (and only) way to ensure that numpy is installed with mkl (from conda) is to uninstall using conda and pip and then reinstall using conda: conda uninstall numpy pip uninstall nump conda install numpy
answers question: http://stackoverflow.com/q/49012215
type: Answer

http://stackoverflow.com/q/49043570
has comment: http://stackoverflow.com/comment/85098538
type: Question
tagged with: qt
has answer: http://stackoverflow.com/a/49207491
has body: Not sure if this is a bug or what, but its driving me crazy. Im using Python 3.5.4 32bit on Win 7. PyQt5's filefinder will not work if pywinauto is imported to the script. If someone could check if this script works for them (test the File>Import button): from PyQt5 import QtWidgets import sys #import pywinauto class Window(QtWidgets.QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50, 50, 800, 600) import_folder = QtWidgets.QAction("import", self) import_folder.triggered.connect(self.open_folder) main_menu = self.menuBar() fileMenu = main_menu.addMenu("&amp;File") fileMenu.addAction(import_folder) self.show() def open_folder(self): folder = QtWidgets.QFileDialog.getExistingDirectory(self, "Open folder") app = QtWidgets.QApplication(sys.argv) main = Window() sys.exit(app.exec_()) And after running that, try uncommenting the pywinauto import and running the script again- it does not work for me. Pywinauto is breaking my file explorer, but I need it in my program! There are no errors or anything, the app just freezes and does not respond. Idk what is going on. If anyone could test this out that would be great. If you have any guidance, cheers.
score: 1
has title: PyQt5 QFileDialog does not work with pywinauto import
tagged with: pyqt
upvote count: 1
answer count: 1
downvote count: 0
tagged with: pywinauto
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85119040
has comment: http://stackoverflow.com/comment/85131048
tagged with: pyqt5

pyobject
tags question: http://stackoverflow.com/q/48971874
type: Tag
tag name: pyobject

http://stackoverflow.com/q/49117963
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49119776
tagged with: seaborn
tagged with: python
score: 11
tagged with: plot
upvote count: 11
has title: Simple way for using multiple Numpy Arrays as an input for one Seaborn boxplot
type: AnsweredQuestion
has body: Most of the examples I found use Pandas DataFrame in order to have multiple boxes in a single box plot. I would like to know if there is a simpler, more straight forward way by directly using numpy arrays as the input. For example, let's take five numpy arrays with each one of them having 20 entries. I would like to plot those five arrays as individual blocks next to each. The block should illustrate the variance of the array entries. The end result should look something like the second picture on Seaborn's page.
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49119776
tagged with: block

http://stackoverflow.com/q/49020814
has comment: http://stackoverflow.com/comment/85046890
has answer: http://stackoverflow.com/a/49020876
type: Question
has title: while loop python cannot be fixed
answer count: 2
has answer: http://stackoverflow.com/a/49020862
favorite count: 0
tagged with: while-loop
downvote count: 3
type: UnansweredQuestion
score: -3
has body: def hits(): while True: hits = int(input("Number of hits :\t")) if hits&gt;1000: print("Invalid integer. Must be from 0 to 1000.") print() **elif hit(hits)&gt;at_bats:** #does not know how to fix that print("Hits cannot be greater than at bats.") print() else : return hits
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/85046901

http://stackoverflow.com/comment/85214920
type: QuestionComment
has text: I want to know the return value of this function and its semantics, but I cannot find any doc about this unpublic api.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49103096

http://stackoverflow.com/comment/85084680
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/help/mcve please add relevant model/table definitions & what you've tried
comment on: http://stackoverflow.com/q/49036259
score: 0

http://stackoverflow.com/comment/85177311
type: Comment
has text: Did you also try my exact example? Copy and paste?
comment on: http://stackoverflow.com/a/49085929
type: AnswerComment
score: 0

http://stackoverflow.com/q/48973612
type: AnsweredQuestion
has body: new to python (4 months) got thru the first steps of basic programming skills, I believe, (having passed edX MIT 6001x and 60002x) having big problems in the world of new libraries... here an example: r= requests.get ('URL',timeout=x) works well with certain URL, keeps waiting with some other URL and I am getting HTTPSConnectionPool(host='URL', port=443): Read timed out. (read timeout=x) and without the timeout parameter, the jupyter notebook keeps turning the sand-watch. I am not trying to handle the exception but to get it work. Is there a simple way out or is requests.get too short for these kind of tasks? And a more general question here,if you have the time: learning from the official docs (especially for larger and more complex modules) is getting too abstract for me, where it makes me feel hopeless. 'Straight diving' produces problems such as this one where you even cant figure out the simplest.. What would be an efficient way to deal with state of the art libraries? How did/do you go forward?
has title: request.get not working // and a more general one
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/48974417
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48974417
tagged with: python

http://stackoverflow.com/q/49037852
has comment: http://stackoverflow.com/comment/85081289
has answer: http://stackoverflow.com/a/49038038
downvote count: 1
has comment: http://stackoverflow.com/comment/85081121
type: Question
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/49038060
has body: I have defined a function that takes in a list like this arr = ['C','D','E','I','M'] I have another function that produces a similar kind of list, the function is: def tree_count(arr): feat = ['2','2','2','2','0'] feat_2 = [] dictionary = dict(zip(arr, feat)) print('dic',dictionary) feat_2.append([k for k,v in dictionary.items() if v=='2']) newarr = str(feat_2)[1:-1] print(newarr) This outputs the correct result that I want, i.e: ['C','D','E','I'] But the problem is, when I use this list in another function, its values should be read as C,D,E,I . But instead when I print this, the bracket [ and ' are included as result: for i in newarr: print(i) The printed result is : [ ' C ', and so on for each line. I want to get rid of [ '. How do I solve this?
has title: Read python list correctly
score: -1
has answer: http://stackoverflow.com/a/49038060
has comment: http://stackoverflow.com/comment/85080869
accepted answer: http://stackoverflow.com/a/49038038
has comment: http://stackoverflow.com/comment/85081261
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85081003
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

export-to-excel
tags question: http://stackoverflow.com/q/48973101
tag name: export-to-excel
type: Tag

http://stackoverflow.com/comment/85075967
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49034817
has text: Thank you for pointing this out. df.iloc[:10] also took a very long time, which lead me to realize my dataframe was many orders of magnitude larger than I had thought. It was quick to load, which I had originally though implied it was a reasonable size, However, thanks to Yserbius comment, I realize lazy evaluation caused it to be created and loaded quickly.

http://stackoverflow.com/comment/84991306
has text: thank you very much ,, i work but you forget in your code to `return`model in `get_queryset`
type: Comment
comment on: http://stackoverflow.com/a/48981864
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85001314
comment on: http://stackoverflow.com/q/48997871
score: 0
type: Comment
type: QuestionComment
has text: Okay, I understand those concepts, they're not foreign to me. My question is, why doesn't the function work when I'm not applying the `list` wrapper? Because I have to trigger it through the iterator?

http://stackoverflow.com/comment/85464945
comment on: http://stackoverflow.com/a/48999325
type: AnswerComment
type: Comment
score: 0
has text: I'd expect it to be the sum of the default heights for the buttons.

http://stackoverflow.com/q/49024632
has answer: http://stackoverflow.com/a/49031464
has comment: http://stackoverflow.com/comment/85054492
has comment: http://stackoverflow.com/comment/85054267
has comment: http://stackoverflow.com/comment/85061861
has comment: http://stackoverflow.com/comment/85056139
favorite count: 0
has comment: http://stackoverflow.com/comment/85054640
has comment: http://stackoverflow.com/comment/85054006
upvote count: 2
tagged with: classification
accepted answer: http://stackoverflow.com/a/49031464
has body: I have this image. I want to classify all of pixels. The color of the pixels in this image is as follows: Blue: Water Red: Roof White: Road Yellow: Shallow Light Green: Grass Dark Green: Tree Black: Background How can I classify all pixels. For example if pixel of 2'column and 1'row is blue then classify (1,2) into water's class and so on.
tagged with: python
downvote count: 1
type: AnsweredQuestion
has title: Classifier for colors in image
score: 1
tagged with: image
possible better answer: http://stackoverflow.com/a/49040323
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49040323

http://stackoverflow.com/a/49055004
has body: The docstring of numpy.cumsum says: Return the cumulative sum of the elements along the given axis. So that means it returns a new array. It does not modify the existing array.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49054927
type: Answer
answers question: http://stackoverflow.com/q/49054927
upvote count: 2
score: 2

http://stackoverflow.com/a/48994289
upvote count: 1
has comment: http://stackoverflow.com/comment/84996300
type: Answer
has comment: http://stackoverflow.com/comment/84996029
accepted answer of: http://stackoverflow.com/q/48993999
has comment: http://stackoverflow.com/comment/84996923
has comment: http://stackoverflow.com/comment/84996980
answers question: http://stackoverflow.com/q/48993999
has comment: http://stackoverflow.com/comment/84996815
score: 1
has comment: http://stackoverflow.com/comment/84996441
type: AcceptedAnswer
downvote count: 0
has body: If all you are doing is trying to match what a line startswith, why not use str.startswith? You can pass in a tuple of multiple matches. This is all without regular expressions too. This is reading from the file you linked to below: &gt;&gt;&gt; with open("test.vams", "r") as f: ... for line in f: ... if line.startswith(('`I_', '`IO_', '`O_', '`SUP_')): ... fn, args = line.strip('`)\n').split('(') ... args = [arg.strip() for arg in args.split(',')] ... print({'fn': fn, 'args': args}) ... {'fn': 'SUP_ANA', 'args': ['NSUP']} {'fn': 'SUP_ANA', 'args': ['PSUP']} {'fn': 'I_DIG', 'args': ['SEL', 'PSUP', 'NSUP']} {'fn': 'I_ANA', 'args': ['A']} {'fn': 'O_ANA', 'args': ['B']}

http://stackoverflow.com/comment/85006738
comment on: http://stackoverflow.com/a/49000714
type: Comment
has text: The generated `app/models.py` is pretty similar to yours. I have updated my question to reflect this.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/93152177
has text: @ScarletAndGray Thanks! It works for Jupyter notebook as well.
comment on: http://stackoverflow.com/q/49092918
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85045014
comment on: http://stackoverflow.com/q/49019919
type: Comment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84984843
type: AnswerComment
has text: Note: only works in Python 2 (Python 3 throws TypeError).
type: Comment
comment on: http://stackoverflow.com/a/48988376
score: 2

http://stackoverflow.com/a/48974540
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Use re.findall for finding all matches. Also, you have to redefine regular expression. Here is how it works: p3 = re.compile(r'(\w+man)') t = 'what if catwoman and superman got married!' r3 = p3.findall(t) # 'findall' corrected originally misspelt 'finadll' print(r3) # ['catwoman', 'superman']
type: Answer
accepted answer of: http://stackoverflow.com/q/48974482
answers question: http://stackoverflow.com/q/48974482
score: 1

http://stackoverflow.com/q/48998470
upvote count: 2
has title: How to Embed a Table in PyQt5
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/48998518
downvote count: 1
type: Question
type: AnsweredQuestion
score: 1
tagged with: pyqt
answer count: 1
has body: I have been writing a GUI in Python 3 using PyQt5. I am having trouble with trying to embed a table in PyQt's QMainWindow Class. In the code below, I have two classes - one controlling the window (with object type QMainWindow) and another (with object type QWidget) controlling the table. I know the code is generating my main window and table as they pop up in two separate windows. What I am trying to do is embed the table in the main window with the button. Like in the image below: Floating Window Issue What am I forgetting to do or not including? Thank you for the help. Here is the code: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5 import QtCore class UserInterface(QMainWindow): def __init__(self): super(UserInterface, self).__init__() self.TaskBar() self.Buttons() self.tabler = MyTable() def TaskBar(self): self.setWindowTitle("MyWindow") self.setGeometry(QDesktopWidget().screenGeometry()) def Buttons(self): close_button = QPushButton("Close", self) close_button.resize(100, 50) close_button.move(100, 900) close_button.setStyleSheet("QPushButton {font-size : 24px}") close_button.clicked.connect(sys.exit) class MyTable(QWidget): def __init__(self): super(MyTable, self).__init__() self.Table() def Table(self): self.mytable() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.setLayout(self.layout) self.show() def mytable(self): self.tableWidget = QTableWidget() self.tableWidget.setRowCount(1) self.tableWidget.setColumnCount(1) self.tableWidget.setItem(0, 0 , QTableWidgetItem("Hello")) self.tableWidget.move(300, 300) def Main(): qapplication_constructor = QApplication(sys.argv) gui = UserInterface() gui.show() sys.exit(qapplication_constructor.exec_()) if __name__ == "__main__": Main()
favorite count: 0
has answer: http://stackoverflow.com/a/48998518
tagged with: python

http://stackoverflow.com/q/49117586
has answer: http://stackoverflow.com/a/49119696
favorite count: 0
has comment: http://stackoverflow.com/comment/85240965
has comment: http://stackoverflow.com/comment/85243929
has body: Here is a python code to read a sequence ( 0.jpg ...1052.jpg) of images with VideoCapture module of openCV. import cv2 import numpy cap = cv2.VideoCapture("/path to/RGB/I%04d.jpg",cv2.CAP_IMAGES). while(1): ret,frame = cap.read() cv2.imshow('image',frame) cv2.waitKey() print(frame.shape) I get this error OpenCV Error: Assertion failed (size.width>0 &amp;&amp; size.height>0) in imshow. It seems that the frame object is empty!
tagged with: python
has title: Read a sequence of images with VideoCapture
has comment: http://stackoverflow.com/comment/85240478
score: 2
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85240883
has comment: http://stackoverflow.com/comment/85243627
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85243737
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/85240580
has comment: http://stackoverflow.com/comment/85241828
has comment: http://stackoverflow.com/comment/85240511
has answer: http://stackoverflow.com/a/49118424
tagged with: numpy
answer count: 2
linked to: http://stackoverflow.com/q/35242735

http://stackoverflow.com/q/49080298
type: Question
answer count: 2
has title: How to timestamp data collected using PySerial and export to csv?
tagged with: pyserial
has answer: http://stackoverflow.com/a/49099206
score: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49121657
has body: I'm trying to collect serial data from multiple devices, timestamp and export it to a .csv file. I want to write separate modules for each device such that they return the data to the main module and all the writing to csv is done in that. The following program writes date and time to csv but not the data returned from the device module. import time import csv from threading import Thread import fio2 def Csv_creator(): my_file = open('test_csv.csv', 'w+') with my_file: new_file = csv.writer(my_file) def Timestamp(): date_now = time.strftime('%d/%m/%y') time_now = time.strftime('%H:%M:%S') return [date_now,time_now] def Write_loop(): Csv_creator() fio2.Initialize() while True: with open('test_csv.csv', 'a') as f: [date_now,time_now] = Timestamp() fio2_data = fio2.Reader() print fio2_data to_write = [date_now,time_now,fio2_data] csv_file = csv.writer(f) csv_file.writerow(to_write) t = Thread(target=Write_loop) t.daemon = True t.start() raw_input("Press any key to stop \n") The device module is as shown below. It works fine on it's own but I have a hard time making it return the value and have it written onto the csv file. import serial ser = serial.Serial("COM6", baudrate=2400, bytesize=serial.EIGHTBITS, parity =serial.PARITY_ODD, timeout=1, writeTimeout =1) def Initialize(): global ser try: ser.isOpen() print("\n Serial is open") except: print ("Error: serial Not Open") def Reader(): global ser if (ser.isOpen()): try: x = ser.readline().decode() x = (x) return x except: return "unable to print" else: return "cannot open serial port"
has comment: http://stackoverflow.com/comment/85191686
possible better answer: http://stackoverflow.com/a/49099206
has comment: http://stackoverflow.com/comment/85191446
tagged with: multithreading
tagged with: python
tagged with: timestamp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85242014
accepted answer: http://stackoverflow.com/a/49121657
has comment: http://stackoverflow.com/comment/85168753

http://stackoverflow.com/q/49028160
accepted answer: http://stackoverflow.com/a/49028375
has title: I cannot get django debug toolbar to appear in the browser. Project is attached
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58232369
has body: Its a very simple small project located here https://github.com/cbaldwin20/project_8/tree/master/project_eight I tried for like two hours to get the 'django debug toolbar' to appear in the browser with no success. I'm not sure if its my code or my computer. Thanks for any help.
score: 1
has answer: http://stackoverflow.com/a/49028261
type: Question
has answer: http://stackoverflow.com/a/49028375
possible better answer: http://stackoverflow.com/a/49028261
downvote count: 0
linked to: http://stackoverflow.com/q/10517765
has answer: http://stackoverflow.com/a/68430473
answer count: 4
favorite count: 0

http://stackoverflow.com/q/49081097
has comment: http://stackoverflow.com/comment/85168053
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/49081225
type: Question
has answer: http://stackoverflow.com/a/49081225
has body: I have a data frame which have two columns in JSON format, like this: author biblio series Mehrdad Vahabi {'volume': 68, 'month': 'January', {'handle':'RePEc:aka:aoecon', 'name': 'Oeconomica'} 'name': 'János Kornai', 'issue': 's', 'handle': 'n:v:68:y:2018:i', 'year': '2018', 'pages': '27-52', 'doi': ''} Michael Bailey {'c_date': '2017', 'number': {'handle': '', 'name': ''} '23608', 'handle': 'RePEc:nbr: nberwo:23608', 'name': 'Measuring'} I Want to my data frame looks like this: author biblio.volume biblio.month biblio.name biblio.issue biblio.handle bibilio.year biblio.pages biblio.doi biblio.c_date bibi¡lio.number series.handle series.name Mehrdad Vahabi 68 January János Kornai s n:v:68:y:2018:i 2018 27-52 NA NA RePEc:aka:aoecon Oeconomica Michael Bailey NA Na Meausuring NA nberwo:23608 NA NA NA 2017 23608 I try do it using the answers in this question, but no one works for me. How can I do it? [EDIT] Here is a sample of the data [EDIT] Following the @jezrael solution I get this: df1 = pd.DataFrame(df['biblio'].values.tolist()) df1.columns = 'biblio.'+ df1.columns df2 = pd.DataFrame(df['series'].values.tolist()) df2.columns = 'series.'+ df2.columns col = df.columns.difference(['biblio','series']) df = pd.concat([df[col], df1, df2],axis=1) print (df) Traceback (most recent call last): File "dfs.py", line 8, in &lt;module&gt; df1.columns = 'bibliographic.'+ df1.columns File "/Users/danielotero/anaconda3/lib/python3.6/site- packages/pandas/core/indexes/range.py", line 583, in _evaluate_numeric_binop other = self._validate_for_numeric_binop(other, op, opstr) File "/Users/danielotero/anaconda3/lib/python3.6/site- packages/pandas/core/indexes/base.py", line 3961, in _validate_for_numeric_binop raise TypeError("can only perform ops with scalar values") TypeError: can only perform ops with scalar values And with json_normalize: Traceback (most recent call last): File "/Users/danielotero/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2525, in get_…
upvote count: 12
accepted answer: http://stackoverflow.com/a/49081366
score: 12
answer count: 2
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/39899005
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49081366
type: AnsweredQuestion
has title: Slice pandas dataframe json column into columns

http://stackoverflow.com/comment/85023142
comment on: http://stackoverflow.com/q/49003798
has text: It would be a bit churlish to close this question as a dupe when there are two good answers below, so here are a couple of places where this question has been asked before in case they're a useful reference: [one](https://stackoverflow.com/questions/34069151/increase-numpy-array-elements-using-array-as-index/34069294#34069294) [two](https://stackoverflow.com/questions/34069151/increase-numpy-array-elements-using-array-as-index/34069294#34069294)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49010258
score: 2
has body: I want to list and describe the tables present in an Oracle database. To do this by connecting to the database with a client such as SQL Plus, a working approach is: List the tables: select tablespace_name, table_name from all_tables; Get columns and data types for each table: describe [table_name]; However when using cx_Oracle through python, cur.execute('describe [table_name]') results in an 'invalid sql' error. How can we use describe with cx_Oracle in python?
downvote count: 0
has answer: http://stackoverflow.com/a/49033302
has title: Get the schema of an Oracle database with python
type: Question
has answer: http://stackoverflow.com/a/49010259
answer count: 2
has comment: http://stackoverflow.com/comment/85041408
upvote count: 2
tagged with: cx-oracle
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85201526
comment on: http://stackoverflow.com/q/49059772
score: 0
type: Comment
has text: Please consider to upvote, accept or comment the answer if they solved your problem. It's The best way to say thanks to other people here at SO when they invest time in posting them. Thanks!
type: QuestionComment

http://stackoverflow.com/a/48997495
has comment: http://stackoverflow.com/comment/85000585
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/85000525
has body: Your deal_by_detail URL pattern captures any sequence of characters. So it will match any URL; none of the other patterns below it will ever be called. You should make that much more specific, just as you have for the category pattern. url(r'^(?P&lt;slug&gt;\w+)/$', deal_by_detail, name='deal_detail'),
score: 2
has comment: http://stackoverflow.com/comment/85000561
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48997218
answers question: http://stackoverflow.com/q/48997218

http://stackoverflow.com/a/58831294
answers question: http://stackoverflow.com/q/49048262
has body: Changing the way I created TF Records worked out for me. Have a look at the following code - example = 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_str.encode('utf-8')), 'image/source_id': dataset_util.bytes_feature(filename_str.encode('utf-8')), 'image/format': dataset_util.bytes_feature(image_format), 'image/encoded': dataset_util.bytes_feature(image_data), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmin), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmax), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymin), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymax), 'image/object/class/text': dataset_util.bytes_list_feature(labels_text), 'image/object/class/label': dataset_util.int64_list_feature(labels), } ) ) Make sure that the TF Records have the same keys as the ones shown above. This is due to the fact that the model that you use would be expecting keys similar to the ones above. I hope this helps. Earlier, I had made use of the following, which did not work out- example = tf.train.Example( features= tf.train.Features( feature={ 'image/height': dataset_util.int64_feature(shape[0]), 'image/width': dataset_util.int64_feature(shape[1]), 'image/channels': dataset_util.int64_feature(shape[2]), 'image/shape': dataset_util.int64_list_feature(shape), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmin), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmax), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymin), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymax), 'image/object/bbox/class/label': dataset_util.int64_list_feature(labels), 'image/object/bbox/class/text': dataset_util.bytes_list_feature(labels_text), 'image/object/bbox/difficult': dataset_util.int64_list_feature(difficult), 'image/object/bbox/truncated…
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/49117755
answers question: http://stackoverflow.com/q/49094242
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85245837
has comment: http://stackoverflow.com/comment/85246041
has comment: http://stackoverflow.com/comment/85247552
accepted answer of: http://stackoverflow.com/q/49094242
type: Answer
score: 3
upvote count: 3
has body: Here is a similar approach. We will split data sets into train and test ones. train data set will be used for tuning hyperparameters and for fitting different models. Then we will choose the best (in terms of MSE) model and predict values from the test data set. All trained (fitted) models will be saved as Pickle files, so they can be loaded later on using joblib.load() method. Output: ----------------------------- [SVR_rbf] ------------------------------ Fitting 3 folds for each of 4 candidates, totalling 12 fits ---------------------------- [SVR_linear] ---------------------------- Fitting 3 folds for each of 4 candidates, totalling 12 fits ------------------------------ [Ridge] ------------------------------- Fitting 3 folds for each of 7 candidates, totalling 21 fits ------------------------------ [Lasso] ------------------------------- Fitting 3 folds for each of 6 candidates, totalling 18 fits --------------------------- [RandomForest] --------------------------- Fitting 3 folds for each of 3 candidates, totalling 9 fits ----------------------------- [SVR_rbf] ------------------------------ Score: 44.88% Parameters: {'SVR_rbf__C': 10, 'SVR_rbf__max_iter': 500} ********************************************************************** ---------------------------- [SVR_linear] ---------------------------- Score: 33.40% Parameters: {'SVR_linear__C': 0.01, 'SVR_linear__max_iter': 1000} ********************************************************************** ------------------------------ [Ridge] ------------------------------- Score: 34.83% Parameters: {'Ridge__alpha': 500, 'Ridge__max_iter': 200} ********************************************************************** ------------------------------ [Lasso] ------------------------------- Score: 22.90% Parameters: {'Lasso__alpha': 0.1, 'Lasso__max_iter': 1000} ********************************************************************** --------------------------- [RandomForest] --------------------------- Score: 36.87% Paramete…

http://stackoverflow.com/q/49098605
has title: How do I add items to multiple lists inside a loop?
has answer: http://stackoverflow.com/a/49106994
accepted answer: http://stackoverflow.com/a/49106994
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85202522
tagged with: list
tagged with: loops
type: Question
has body: I am trying to add items to 9 lists that are already in 9 other lists. I would like to have the first element of every list in the first list. And then the second element of each list into a second list. So for example, I want my first output list using the three lists [1,2,3] and [3,2,1] to be [1,3]. I've come up with this but it keeps returning a KeyError: def sudokuSolver(): row1,row2,row3,row4,row5,row6,row7,row8,row9=([] for i in range(9)) for k in range(1,10): for l in range(9): globals()['row%s' % k].append(globals()['cell%s' % k][l])
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/85202588
has comment: http://stackoverflow.com/comment/85202677
tagged with: python

http://stackoverflow.com/q/49114778
has comment: http://stackoverflow.com/comment/85235071
has title: Python regex to validate expression
type: Question
has comment: http://stackoverflow.com/comment/85234893
tagged with: python
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/85234633
tagged with: python-3.x
upvote count: 2
has body: I'm trying to check the validity of some expressions using a Python regex. Expressions could be like these ones: (expand(function_1(&lt;&lt;TAG_1&gt;&gt;)) or expand(function_2(&lt;&lt;TAG_2&gt;&gt;))) and tag_value(&lt;&lt;TAG_3&gt;&gt;) &gt;= 3 What I need to validate is that all expression is valid (means that it has a correct number of parenthesis, all arithmetical operators are present and so on) and especially, that inside expand function there is only one argument; means that the following example is wrong: (expand(function_1(&lt;&lt;TAG_1&gt;&gt;) and function_3(&lt;&lt;TAG_4&gt;&gt;)) or expand(function_2(&lt;&lt;TAG_2&gt;&gt;))) and tag_value(&lt;&lt;TAG_3&gt;&gt;) &gt;= 3 To do that, I wrote this Python regex: expand\s*\(\s*(\&lt;\&lt;(.+)\&gt;\&gt;\s*[\+-/\*\&lt;\&gt;\=\s*0-9]+|([A-Za-z0-9_]+)\s*\(\s*(\&lt;\&lt;(.+)\&gt;\&gt;|\&lt;\&lt;(.+)\&gt;\&gt;\s*,\s*.*)\))\s*\) Debuggex Demo As you can see from the debuggex demo, the string used as test is not valid (expand( function_1(&lt;&lt;TAG_1&gt;&gt;) and &lt;&lt;pippo&gt;&gt; &lt; 3) or expand(function_2(&lt;&lt;TAG_2&gt;&gt;))) and tag_value(&lt;&lt;TAG_3&gt;&gt;) &gt;= 3 More in details, seems that it takes from the first expand until the last one. How is it possible fix the regex to achieve this goal? Thank you in advance
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85235445
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/85235309

http://stackoverflow.com/q/49071121
favorite count: 0
type: Question
tagged with: python
tagged with: macos
score: 10
has body: When I run virtualenv, I get this: $ virtualenv -bash: /usr/local/bin/virtualenv: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory virtualenv only started behaving this way today. It worked yesterday. It breaks because virtualenv is a Python script using a nonexistent Python interpreter: $ head -1 $(which virtualenv) #!/usr/local/opt/python/bin/python2.7 On my machine, /usr/local/opt/python is a symlink to a Python 3.6 directory: $ ls -l /usr/local/opt/python lrwxr-xr-x 1 jim admin 24 2 Mar 13:45 /usr/local/opt/python -&gt; ../Cellar/python/3.6.4_3 As expected, the Python 3.6 directory does not contain a bin/python2.7: $ ls /usr/local/Cellar/python/3.6.4_3/bin/ 2to3 idle pip3 pydoc3.6 python3-config python3.6m-config wheel3 2to3-3.6 idle3 pip3.6 python python3.6 pyvenv easy_install idle3.6 pydoc python-config python3.6-config pyvenv-3.6 easy_install-3.6 pip pydoc3 python3 python3.6m wheel virtualenv clearly expects /usr/local/opt/python to contain Python 2 material, but it only contains Python 3 material. My /usr/local/opt/python is managed by Homebrew. I don't know the provenance of my virtualenv. How do I find out where my /usr/local/bin/virtualenv came from? Which is to blame? My virtualenv or Homebrew?
tagged with: homebrew
answer count: 3
has answer: http://stackoverflow.com/a/49071619
has title: virtualenv on macOS uses nonexistent python interpreter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54304196
upvote count: 10
downvote count: 0
has answer: http://stackoverflow.com/a/52617876
tagged with: virtualenv

http://stackoverflow.com/comment/85134082
has text: it outputs '/usr/bin/python', now i have python , python2, python2.7, python3, python3.4 binaries in same bin folder. how do i make sure that it uses right binary?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49064425

http://stackoverflow.com/comment/85130689
comment on: http://stackoverflow.com/a/49062598
score: 0
type: Comment
has text: Ye I tried going through it quickly I have a project due Friday week so just sorting out some last bits with users and profiles. Thanks
type: AnswerComment

http://stackoverflow.com/q/48997401
tagged with: string
favorite count: 0
linked to: http://stackoverflow.com/q/8222855
tagged with: python
possible better answer: http://stackoverflow.com/a/48997548
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48997548
score: 1
has answer: http://stackoverflow.com/a/48997610
upvote count: 1
has title: Convert titlecase words in the string to lowercase words
type: Question
downvote count: 0
tagged with: lowercase
answer count: 2
accepted answer: http://stackoverflow.com/a/48997610
has body: I want to convert all the titlecase words (words starting with uppercase character and having rest of the characters as lowercase) in the string to the lowercase characters. For example, if my initial string is: text = " ALL people ARE Great" I want my resultant string to be: "ALL people ARE great" I tried the following but it did not work text = text.split() for i in text: if i in [word for word in a if not word.islower() and not word.isupper()]: text[i]= text[i].lower() I also checked related question Check if string is upper, lower, or mixed case in Python.. I want to iterate over my dataframe and for each word that meet this criteria.

http://stackoverflow.com/a/49015945
score: 3
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49015864
has body: The file will be automatically closed during exit or garbage collection. But as best practices matter, the better approach would be to use a context manager such as below: with open(pathf, "r") as f: fdata = f.read().splitlines() Thank you.
downvote count: 0

http://stackoverflow.com/q/49018497
has answer: http://stackoverflow.com/a/49213064
linked to: http://stackoverflow.com/q/39547598
has comment: http://stackoverflow.com/comment/85209230
tagged with: python
tagged with: debian
has body: This is a pretty bizarre situation I have encountered. I have the following simple Python script: from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.add_argument("-headless") browser = webdriver.Firefox(firefox_options=options) browser.get("https://www.google.com") print(browser.current_url) And wrapper for the script: #!/bin/bash wget https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-linux64.tar.gz tar -xzvf geckodriver-v0.19.1-linux64.tar.gz chmod 777 geckodriver mv geckodriver /usr/bin/ firefox -v # python3 when ubuntu python test.py Additionally I have two Dockerfiles: Dockerfile A (Ubuntu; works fine): FROM ubuntu:16.04 RUN apt-get update -y &amp;&amp; apt-get install -y python3 \ python3-pip \ firefox \ build-essential \ wget COPY . /app WORKDIR /app RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt ENTRYPOINT ["bash"] CMD ["test_wrapper.sh"] Dockerfile B (Debian; crashes): FROM continuumio/anaconda3:5.0.1 RUN apt-get update -y &amp;&amp; apt-get install -y iceweasel \ build-essential \ wget COPY . /app WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt ENTRYPOINT ["bash"] CMD ["test_wrapper.sh"] test.py run from the image built from Dockerfile B throws the following exception: selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 1 The geckodriver.log shows the following error: GTK_BACKEND doesn't match available displays Has anyone encountered this and know a workaround? It shouldn't need access to a display because it's running headless - unless selenium Firefox options are different in iceweasel than regular Firefox? I expected similar behavior, and I would much prefer to use the Anaconda image I just tried this which I was almost certain would solve it but it did not work. EDIT: I do not believe this is a geckodriver issue as I tried the same Dockerfile with firefox-esr i…
has comment: http://stackoverflow.com/comment/85208913
tagged with: selenium
has title: Selenium Firefox webdriver works on images built from Ubuntu but not on images built from Debian
upvote count: 7
accepted answer: http://stackoverflow.com/a/49213064
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49213000
has answer: http://stackoverflow.com/a/49213000
score: 7
tagged with: iceweasel
has comment: http://stackoverflow.com/comment/85186475
type: Question
answer count: 2
downvote count: 0
favorite count: 0
tagged with: docker

http://stackoverflow.com/comment/85221597
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49108278
has text: This comes down to a matter of preference, but you can also use `operator.itemgetter`: `[(min(map(itemgetter(0), g)), k) for k, g in groupby(d.items(), key=itemgetter(1))]`. I upvoted nonetheless :).

http://stackoverflow.com/a/49085917
has comment: http://stackoverflow.com/comment/85225862
downvote count: 0
has body: For a simple logo like in the example, where all edges worth looking for are between foreground and background, the transparency mask has all the information you need: mask = source[:,:,3] You can look for the edges of mask and find all the edges in the Reuters logo. I think this is true for most logos, but some might be more complex, though.
answers question: http://stackoverflow.com/q/49071592
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/49049318
has answer: http://stackoverflow.com/a/49070934
accepted answer: http://stackoverflow.com/a/49070934
score: 4
has body: I have a bunch of photos like this: I would like to automatically crop the image so that just the photograph (and possibly the caption) are shown. I tried detecting contours, but they found the borders of objects in the photo and not the photo itself. There's also a spurious contour for the edges of the image as well as other small ones. What can I do to get just the rectangle that includes the photo?
answer count: 1
has comment: http://stackoverflow.com/comment/85146523
favorite count: 0
has comment: http://stackoverflow.com/comment/85146739
has comment: http://stackoverflow.com/comment/85102832
tagged with: python
upvote count: 4
tagged with: opencv
type: AnsweredQuestion
downvote count: 0
tagged with: image-processing
has title: Cropping rectangular photos from scans in OpenCV with Python
type: Question

http://stackoverflow.com/comment/85166861
type: QuestionComment
score: 1
has text: In your `page_pro` function, if the first condition isn't met you don't return anything, and then you try to print the return value, which will be None
comment on: http://stackoverflow.com/q/49080536
type: Comment

scipy
tags question: http://stackoverflow.com/q/48995378
tags question: http://stackoverflow.com/q/49098466
tags question: http://stackoverflow.com/q/48981856
tags question: http://stackoverflow.com/q/49023851
tags question: http://stackoverflow.com/q/49015138
tags question: http://stackoverflow.com/q/49101574
tags question: http://stackoverflow.com/q/48986606
tags question: http://stackoverflow.com/q/49085456
type: Tag
tag name: scipy
tags question: http://stackoverflow.com/q/49058788
tags question: http://stackoverflow.com/q/49050642
tags question: http://stackoverflow.com/q/48995278
tags question: http://stackoverflow.com/q/49007201
tags question: http://stackoverflow.com/q/48966834
tags question: http://stackoverflow.com/q/48970785
tags question: http://stackoverflow.com/q/48984858
tags question: http://stackoverflow.com/q/49029995
tags question: http://stackoverflow.com/q/49085503
tags question: http://stackoverflow.com/q/48968242
tags question: http://stackoverflow.com/q/48985352
tags question: http://stackoverflow.com/q/49109466
tags question: http://stackoverflow.com/q/49043070
tags question: http://stackoverflow.com/q/49061906
tags question: http://stackoverflow.com/q/49104677
tags question: http://stackoverflow.com/q/49094774
tags question: http://stackoverflow.com/q/48969243
tags question: http://stackoverflow.com/q/49007421
tags question: http://stackoverflow.com/q/49109481
tags question: http://stackoverflow.com/q/49039465
tags question: http://stackoverflow.com/q/49061066
tags question: http://stackoverflow.com/q/49118890
tags question: http://stackoverflow.com/q/49073711
tags question: http://stackoverflow.com/q/49016939
tags question: http://stackoverflow.com/q/49085832
tags question: http://stackoverflow.com/q/49032732
tags question: http://stackoverflow.com/q/48999970
tags question: http://stackoverflow.com/q/49013020
tags question: http://stackoverflow.com/q/49093070
tags question: http://stackoverflow.com/q/48996148
tags question: http://stackoverflow.com/q/49073609
tags question: http://stackoverflow.com/q/49086896
tags question: http://stackoverflow.com/q/48975480
tags question: http://stackoverflow.com/q/49006033
tags question: http://stackoverflow.com/q/49072378
tags question: http://stackoverflow.com/q/49023337
tags question: http://stackoverflow.com/q/49036853
tags question: http://stackoverflow.com/q/49038022
tags question: http://stackoverflow.com/q/49055591
tags question: http://stackoverflow.com/q/48972133

http://stackoverflow.com/a/48973081
has comment: http://stackoverflow.com/comment/84951737
type: Answer
answers question: http://stackoverflow.com/q/48972216
has comment: http://stackoverflow.com/comment/84951690
has body: Your code have broken many PEP-8 style guide notes, that i suggest you read or reread, it will help you, maybe not now, but in future. I strongly suggest you to rething all the app architecture and business logic and use rest_framework.generics views, they will do all work for you. I will put that pieces that i would like to be your start point of writing better app: app/models.py from django.db import models class Product(models.Model): ... class CartItem(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL) product = models.ForeignKey(to='Product') quantity = models.PositiveIntegerField(default=0) app/serializers.py from . import CartItem, Product class ProductSerializer(serialziers.ModelsSerializer): class Meta: model = Product fields = (&lt;your_fields&gt;,) class CartItemSerializer(serialziers.ModelSerializer): product = ProductSerializer() class Meta: model = CartItem fields = ('product', 'quantity', ) app/views.py from rest_framework import generics from .serializers import CartItemSerializer class CartAPIView(generics.ListAPIView): serializer_class = CartItemSerializer def get_queryset(self) return CartItem.objects.filter(user=self.request.user)
score: 0

http://stackoverflow.com/comment/85189300
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49091961
type: Comment
has text: @MaximHaytovich, can you run the test code in my answer to see if it works? It worked for me.

http://stackoverflow.com/comment/85082780
type: Comment
has text: I was trying to give some context as to why it was important to start the background task first, but since it's confusing I edited the question and removed it. (fwiw `task_result` is set to something outside the loop as an initial value)
type: QuestionComment
comment on: http://stackoverflow.com/q/49037949
score: 0

http://stackoverflow.com/q/49061180
tagged with: loops
type: Question
has body: I'm trying to make two loops in the same program but it only stays on the first loop and it doesn't go to the second loop... I'm trying to make the program write the temperature in a text file without overwriting itself... There's my program: GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(18,GPIO.OUT) os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 return temp_c while True: print(read_temp()) time.sleep(0.5) if read_temp() &gt; 25: GPIO.output(18, True) else: GPIO.output(18, False) while True: f = open("temperatureFile.txt", "w") f.write(read_temp()) f.close
has comment: http://stackoverflow.com/comment/85127442
answer count: 2
has title: Python, How to create 2 loops in one script so it works
possible better answer: http://stackoverflow.com/a/49061246
has answer: http://stackoverflow.com/a/49061246
tagged with: while-loop
tagged with: python
has answer: http://stackoverflow.com/a/49061258
has comment: http://stackoverflow.com/comment/85127507
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49061258
score: 0

http://stackoverflow.com/q/49003764
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85013488
score: 1
has answer: http://stackoverflow.com/a/49005175
possible better answer: http://stackoverflow.com/a/49005088
has comment: http://stackoverflow.com/comment/85013272
has answer: http://stackoverflow.com/a/49005088
type: Question
has body: I am accessing different websites to practice web scraping and trying to web scrape the following website - http://www.pizzahut.com.cn/StoreList I have posted a similar question previously on web scraping the same website. The answer provided worked perfectly well allowing me to extract all lat and long for all stores in one city. However, I also want to extract lat and long for stores from multiple cities and encountered a problem which I needed some guidance. Changing cities do not alter URL as well. The website is all in Chinese so I had to use google translation to make it into english and work along the way. How I chose different city is shown in the image highlighted as red above. I basically clicked that link and chose the city I want to display. I would like to see stores' latitude and longitude for different cities or just Beijing given the example. Below is the code that I have been working currently. The code below only extracts out latitude and longitude for all stores in Shanghai, which is shown on a default page. import os import requests import csv import time from bs4 import BeautifulSoup csv_name = 'Lat_long_practice.csv' csv = open(csv_name, 'w', encoding='utf-8-sig') columnTitleRow = "Name, Latitude, Longitude\n" csv.write(columnTitleRow) for page_no in range(1, 14): data = {'pageIndex': page_no, 'pageSize': 10, 'keyword': '输入餐厅地址或餐厅名称'} page = requests.post('http://www.pizzahut.com.cn/StoreList/Index', data=data) soup = BeautifulSoup(page.text, 'html.parser') print('PAGE', page_no) for row in soup.find_all('div',class_='re_RNew'): name = row.find('p',class_='re_NameNew').string #Get the name of the store info = row.find('input').get('value') location = info.split('|') #print(location) row = '' if location[0] == '': print(name) row = name + ',' + '' + ',' + '' + '\n' csv.write(row) else: location_data = location[0].split(',') latitude = location_data[0] longitude = location_data[1] print(name, latitude, longitude) row = name + ',' + latitude + ','…
has comment: http://stackoverflow.com/comment/85014573
has answer: http://stackoverflow.com/a/49005439
has title: How to web scrape multiple pages with different cities in unchanging URL - Python 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85013625
has comment: http://stackoverflow.com/comment/85013082
answer count: 3
has comment: http://stackoverflow.com/comment/85013667
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/49005439
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85014396
tagged with: web-scraping
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85013801

http://stackoverflow.com/q/49119453
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49119631
has comment: http://stackoverflow.com/comment/85244639
has comment: http://stackoverflow.com/comment/85244780
has comment: http://stackoverflow.com/comment/85244404
answer count: 2
possible better answer: http://stackoverflow.com/a/49120533
has comment: http://stackoverflow.com/comment/85244689
accepted answer: http://stackoverflow.com/a/49119631
has answer: http://stackoverflow.com/a/49120533
favorite count: 0
has body: Had PIP working normally until few days ago. Not sure how. Trying to run it now and now show issues. Adding full stack bellow of the error: Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 487, in _prepare_file req_to_install, finder) File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 428, in _check_skip_installed req_to_install, upgrade_allowed) File "/usr/local/lib/python2.7/site-packages/pip/index.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "/usr/local/lib/python2.7/site-packages/pip/index.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "/usr/local/lib/python2.7/site-packages/pip/index.py", line 568, in _get_pages page = self._get_page(location) File "/usr/local/lib/python2.7/site-packages/pip/index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/local/lib/python2.7/site-packages/pip/index.py", line 792, in get_page "Cache-Control": "max-age=600", File "/usr/local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 488, in get return self.request('GET', url, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip/download.py", line 386, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py", line 475, in request resp = self…
has comment: http://stackoverflow.com/comment/85245023
has title: How to completely remove and install again PIP on MacOS Sierra (10.x)?
tagged with: python
has comment: http://stackoverflow.com/comment/85244739
has comment: http://stackoverflow.com/comment/85244428
type: AnsweredQuestion
tagged with: installation
score: 0
tagged with: pip
upvote count: 1

http://stackoverflow.com/a/49120469
has comment: http://stackoverflow.com/comment/85271949
type: Answer
score: 0
has body: Not sure if fuzzy match is what you are looking for. Maybe make every name a proper name? df1.Name = df1.Name.apply(lambda x: x.title()) df2.Name = df2.Name.apply(lambda x: x.title()) pd.merge(df1, df2, how='inner', on='Name')
answers question: http://stackoverflow.com/q/49120364
has comment: http://stackoverflow.com/comment/85246561

http://stackoverflow.com/comment/85184799
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49089025
type: QuestionComment
has text: Posted :) sorry it's a bit messy, would you like the code from the CNN itself as well? thank you

http://stackoverflow.com/q/48988428
score: -1
has comment: http://stackoverflow.com/comment/84981379
has title: how to store and load a list to and from a file in python, while retaining its element type
has body: if i store objects in a list. and i want this list to be stored in a file, in such a way that this list, when loaded from the file. It must contain same characteristics as before it saved, like element type.
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48988470
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48988470
tagged with: list
downvote count: 1
type: Question

http://stackoverflow.com/q/49024226
tagged with: dataframe
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/49025819
has comment: http://stackoverflow.com/comment/85053115
has answer: http://stackoverflow.com/a/49031559
has comment: http://stackoverflow.com/comment/85053231
has comment: http://stackoverflow.com/comment/85053683
favorite count: 0
has comment: http://stackoverflow.com/comment/85053655
has comment: http://stackoverflow.com/comment/85053491
type: Question
tagged with: http://stackoverflow.com/tag/csv
answer count: 2
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/85053601
has comment: http://stackoverflow.com/comment/85053444
has comment: http://stackoverflow.com/comment/85053599
downvote count: 3
has body: I am reading my data from a CSV file using pandas and it works well with range 700. But as soon as I go above 700 and trying to append to a list in python it is showing me list index out of range. But the CSV has around 500K of rows Can anyone help me with that why is it happening? Thanks in advance. import pandas as pd df_email = pd.read_csv('emails.csv',nrows=800) test_email = df_email.iloc[:,-1] list_of_emails = [] for i in range(len(test_email)): var_email = test_email[i].split("\n") #this code takes one single email splits based on a new line giving a python list of all the strings in the email email = {} message_body = '' for _ in var_email: if ":" in _: var_sentence = _.split(":") #this part actually uses the ":" to find the elements in the list that have ":" present for j in range(len(var_sentence)): if var_sentence[j].lower().strip() == "from": email['from'] = var_sentence[var_sentence.index(var_sentence[j+1])].lower().strip() elif var_sentence[j].lower().strip() == "to": email['to'] = var_sentence[var_sentence.index(var_sentence[j+1])].lower().strip() elif var_sentence[j].lower().strip() == 'subject': if var_sentence[var_sentence.index(var_sentence[j+1])].lower().strip() == 're': email['subject'] = var_sentence[var_sentence.index(var_sentence[j+2])].lower().strip() else: email['subject'] = var_sentence[var_sentence.index(var_sentence[j+1])].lower().strip() elif ":" not in _: message_body += _.strip() email['body'] = message_body list_of_emails.append(email)
has title: Python Programming Error for DataScience DataFrame
has comment: http://stackoverflow.com/comment/85053461
has comment: http://stackoverflow.com/comment/85053137
has comment: http://stackoverflow.com/comment/85053956
upvote count: 0

http://stackoverflow.com/a/49036356
answers question: http://stackoverflow.com/q/49036124
has body: I guess it's encrypted, you need to first copy the snapshot and change the keys and the restore. https://aws.amazon.com/premiumsupport/knowledge-center/rds-snapshots-share-account/
score: 3
downvote count: 0
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49036124

http://stackoverflow.com/comment/85109754
comment on: http://stackoverflow.com/q/49051965
has text: Sorry for the awkward code, I fixed some glaring oversights.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84972172
comment on: http://stackoverflow.com/q/48983597
score: 0
type: QuestionComment
type: Comment
has text: Do you really need to see the source code to use the libraries? But as stated, if you are using CPython, most of hte built-in libraries are implemented in C, and you won't have access to the source. You can find it on the github repo, though.

http://stackoverflow.com/a/49103755
accepted answer of: http://stackoverflow.com/q/49101978
answers question: http://stackoverflow.com/q/49101978
has body: Thanks to @quantik and @Iguananaut (see this), I could find a more general solution that works for calling Python functions from .py and .ipynb files: func.py Content: import os.path import sys import urllib.request import json def this_file(): # prints the address of this file print(__file__) return __file__ def that_file(): # prints the address of the file that is calling this function if sys.argv[0][-21:]=='ipykernel_launcher.py': print('Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead.') return False else: print(os.getcwd() + "/" + sys.argv[0]) return os.getcwd() + "/" + sys.argv[0] def that_notebook(base_url='http://127.0.0.1:8888'): # prints the address of the notebook that is calling this function ## read more about Jupyter APIL: https://github.com/jupyter/jupyter/wiki/Jupyter-Notebook-Server-API # See if the url is correct try: sessions = json.load(urllib.request.urlopen(base_url+'/api/sessions')) except: print('Oops! %s is an invalid URL.' % (base_url+'/api/sessions')) return False # See if there is any active session if len(sessions) == 0: print('No active session found!') print('Are you calling me from a Python file? Try "that_file()" instead.') return False # In case of multiple active sessions, only print the most recently latest=max([s['kernel']['last_activity'] for s in sessions]) for s in sessions: if s['kernel']['last_activity']==latest: print(s['path']) return(s['path']) calls.py Contents: from func import * this_file() that_file() that_notebook() Outputs: python calls.py /home/jovyan/work/calls.py No active session found! Are you calling me from a Python file? Try "that_file()" instead. jovyan@c5cd7b908543:~/work$ calls.ipynb Contents: from func import * this_file() that_file() that_notebook() Outputs: calls.ipynb /home/jovyan/work/func.py Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead. work/calls.ipynb
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85419543

http://stackoverflow.com/comment/84954710
has text: no it's acutally 2-dimensional...i used this as a datastructure to acces the elements with "my_list[row_number][column_number]"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48974122

http://stackoverflow.com/comment/85166758
has text: Okay, thank you. Do you think that creating another separate table to log the numbers in would be the best choice then? This way I can still keep each number that is associated with a name in the original database together. So one db, keeping personal information together (name, email, country, and phone associated to that name), and the other db, keeping track of what numbers have been used and which ones have not?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49080472
type: Comment

http://stackoverflow.com/q/49099637
accepted answer: http://stackoverflow.com/a/49099823
tagged with: try-finally
has comment: http://stackoverflow.com/comment/85235667
has comment: http://stackoverflow.com/comment/85224289
answer count: 6
score: 47
has comment: http://stackoverflow.com/comment/85218213
has comment: http://stackoverflow.com/comment/85211611
tagged with: control-flow
has answer: http://stackoverflow.com/a/49099823
tagged with: exception
upvote count: 49
tagged with: python
has answer: http://stackoverflow.com/a/59942309
has body: Is it possible to tell if there was an exception once you're in the finally clause? Something like: try: funky code finally: if ???: print('the funky code raised') I'm looking to make something like this more DRY: try: funky code except HandleThis: # handle it raised = True except DontHandleThis: raised = True raise else: raised = False finally: logger.info('funky code raised %s', raised) I don't like that it requires to catch an exception, which you don't intend to handle, just to set a flag. Since some comments are asking for less "M" in the MCVE, here is some more background on the use-case. The actual problem is about escalation of logging levels. The funky code is third party and can't be changed. The failure exception and stack trace does not contain any useful diagnostic information, so using logger.exception in an except block is not helpful here. If the funky code raised then some information which I need to see has already been logged, at level DEBUG. We do not and can not handle the error, but want to escalate the DEBUG logging because the information needed is in there. The funky code does not raise, most of the time. I don't want to escalate logging levels for the general case, because it is too verbose. Hence, the code runs under a log capture context (which sets up custom handlers to intercept log records) and some debug info gets re-logged retrospectively: try: with LogCapture() as log: funky_code() # &lt;-- third party badness finally: # log events are buffered in memory. if there was an exception, # emit everything that was captured at a WARNING level for record in log.captured: if &lt;there was an exception&gt;: log_fn = mylogger.warning else: log_fn = getattr(mylogger, record.levelname.lower()) log_fn(record.msg, record.args)
has answer: http://stackoverflow.com/a/49099889
favorite count: 0
has answer: http://stackoverflow.com/a/49113413
downvote count: 2
has title: How to determine if an exception was raised once you're in the finally block?
has answer: http://stackoverflow.com/a/49099726
tagged with: logging
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85232349
has comment: http://stackoverflow.com/comment/85218138
has comment: http://stackoverflow.com/comment/85218324
has answer: http://stackoverflow.com/a/49099799
possible better answer: http://stackoverflow.com/a/49099889
type: Question

timer
tag name: timer
tags question: http://stackoverflow.com/q/49035368
type: Tag
tags question: http://stackoverflow.com/q/48984512

http://stackoverflow.com/q/48997718
has comment: http://stackoverflow.com/comment/85036990
tagged with: python
has comment: http://stackoverflow.com/comment/85114324
score: 0
tagged with: machine-learning
tagged with: tensorflow
type: UnansweredQuestion
tagged with: bazel
has comment: http://stackoverflow.com/comment/85090381
answer count: 0
tagged with: usps
has body: Currently attempting to run Google's Pixel Level Domain Adaptation Model. We were able to run MNIST to MNIST-M training and testing. Added the USPS tfrecords in the datasets folder and we recreated the MNIST_M.py file into a USPS.py file. Imported the filed like they import it for MNIST. Somehow when we run training, the architecture isn't able to find the USPS file. Google's Original Model: Google's Model Command being run: bazel run domain_daptation/pixel_domain_adaptation:pixeldatrain -- --dataset_dir $DSN_DATA_DIR --source_dataset mnist --target_dataset usps Location of usps.py file: /home/.../models/domain_adaptation/datasets:usps Original Stack Trace: INFO: Analysed target //domain_adaptation/pixel_domain_adaptation:pixelda_train (2 packages loaded). INFO: Found 1 target... Target //domain_adaptation/pixel_domain_adaptation:pixelda_train up-to-date: bazel-bin/domain_adaptation/pixel_domain_adaptation/pixelda_train INFO: Elapsed time: 0.575s, Critical Path: 0.12s INFO: Build completed successfully, 1 total action INFO: Running command line: bazel-bin/domain_adaptation/pixel_domain_adaptation/pixelda_train --dataset_dir /home/gabe/models/domain_adaptation/datasets --source_dataset mnist --target_dataset usps Traceback (most recent call last): File "/home/.../.cache/bazel/_bazel_root/b15fa6ac5bc49187f8190f3d0425c8db/execroot/__main__/bazel-out/k8-fastbuild/bin/domain_adaptation/pixel_domain_adaptation/pixelda_train.runfiles/__main__/domain_adaptation/pixel_domain_adaptation/pixelda_train.py", line 24, in &lt;module&gt; from domain_adaptation.datasets import dataset_factory File "/home/.../.cache/bazel/_bazel_root/b15fa6ac5bc49187f8190f3d0425c8db/execroot/__main__/bazel-out/k8-fastbuild/bin/domain_adaptation/pixel_domain_adaptation/pixelda_train.runfiles/__main__/domain_adaptation/datasets/dataset_factory.py", line 26, in &lt;module&gt; from domain_adaptation.datasets import usps ImportError: cannot import name usps ERROR: Non-zero return code '1' from command: Pr…
type: Question
has title: Can't Import Python File - MNIST TO USPS - Google Pixel DA

http://stackoverflow.com/q/48969973
has answer: http://stackoverflow.com/a/48987137
downvote count: 0
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48972040
upvote count: 1
has body: I am looking for a way how to transfer shaders from one character to another character if they are totally similar. So I am looking for the way how to query shader from one face of the mesh to another completely similar one. I am already stuck on the moment how to query shader. Anybody can give some tips? Thanks
tagged with: maya
tagged with: mel
has title: Assign shaders from one mesh to another in Maya via Python
favorite count: 0
tagged with: shader
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49118347
downvote count: 0
has answer: http://stackoverflow.com/a/49325567
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
tagged with: bioinformatics
tagged with: python
tagged with: genomicranges
tagged with: pyranges
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/55676252
type: UnansweredQuestion
has title: pythonic equivalent to reduce() in R GRanges - how to collapse ranged data?
type: Question
has body: In R (albeit longwinded): Here is a test data.frame df &lt;- data.frame( "CHR" = c(1,1,1,2,2), "START" = c(100, 200, 300, 100, 400), "STOP" = c(150,350,400,500,450) ) First I make GRanges object: gr &lt;- GenomicRanges::GRanges( seqnames = df$CHR, ranges = IRanges(start = df$START, end = df$STOP) ) Then I reduce the intervals to collapse into new granges object: reduced &lt;- reduce(gr) Now append a new column to original dataframe which confirms which rows belong to the same contiguous 'chunk'. subjectHits(findOverlaps(gr, reduced)) Output: &gt; df CHR START STOP locus 1 1 100 150 1 2 1 200 350 2 3 1 300 400 2 4 2 100 500 3 5 2 400 450 3 How do I do this in Python? I am aware of pybedtools, but to my knowledge, this would require me to save my data.frame to disk. Any help appreciated.
answer count: 2

http://stackoverflow.com/q/49104670
type: Question
possible better answer: http://stackoverflow.com/a/49104925
has answer: http://stackoverflow.com/a/49104818
has comment: http://stackoverflow.com/comment/85214804
answer count: 3
upvote count: 1
downvote count: 0
has body: PROBLEM I have a list that I got from pulling data from a MySQL database. Using SQLAlchemy selectAA1 = conn.execute(' SELECT YIELD_EXPECTED_QTY as x, YIELD_ACTUAL_QTY as y FROM obj2mart') WHAT I'VE GOT SO FAR keys = ["x", "y"] values = [] for row in selectAA1: values.append(row[0]) values.append(row[1]) print (values) The result of this code is: [3, 198, 3, 198, 3, 198, 3, 198, 3, 198, ...] What I want is to have a list of dictionaries that maps these keys to each of the list, namely 'x' and 'y' The result should be a list of dictionaries: [{ x: 3, y: 198 }, { x: 3, y: 198}, { x: 3, y: 198} , ...] WHAT I'VE TRIED dictionary = {} dictionary = dict(zip(keys, values)) print (dictionary) However, this code returns only one: { 'x': 3, 'y': 198 } I am a newbie in python. Can someone help me? NOTE: I am using Python 3.7
tagged with: flask-sqlalchemy
favorite count: 0
has answer: http://stackoverflow.com/a/49104925
has comment: http://stackoverflow.com/comment/85214380
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has title: Appending dictionary to a list in Python 3.7
has answer: http://stackoverflow.com/a/49104779
score: 1
accepted answer: http://stackoverflow.com/a/49104818

http://stackoverflow.com/comment/85157991
type: Comment
type: QuestionComment
has text: Where have you even defined the `some_name` attribute in your class definition?? What happens when you try `print(a.prop_name)`?
score: 0
comment on: http://stackoverflow.com/q/49076067

http://stackoverflow.com/a/49008052
accepted answer of: http://stackoverflow.com/q/49005924
answers question: http://stackoverflow.com/q/49005924
type: AcceptedAnswer
downvote count: 0
score: 6
type: Answer
upvote count: 6
has body: You can use multiprocessing for the job, so each process run each function def run_schedule(): while True: schedule.run_pending() time.sleep(1) def run_crawler_schedule(): channel_crawler(priority=1) schedule.every(PRIORITY[1]["interval"]).minutes.do(channel_crawler, priority=1) run_schedule(schedule) def run_fix(): schedule.every().day.at("17:30").do(distance_fixer) run_schedule() def run_job() p = Process(target=run_crawler_schedule) c = Process(target=run_fix) p.start() c.start() p.join() c.join() if __name__ == "__main__": run_job()

http://stackoverflow.com/comment/84959018
type: QuestionComment
comment on: http://stackoverflow.com/q/48977032
has text: depends on the actual contents of `ride.in` but it seems like ",-86," occurs more than once in `output`
score: 0
type: Comment

http://stackoverflow.com/a/49106231
has body: for your input format lines = [] while True: line = list(map(int,input().split())) if line: lines.append(line) else: break print(lines) input: 3 11 1 2 -1 4 0 5 -3 8 7 0 10 10 1 2 -1 4 0 5 -3 8 7 10 5 1 2 3 4 5 output [[3], [11], [1, 2, -1, 4, 0, 5, -3, 8, 7, 0, 10], [10], [1, 2, -1, 4, 0, 5, -3, 8, 7, 10], [5], [1, 2, 3, 4, 5]] For Single Line input inputnumbers=list(map(int,input("Input:").split())) print("Output",inputnumbers) print("input[3]",inputnumbers[3]) Output Input: 1 2 3 4 5 Output [1, 2, 3, 4, 5] input[3] 4 For multiLine lines = [] while True: line = input() if line: lines.append(line) else: break print(lines) Input: 1 2 3 4 5 asdf asdf asdf 1234 Output: ['1 2 3 4 5', 'asdf asdf asdf', '1234']
accepted answer of: http://stackoverflow.com/q/49106182
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85217383
has comment: http://stackoverflow.com/comment/85220248
has comment: http://stackoverflow.com/comment/85217648
score: 0
has comment: http://stackoverflow.com/comment/85217343
type: Answer
answers question: http://stackoverflow.com/q/49106182

http://stackoverflow.com/comment/85019288
type: QuestionComment
has text: Are you sure you have cpu version? Because error is "Library not loaded: @rpath/libcublas.8.0.dylib" libcublas is part of cuda. .
score: 1
comment on: http://stackoverflow.com/q/49007149
type: Comment

http://stackoverflow.com/a/49121818
downvote count: 0
has comment: http://stackoverflow.com/comment/90161886
has body: This is almost always a missing path in your LD_LIBRARY_PATH. Find libcublas.so.9.0 on your system (start looking under /usr/local). If you don't find it, then install the CUDA 9.0 Toolkit (note that with TF 1.5 you want 9.0 and not 9.1, a common gotcha, at least common in-so-far as I made that mistake myself). https://developer.nvidia.com/cuda-90-download-archive If you have it, then update your LD_LIBRARY_PATH to point to the appropriate lib directory. If you've done either of those and are now getting a similar looking error for a cudnn related library, then repeat that process for the CUDNN library. https://developer.nvidia.com/cudnn I think the latest version works. Tensorflow depends on both CUDA toolkit and the CuDNN library extension. Note that you can install all of this in userspace too (sudo is typical, but not required).
score: 4
accepted answer of: http://stackoverflow.com/q/49115391
has comment: http://stackoverflow.com/comment/90162588
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49115391
type: Answer
upvote count: 4

http://stackoverflow.com/comment/85090261
comment on: http://stackoverflow.com/q/49041669
type: Comment
type: QuestionComment
has text: @JerinPeterGeorge lft, rgt values get generated automatically. See Organization is the child class of `NS_Node` class https://github.com/django-treebeard/django-treebeard/blob/3c87f481c19b096db0d0b2cd646fa6e95f66eab9/treebeard/ns_tree.py#L114
score: 0

http://stackoverflow.com/q/49062045
tagged with: macos
has comment: http://stackoverflow.com/comment/85145073
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49065449
upvote count: 5
has answer: http://stackoverflow.com/a/49065449
tagged with: python
has title: High Sierra + Python + Postgresql error: Illegal instruction: 4
tagged with: psycopg2
linked to: http://stackoverflow.com/q/48710094
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49090013
has body: I can connect to Postgres via the command line no problem, however if I try to connect via Python using the psycopg2 module I get the error below. Interestingly I have just tried connecting with PSeqal.app and it crashes with the same error. Environment: MacOS: 10.13.3 Xcode 9.2 Python: 3.6.4 Connection module: psycopg2 Postgresql: 10.3 Script: Here is my simple connection script which is trying to connect via Python to Postgresql: def connect(self, params): """ Connect to the PostgreSQL database server """ conn = None try: # connect to the PostgreSQL server logging.info('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor self.cursor = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() logging.warning('Database connection closed.') Error: Script output: $ python3 testdb.py Illegal instruction: 4 Apple error (partial): Process: Python [79534] Path: /usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.6.4 (3.6.4) Code Type: X86-64 (Native) Parent Process: bash [657] Responsible: Python [79534] User ID: 501 Date/Time: 2018-03-02 15:30:27.642 +1300 OS Version: Mac OS X 10.13.3 (17D102) Report Version: 12 Anonymous UUID: xx Time Awake Since Boot: 21000 seconds System Integrity Protection: disabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Illegal instruction: 4 Termination Reason: Namespace SIGNAL, Code 0x4 Terminating Process: exc handler [0] Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libpq.5.10.dylib 0x00000001118e8d27 initPQExpBuffer + 32 1 libpq.5.10.dylib 0x00000001118dba93 PQconninfoParse + 43 2 _psycopg.cpython-36m-darwin.so 0x0000000111897cf1 psyco_parse_dsn + 113 3 org.pyth…
accepted answer: http://stackoverflow.com/a/49090013
type: Question
answer count: 2
score: 5
linked to: http://stackoverflow.com/q/14261820
tagged with: postgresql
linked to: http://stackoverflow.com/q/14268887

http://stackoverflow.com/q/49103029
tagged with: fft
score: 0
tagged with: python
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85211486
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has title: Test frequency off by a factor of 2 with numpy fft
has comment: http://stackoverflow.com/comment/85237501
tagged with: signal-processing
type: Question
tagged with: numpy
has body: I am messing around with signal processing where I'm just reading a test frequency of 440 Hz into the microphone on my computer and trying to recover it from the raw audio data with numpy's fft. It seems I'm off by a factor of 2 though - I keep getting ~220 Hz instead of 440. Code RATE = 44100 CHUNK = 1024 N = 2048 RECORD_SECONDS = 1 p = pyaudio.PyAudio() player = p.open(format=pyaudio.paInt16, channels=2, rate=RATE, output=True, output_device_index=1, frames_per_buffer=CHUNK) stream = p.open(format=pyaudio.paInt16, channels=2, rate=RATE, input=True, input_device_index=0, frames_per_buffer=CHUNK) frames = [] max_frames = [] for i in range(int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) data = np.fromstring(data,dtype=np.int16) spec_y = np.fft.fft(data[:]) spec_y = [np.sqrt(j.real**2 + j.imag**2) for j in spec_y] spec_x = np.fft.fftfreq(N, d = 1.0 / RATE) frames.append((spec_x, spec_y)) spec_index = np.where(spec_y==np.max(spec_y))[0] max_frames.append(np.abs(spec_x[spec_index])) player.write(data, CHUNK) # frames = ''.join(frames) stream.stop_stream() stream.close() p.terminate() #Spectrum plt.clf() plt.subplot(312) plt.plot(frames[-1][0], frames[-1][1], marker= 'o', linestyle='-') plt.axis([-RATE/2, RATE / 2, 0, np.max(frames[-1][1])]) plt.xlabel("frequency [Hz]") plt.ylabel("amplitude spectrum") plt.show()

http://stackoverflow.com/comment/85285070
score: 0
type: Comment
type: QuestionComment
has text: In the second block of code you can find: validation_data_dir = '/mnt/data/train' # redefined validation set to test accuracy of validation loss/accuracy calculations
comment on: http://stackoverflow.com/q/49116174

http://stackoverflow.com/comment/84977053
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48985994
has text: can you give your mail id so that i can send you the file

http://stackoverflow.com/a/49094178
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49094098
score: 2
answers question: http://stackoverflow.com/q/49094098
has body: Supposing that your number variable is a list of 5 elements (five cards) you can probably try something like: from collections import Counter numbers = [1,4,5,5,6] c = Counter(numbers) This leverages the awesome Counter class. :) Once you have the counter you can check for what is the number of most common occurencies by doing: # 0 is to get the most common, 1 is to get the number max_occurrencies = c.most_common()[0][1] # this will result in max_occurrencies=2 (two fives) If you also want to know which one is the card that is so frequent you can get both information in one go using tuple unpacking: card, max_occurrencies = c.most_common()[0] # this will result in card=5, max_occurrencies=2 (two fives)

http://stackoverflow.com/comment/84944831
comment on: http://stackoverflow.com/a/48966810
score: 0
type: AnswerComment
type: Comment
has text: yeah that worked as water flow, thank you, however the code i'm trying to run is a little more complicated when i try to do the same code of yours it always gives me indentation error at i+=1

http://stackoverflow.com/a/49008589
has comment: http://stackoverflow.com/comment/129051079
type: AcceptedAnswer
downvote count: 0
score: 8
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/49008508
answers question: http://stackoverflow.com/q/49008508
has body: Simpliest is use apply with in: df1 = df[df.lists.apply(lambda x: 'a' in x)] But if want check a create DataFrame, but it is a bit complicated: df1 = df[pd.DataFrame(df.lists.values.tolist()).eq('a').any(axis=1)] Another solution is use str.join with str.contains: df1 = df[df.lists.str.join(',').str.contains('a')] print (df1) lists 0 [a, c] 1 [a, b, d]

http://stackoverflow.com/a/48992561
has body: The trouble is that there are pathological corner cases ... for example, a huge, huge graph with zero cycles, such that it requires too much time before even the first iteration of nx.simple_cycles(G) can complete. As a result, there won't be a way to do it from outside the generator unless you place the execution into another context that you are able to terminate, like a separate Process from multiprocessing, or running the coroutine with asyncio. Then for each cycle that is asynchronously obtained (either from the process or thread), you can check the length condition and a condition on the overall amount of elapsed time, and choose to terminate the other process / thread if you exceed the time limit. On the other hand, if you don't care about this type of corner case and you're reasonably sure that the values yielded by nx.simple_cycles(G) will return in reasonable amounts of time, then you could wrap that generator to make your own time-limited generator: import time def time_limited_cycles(G, time_limit=100.0): elapsed, cycle_generator = 0.0, nx.simple_cycles(G) while elapsed &lt;= time_limit: start_time = time.time() try: # crucial assumption here, that calling next on # the original generator never takes too long. cycle = next(cycle_generator) except StopIteration: break yield cycle elapsed += time.time() - start_time # move elapsed above the yield line if you are looking # to limit the internal runtime of the generator, rather # than overall time spent processing cycles. With the above, you can replace your original usage of nx.simple_cycles with a call to time_limited_cycles instead (with your desired time limit), and the rest of your code will work the same, because time_limited_cycles yields the same cycle results that nx.simple_cycles would yield, up to the point that it stops.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48992398
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48992398
downvote count: 0
score: 1

http://stackoverflow.com/comment/85945339
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49062650
type: Comment
has text: Output Generated as below:

http://stackoverflow.com/q/49036715
has comment: http://stackoverflow.com/comment/85078801
has answer: http://stackoverflow.com/a/49037210
type: Question
tagged with: numpy
score: 0
answer count: 1
has body: I'm using np.concatenate to concatenate a non-sequential column with some sequential columns in a large dataset, and I realized my method would look rather cumbersome if I wanted to do this with multiple non-sequential columns. Would I just chain concatenate all of the individual columns? I'm looking for a broad answer, not a solution for say columns 2, 5 and 7. import numpy as np rand_data = np.random.rand(156,26) new_array = np.concatenate((rand_data[:,22].reshape(-1,1),rand_data[:, 24:27]), axis = 1)
type: UnansweredQuestion
has title: Efficient method of concatenating non-sequential columns in 2d numpy array
has comment: http://stackoverflow.com/comment/85079346
tagged with: python

http://stackoverflow.com/q/49034910
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85074759
tagged with: python
tagged with: pixel
has answer: http://stackoverflow.com/a/49039538
tagged with: matplotlib
has body: I am trying to display several pictures on my Jupyter notebook. However, the pixel is really rough like below. The pixel of original picture is clear. How should I improve this issue ? This is a certain point of process to have a classification whether the picture is dog or cat. I have a many pictures of dogs and cat in the folder located on same directory and just took them from there. The picture is I just tried to show on the Jupyter notebook with using matplotlib. Thank you in advance.
has answer: http://stackoverflow.com/a/49037151
type: Question
score: 0
answer count: 2
has title: Concatenated images are badly degraded

http://stackoverflow.com/a/49099993
has comment: http://stackoverflow.com/comment/91936763
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49090514
answers question: http://stackoverflow.com/q/49090514
downvote count: 0
has body: Found out what was wrong. I had to pip install: pip install pyflakes pip install pycodestyle
score: 1

http://stackoverflow.com/a/48981642
type: AcceptedAnswer
has body: Alternatively you can head to nltk corpora page and download whatever you need. Just make sure you download and unpack (if needed) it to one of the folders where nltk looks for. Or you could add the path like so import nltk.data nltk.data.path.append(custom_path)
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48974864
answers question: http://stackoverflow.com/q/48974864
upvote count: 1

http://stackoverflow.com/q/49030127
tagged with: azure-cli
has title: Get a list of Azure OS Disks attached to VMs in specific subscription
type: Question
has answer: http://stackoverflow.com/a/49041162
accepted answer: http://stackoverflow.com/a/49041162
tagged with: disk
tagged with: azure
answer count: 1
downvote count: 0
favorite count: 0
has body: I am fetching a list of OS Disks attached to VMs in Azure in all resource groups of specific subscription. I found a AZ utility to fetch the list in json format. Using below sequence I am able to get the list in json format, Is there any similar way to get this achieved using any python module ? az login az account set --subscription &lt;subscription&gt; az disk list
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/85163060
comment on: http://stackoverflow.com/q/49078479
type: Comment
has text: You could just add one day to the second data frame, as the last day in a month is always followed by a first day in a month. However, October has 31 days, so 2009-10-30 is not on the last day of the month.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49117991
downvote count: 0
has answer: http://stackoverflow.com/a/49118254
accepted answer: http://stackoverflow.com/a/49118254
has title: How to downgrade python version to Python 2.7.13 (default, Nov 7 2017, 00:42:48)?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85242105
favorite count: 0
has comment: http://stackoverflow.com/comment/85242639
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85242305
has comment: http://stackoverflow.com/comment/85241372
tagged with: ubuntu-17.10
score: 2
type: AnsweredQuestion
has body: I tried to downgrade my python version from 3.0 to 2.7.13 by following this instruction Finally, I ended up with Python 2.7.13 (default, Mar 6 2018, 01:35:39), I realized that this version could not compatible with my currently project, that some modules which was used to working are depreciated ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead. from flask.ext.sqlalchemy import SQLAlchemy The version that could be working is Python 2.7.13 (default, Nov 7 2017, 00:42:48) as checking on other machine working on the same project. I don't want to change some modules to compatible with python version, instead I want to downgrade my python version to the previous working one Python 2.7.13 (default, Nov 7 2017, 00:42:48). Any clues how can I downgrade it to the working python version? I'm Ubuntu 17.10. Thanks.

closures
tags question: http://stackoverflow.com/q/49046554
tags question: http://stackoverflow.com/q/49085106
tag name: closures
type: Tag

http://stackoverflow.com/comment/85042439
score: 0
type: QuestionComment
type: Comment
has text: Breaking them up into single key value pairs gives me this error (TypeError: Cannot compare types 'ndarray(dtype=object)' and 'str'). It's only with the timedelta[ns] string. Looks like there might be something wrong with the [] in the string
comment on: http://stackoverflow.com/q/49018295

http://stackoverflow.com/comment/85193541
type: QuestionComment
has text: You could test if this is going a little faster: `sed -n '/^pattern1$/,/^pattern2$/p`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49094035

http://stackoverflow.com/q/49115569
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49115701
tagged with: python
tagged with: mysql
upvote count: 1
has body: I have an SQL query which is giving an error: cur.execute("INSERT INTO `DB` (`ban`, `dntr`, `usrnm`, `id`, `dis`) VALUES (1,0,?,?,?)",(param1,param2,param3,)) I don't want to use %s in query because it is prone to SQL injection and I am taking input from users.
answer count: 1
type: UnansweredQuestion
has title: Error "not all arguments converted during string formatting" while inserting in Database MySQL

http://stackoverflow.com/q/49023750
type: AnsweredQuestion
tagged with: dynamic
tagged with: widget
score: 1
accepted answer: http://stackoverflow.com/a/49026200
upvote count: 1
type: Question
has title: How to Change BG Color of Dynamically Created Widget with On_Press and Save with Pickle? (Python with Kivy)
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49026200
favorite count: 0
has body: Goal: Change background color of dynamically created widget with on-press. Save this state with pickle such that when I open the program back up, the new color change is preserved Note: You'll see in my code that I haven't made an attempt on saving the button bg color state to a file yet, as I'm still trying to get the on-press event to function. I get the following error: File "C:/Users/phili/scrollablelabelexample.py", line 45, in create_button button_share.bind(on_press = self.update_buttons_departoverride(self)) TypeError: update_buttons_departoverride() takes 1 positional argument but 2 were given Python code: from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.uix.textinput import TextInput from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.widget import Widget from kivy.uix.scrollview import ScrollView from kivy.properties import StringProperty, ObjectProperty, NumericProperty from kivy.clock import Clock import pandas as pd from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.label import Label class AnotherScreen(Screen): pass class BackHomeWidget(Widget): pass class Sequence(Screen): pass class ScreenManagement(ScreenManager): pass class MainScreen(Screen): pass class CleanScreen(BoxLayout): def __init__(self, **kwargs): super(CleanScreen, self).__init__(**kwargs) self.orientation = "vertical" Clock.schedule_once(lambda *args:self.create_button(self.ids.box_share)) def create_button(self, box_share): top_button_share = 1.1 color = [.48,.72,.23,1] for i in range(len(parts)): top_button_share -= .4 button_share = Button(background_normal = '', background_color = color, id = "part"+str(i+1),pos_hint={"x": 0, "top": top_button_share}, size_hint_y=None, height=60, text=str(i)) button_share.bind(on_press = self.update_buttons_departoverride(self)) box_share.add_widget(button_share) def update_buttons_de…
tagged with: python
tagged with: kivy

http://stackoverflow.com/a/49025886
has comment: http://stackoverflow.com/comment/85057303
has body: I think you can do so : c = pd.DataFrame(abs((a.values-b.values)/(a.values+b.values)))
upvote count: 4
has comment: http://stackoverflow.com/comment/85057901
has comment: http://stackoverflow.com/comment/85058199
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/49025790
type: Answer

http://stackoverflow.com/a/49028816
upvote count: 0
has body: How about: username = input("Enter your name\n") This works, because I'm using the newline character ("\n").
score: -1
answers question: http://stackoverflow.com/q/49028775
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49028775
type: Answer

http://stackoverflow.com/q/49097043
accepted answer: http://stackoverflow.com/a/49097186
tagged with: matplotlib
tagged with: figure
score: -1
has body: Ive got a loop in which i gather measurement data which needs to be drawn in about 12 subplots (here only 4 subplots) in 1 figure, which should update the subplots during every loop-cycle. However, my code just creates an additional figure-window every loop-cycle instead of updating the single figure-window. Also the measurement data consists of large float-values (e.g. 989.9871234) which crowds my major y-tick labels, so the y-axis are unreadable and i havent found a working solution to limit the number of y-axis-labels. I used the example from Code example as the basis for my code. Heres my code (unnecessary measurement data gathering omitted): fig = plt.figure(figsize=(6, 4)) sub1 = fig.add_subplot(221) sub1.plot(secondspassed_array, resistance1_array) sub2 = fig.add_subplot(222) sub2.plot(secondspassed_array, resistance2_array) sub3 = fig.add_subplot(223) sub3.plot(secondspassed_array, resistance3_array) sub4 = fig.add_subplot(224) sub4.plot(secondspassed_array, resistance4_array) plt.plot(secondspassed_array, resistance4_array) plt.tight_layout() plt.ion() plt.pause(0.05)
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85199626
has answer: http://stackoverflow.com/a/49097186
tagged with: python
has title: Continously updating a single plt.figure instead of creating multiple figure-windows
has comment: http://stackoverflow.com/comment/85199650
downvote count: 1
type: Question
type: AnsweredQuestion

pyopengl
tags question: http://stackoverflow.com/q/49069960
tag name: pyopengl
tags question: http://stackoverflow.com/q/49018486
tags question: http://stackoverflow.com/q/48983828
type: Tag
tags question: http://stackoverflow.com/q/49078120

http://stackoverflow.com/comment/85041559
has text: @BryanOakley Thanks for the help, I think it's clearer now. Initially, I thought it would resize to its given size if the widgets inside were to be destroyed but that seems wrong. One should unset the propagation exactly after the widget is in the size they wish.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49017573

subprocess
tags question: http://stackoverflow.com/q/48966743
tag name: subprocess
tags question: http://stackoverflow.com/q/49015162
tags question: http://stackoverflow.com/q/49058794
tags question: http://stackoverflow.com/q/49018413
tags question: http://stackoverflow.com/q/49013020
tags question: http://stackoverflow.com/q/49071772
tags question: http://stackoverflow.com/q/48991249
tags question: http://stackoverflow.com/q/49037092
tags question: http://stackoverflow.com/q/49018226
tags question: http://stackoverflow.com/q/49100908
tags question: http://stackoverflow.com/q/48995393
tags question: http://stackoverflow.com/q/49028807
tags question: http://stackoverflow.com/q/49076404
tags question: http://stackoverflow.com/q/49031841
tags question: http://stackoverflow.com/q/49013269
tags question: http://stackoverflow.com/q/49112447
tags question: http://stackoverflow.com/q/49098469
type: Tag
tags question: http://stackoverflow.com/q/49110935
tags question: http://stackoverflow.com/q/49089415
tags question: http://stackoverflow.com/q/49040017
tags question: http://stackoverflow.com/q/49010813
tags question: http://stackoverflow.com/q/49068223
tags question: http://stackoverflow.com/q/49005670
tags question: http://stackoverflow.com/q/48992036
tags question: http://stackoverflow.com/q/48998501
tags question: http://stackoverflow.com/q/49095889
tags question: http://stackoverflow.com/q/48964477
tags question: http://stackoverflow.com/q/49031125
tags question: http://stackoverflow.com/q/48971102
tags question: http://stackoverflow.com/q/49109500
tags question: http://stackoverflow.com/q/48967092

http://stackoverflow.com/q/49101245
has answer: http://stackoverflow.com/a/49101288
possible better answer: http://stackoverflow.com/a/49101282
downvote count: 3
has answer: http://stackoverflow.com/a/49101282
upvote count: 1
accepted answer: http://stackoverflow.com/a/49101360
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85207809
score: -2
has comment: http://stackoverflow.com/comment/85208358
type: Question
has answer: http://stackoverflow.com/a/49101286
has comment: http://stackoverflow.com/comment/85207826
has title: map list of integers to dict keys in python
has comment: http://stackoverflow.com/comment/85207884
favorite count: 0
has answer: http://stackoverflow.com/a/49101360
answer count: 5
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49101356
has body: The larger problem at view: I am breaking down a circle in 20 sectors to find where coordinates fall to find their value for a darts board game. There are 20 values 1-20 NOT in order. The dart board values fall along a circle: I currently have a list of thetas (ranges of degrees) [(0-18),(18-36),(36-54)...] I am trying to map the list of thetas to each sector of the dart board which corresponds to a different value, NOT in order. The list of dart board values is such: darts_list = [20,1,18,4,13,6,10,15,2,17,3,19,7,16,8,11,14,9,12,5] Any idea how to get: {20: (0-18), 1: (18-36), 18: (36-54)...} So I can map the ranges of the theta to the dict values. Thanks in advance! EDIT: I think there was some confusion on what I was looking for, I didnt want 0 as dict values, so I changed to what I am looking for. Python version: '3.4.5 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:47:47) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]' I believe the most efficient solution is to map the ranges to dart board values as keys. @jpp I am open to a more efficient solution instead of creating an XY problem.

http://stackoverflow.com/a/49027315
answers question: http://stackoverflow.com/q/49026796
type: Answer
upvote count: 1
downvote count: 1
has body: At very simple i make this program for you as per your requirement that user must enter 10 numbers and program finds either it is prime or not. try this: for i in range(0, 10): num = int(input('Enter Number:')) if num > 1: # check for factors for i in range(2, num): if (num % i) == 0: print(num, "is not a prime number") print(i, "times", num // i, "is", num) break else: print(num, "is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num, "is not a prime number") Note: In a for loop a take input from user 10 times if you want to take inputs in the starting then you can also to that and you can then run a loop o that list. Choice is yours!
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49026796

http://stackoverflow.com/comment/85122309
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49058313
has text: @DeliriousLettuce Oh no, I'm not going to try implement it myself, you can have that :) But I'm going to check whether there is a clean solution to the problem already (since, for now you can't post anything with this being tagged as a dupe). I think that tag might need to be removed.

http://stackoverflow.com/q/49079133
upvote count: 3
type: UnansweredQuestion
has body: Question I am trying to run a Python DEAP genetic algorithm in a Jupyter notebook with pySpark for parallelization. With some research I understand that the essence is to register a spark based map function with toolbox to allow spark to do the fitness evaluations (code below). My question is, how do I expose creator functions for the SparkContext? Does Spark require any special treatment when compared to SCOOP and multiprocessing? Code The essence of the code I am running is as follows with SparContext (sc) already created: import deap as ea from deap import creator, base, tools, algorithms ea.creator.create("FitnessMin", ea.base.Fitness, weights=(-1.0,)) ea.creator.create("Individual", list, fitness=ea.creator.FitnessMin) toolbox = ea.base.Toolbox() def sparkMap(algorithm, *population): return sc.parallelize(population).map(algorithm) toolbox.register("map", sparkMap) #Set DEAP to run on a machine cluster using Spark hallOfFame = tools.HallOfFame(2) population = toolbox.population(n=POPULATION_SIZE) tools.initIterate(list, partial(sample, range(MAX_NUMBER_OF_CLUSTERS), MAX_NUMBER_OF_CLUSTERS)) gen = 0; while gen &lt; NUMBER_OF_GENERATOINS: # Update population population = toolbox.select(population, k=len(population)) population = [toolbox.clone(ind) for ind in population] population = ea.algorithms.varAnd(population, toolbox, cxpb=cxpb, mutpb=mutpb, ) offspring = [individual for individual in population if not individual.fitness.valid] fits = toolbox.map(toolbox.evaluate, offspring).collect() for fit, ind in zip(fits, offspring): ind.fitness.values = fit #Update hall of fame to ensure we always know the best found solution hallOfFame.update(offspring) gen += 1 best = hallOfFame[0] However, this results in an error stating that: AttributeError: Can't get attribute 'Individual' on module 'deap.creator' from '/gpfs/fs01/user/s093-7b1ca9741d3405-545a66b5b986/.local/lib/python3.5/site-packages/deap/creator.py' My understanding is that with other parallelization setups …
type: Question
score: 3
tagged with: deap
tagged with: pyspark
tagged with: apache-spark
has title: Python DEAP running on pySpark is unable to call creator function
answer count: 1
has answer: http://stackoverflow.com/a/57882508
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/a/62007269
has body: Please check the file type that saved it as is the csv format. file_type = pd.read_csv(&quot;c:\\file_name\.csv') It should work.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49087317

http://stackoverflow.com/q/48981687
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85007266
has comment: http://stackoverflow.com/comment/85002271
score: 3
has comment: http://stackoverflow.com/comment/85006192
has comment: http://stackoverflow.com/comment/85002116
has comment: http://stackoverflow.com/comment/84968536
has answer: http://stackoverflow.com/a/49001113
has comment: http://stackoverflow.com/comment/85007333
has comment: http://stackoverflow.com/comment/85007204
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84968502
favorite count: 0
has comment: http://stackoverflow.com/comment/84968683
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84993102
has comment: http://stackoverflow.com/comment/85002251
has body: The following is a simple linear regression/ML code that I have modified. For all initial weight and bias (i.e. weight = np.array([0.03, 0.04, 0.02]), bias = 0.01), the training will blow up (It just won't converge). Wonder if there is a bug in the code or how to choose good initial values (weight and bias) so it will converge. #Adopted from http://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html import numpy as np from numpy import genfromtxt def predict(X, weight, bias): return np.dot(X, weight) + bias def cost_function(X, Y, weight, bias): companies = X.shape[0] return np.sum((predict(X, weight, bias) - Y) **2) / companies def update_weights(X, Y, weight, bias, learning_rate): companies = X.shape[0] dW = 2 * np.dot(X.T, predict(X, weight, bias) - Y) db = 2 * np.sum(predict(X, weight, bias) - Y) """ for i in range(companies): # Calculate partial derivatives # -2x(y - (mx + b)) dw += -2*X[i] * (sales[i] - (weight*X[i] + bias)) # -2(y - (mx + b)) db += -2*(sales[i] - (weight*X[i] + bias)) """ #print(dW, db) # We subtract because the derivatives point in direction of steepest ascent #weight -= (dW / companies) * learning_rate #bias -= (db / companies) * learning_rate return weight - (dW / companies) * learning_rate, bias - (db / companies) * learning_rate def train(X, Y, weight, bias, learning_rate, iters): cost_history = [] for i in range(iters): weight,bias = update_weights(X, Y, weight, bias, learning_rate) #Calculate cost for auditing purposes cost = cost_function(X, Y, weight, bias) cost_history.append(cost) # Log Progress if i % 100 == 0: print ("iter: "+str(i) + " cost: "+str(cost) + "\n") return weight, bias, cost_history #the Advertising.csv is from http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv if __name__ == "__main__": my_data = genfromtxt('Advertising.csv', delimiter=',') X = my_data[1:, 1:4:1] Y = my_data[1:, 4]; #the sales a,b, _ = train(X, Y, np.array([0.03, 0.04, 0.02]), 0.01, 0.001, 1000) The problem is, whatever value I use as init…
tagged with: python
has title: Can't make a multi-variable linear regression converge
has comment: http://stackoverflow.com/comment/85002286
upvote count: 3
tagged with: machine-learning

http://stackoverflow.com/a/49096337
downvote count: 0
has comment: http://stackoverflow.com/comment/85199250
score: 1
has body: I think your problem is that although you have parsed the t column it is not of type date-time. Try the following: # Set t to date-time and then to index df['t'] = pd.to_datetime(df['t']) df.set_index('t', inplace=True) Reading you comment and the answer you have added someone may conclude that this kind of problem can only be solved by specifying a parser in pd.read_csv(). So here is proof that my solution works in principle. Looking at what you have posted as a question, the other problem with you code is the way you have specified the plot command. Once t has become an index, you only need to select columns other than t for the plot command. import pandas as pd import matplotlib.pyplot as plt # Read data from file df = pd.read_csv('C:\\datetime.csv', parse_dates=['Date']) # Convert Date to date-time and set as index df['Date'] = pd.to_datetime(df['Date']) df.set_index('Date', inplace=True) df.plot(marker='D') plt.xlabel('Date') plt.ylabel('Number of Visitors') plt.show() df Out[37]: Date Adults Children Seniors 0 2018-01-05 309 240 296 1 2018-01-06 261 296 308 2 2018-01-07 273 249 338 3 2018-01-08 311 250 244 4 2018-01-08 272 234 307 df Out[39]: Adults Children Seniors Date 2018-01-05 309 240 296 2018-01-06 261 296 308 2018-01-07 273 249 338 2018-01-08 311 250 244 2018-01-08 272 234 307
answers question: http://stackoverflow.com/q/49095323
upvote count: 1
type: Answer

http://stackoverflow.com/a/49003116
has body: As an addendum to @PaulPanzer's answer, I have attempted to get the same result with the minimum number of temp arrays. This answer is here for fun, and does not provide any benefits to outweigh the clarity and legibility of PaulPanzer's answer. Instead of ndarray.any, you can check for zeros directly with ndarray.all and flip the 2D array in-place instead of the 3D, avoiding a temp array. You can use the property that any number added (or subtracted, multiplied, divided, etc) to nan results in nan. Instead of using ndarray.any, you can use ufunc.reduce to make your 2D matrix, which will save you another 3D boolean array. You can't use the fact that np.isnan is a ufunc directly, because it is a unary function which does not support the reduce operation. # Check for zeros mask = y.all(axis=2) # Straight to 2D, no temp arrays mask = np.logical_not(mask, out=mask) # In place negation, no temp arrays # Check for nans nans = np.add.reduce(y, axis=2) # 2D temp array, not 3D mask |= np.isnan(nans) # Another temp array, also 2D I chose to use np.add because it is not likely to run into problems that cause false nans to appear (unlike say np.divide). Any overflows will become +/-inf, which will not trigger the isnan check.
downvote count: 0
answers question: http://stackoverflow.com/q/49002272
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/q/48985477
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48985740
type: AnsweredQuestion
tagged with: google-cloud-datastore
tagged with: app-engine-ndb
has title: Cannot retrieve entity with generated id in Datastore
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48985740
type: Question
tagged with: python
has body: I'm using the Google Cloud Datastore in a very simple way, and I try to retrieve an entity by its id. I've read this (it's in Java but seems to follow the same logic) Def of my entity is here: class Logs(ndb.Model): startDate = ndb.DateTimeProperty() endDate = ndb.DateTimeProperty() requestedDate = ndb.DateProperty() taskName = ndb.StringProperty() status = ndb.StringProperty() Then when I insert a new one I do logs = Logs(startDate=datetime.utcnow(), taskName=taskName, requestedDate=requestedDate, status=u'IN_PROGRESS') key = logs.put() id = key.id() # I use this variable later And when I want to retrieve it logs = Logs.get_by_id(id) But it never returns any entity... What's wrong with this ? Thanks for helping
linked to: http://stackoverflow.com/q/22268257

http://stackoverflow.com/comment/85182550
score: 0
has text: Thank you so much! I've fixed it! I will mark this as accepted! But i have one more question. It is really hard to discriminate the color of the object and yellow color on the object. Any suggestions?
type: Comment
comment on: http://stackoverflow.com/a/49088255
type: AnswerComment

http://stackoverflow.com/comment/85035519
type: QuestionComment
comment on: http://stackoverflow.com/q/49014947
has text: @BryanOakley Ya after Novel answered my question I can see how my statement was not accurate.
score: 0
type: Comment

http://stackoverflow.com/a/49106755
accepted answer of: http://stackoverflow.com/q/49106297
has comment: http://stackoverflow.com/comment/85218808
answers question: http://stackoverflow.com/q/49106297
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85218698
score: 0
has body: try this data = input("Enter name age and score:") while data.strip() != '': data = input("Enter name age and score:")
type: Answer

http://stackoverflow.com/q/49101366
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/49101693
has answer: http://stackoverflow.com/a/49101698
favorite count: 0
has comment: http://stackoverflow.com/comment/85208432
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/85208016
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49101698
linked to: http://stackoverflow.com/q/7124778
downvote count: 2
has body: Hello I'm playing around with regular expressions in pythex and i'm having troubles. i'm trying to take the following string "RANDOM 1 ABBBABBBA SDFSBSBS WBWBSBW WBWBWBWB 10 EBEBEBEB EHRHSHSD EBWBBSHSHSB //" and grab all the non-numeral characters between RANDOM and the forwards slashes. How do I do this with regular expressions? Help!
type: Question
has title: regex in python: match any non-digit character between two words
score: -2
has answer: http://stackoverflow.com/a/49101693

http://stackoverflow.com/comment/85226389
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49109613
type: Comment
has text: Thanks! Using django-guardian or other third-party apps is overkill. :)

http://stackoverflow.com/q/48969124
has answer: http://stackoverflow.com/a/48969170
has body: I have a file called views.py, and in it there is this line: from django.shortcuts import render, which is marked as an unused import statement. I've ooked around and found the shortcuts.py file, but for some reason pycharm still marks my import statement as unused. How do I fix this?
tagged with: pycharm
upvote count: 2
type: UnansweredQuestion
downvote count: 3
tagged with: django
tagged with: python
score: -1
has title: unused import statement in pycharm
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48969158
favorite count: 0

http://stackoverflow.com/comment/85183294
has text: edited with expected result
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49088759

http://stackoverflow.com/comment/85047566
type: QuestionComment
has text: To put it in context, I have a `PyQt` tableView where its model has some data. Now, the model's data (type or value) might be changed by the user at any time. I have threads running in the background which use the table's model data from the program start. If a user changes the data, I would rather it be reflected automatically in the other threads and classes without rereading the model.
score: 0
comment on: http://stackoverflow.com/q/49021098
type: Comment

http://stackoverflow.com/comment/85105444
type: AnswerComment
comment on: http://stackoverflow.com/a/49050424
type: Comment
has text: Well that string is what OP sees when he prints result of encrypt in python console. So it's not a meaningful string in any encoding, it is byte array which python prints to console like this.
score: 0

http://stackoverflow.com/comment/84982704
type: QuestionComment
has text: Other than that I would suggest to do `print j` and `print len(vertex)` before line 78, as j seems to be too large. Possibly you need to initialize it with `L-1` and not `L`?
score: 0
comment on: http://stackoverflow.com/q/48988955
type: Comment

http://stackoverflow.com/comment/85183305
type: Comment
has text: Show a [mcve] that demonstrates your problem.
score: 5
comment on: http://stackoverflow.com/q/49088927
type: QuestionComment

http://stackoverflow.com/a/49060152
has comment: http://stackoverflow.com/comment/85125378
has comment: http://stackoverflow.com/comment/85148151
answers question: http://stackoverflow.com/q/49051262
has comment: http://stackoverflow.com/comment/85141394
has body: You can use Unicode to get superscripts and subscripts. For example your text in second button can be text: 'Hellow\u2074', which is Hellow with a superscript 4. Check out unicode HOWTO and superscripts-and-subscripts
score: 0
type: Answer

http://stackoverflow.com/comment/85102317
comment on: http://stackoverflow.com/q/49049114
has text: I want like this https://stackoverflow.com/questions/48769342/how-to-generate-a-list-of-3-digit-numbers/48769540#48769540 but with the numbers that begins with 0 .
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85148515
type: QuestionComment
comment on: http://stackoverflow.com/q/49071423
has text: @Kyrylo Edited. included traceback.
score: 0
type: Comment

http://stackoverflow.com/comment/85291604
has text: Great, It works Thanks a lot
comment on: http://stackoverflow.com/q/49115809
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85220359
has text: @SaiBot you can assume the entries will be unique. "I" and "I am" are treated as two different objects. Good question though. I suppose "I" and "I am" will count as a point towards "i" and "I am".
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49107491

http://stackoverflow.com/comment/90494682
has text: Thanks for your answers! The things is that I don't use any matrix at all. I just typed `1+1` and that's it...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51767163
type: Comment

http://stackoverflow.com/q/49033130
has comment: http://stackoverflow.com/comment/85071074
downvote count: 0
has comment: http://stackoverflow.com/comment/85070973
has body: I want to write a simple text classifier by languages using unique letters, just for experiment. For example, I have alphabet for each language as a dict of sets with the following keys: ['ru', 'uk', 'pl', 'en', 'de', 'be', ...]. For example, unique Polish letters are "ę" and "ś", English doesn't have unique ones. In fact, I should find all letters that don't belong to others languages. I did it like this (simple example): alphabets = {'it': {'a', 'b', 'c', 'd', 'e', 'à', 'ì'}, 'en': {'a', 'b', 'c', 'd', 'e'}, 'pl': {'a', 'b', 'c', 'd', 'e', 'ę', 'ś'}} def union_others(except_lang): res = set() for lang in alphabets: if lang != except_lang: res = res | alphabets[lang] return res unique = {lang: set() for lang in alphabets} for lang in alphabets: unique[lang] = alphabets[lang] - union_others(lang) print(unique['pl']) I get the following output: {'ę', 'ś'} Is there any simple way (without cycle) to get a union of all sets of languages except the current one instead of using union_others(lang) function?
has answer: http://stackoverflow.com/a/49033655
accepted answer: http://stackoverflow.com/a/49033655
has comment: http://stackoverflow.com/comment/85071110
answer count: 3
has comment: http://stackoverflow.com/comment/85071502
has answer: http://stackoverflow.com/a/49033389
tagged with: python
has title: Unique letters in alphabet
favorite count: 0
has comment: http://stackoverflow.com/comment/85087700
has comment: http://stackoverflow.com/comment/85072061
has comment: http://stackoverflow.com/comment/85073026
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49033228
upvote count: 3
possible better answer: http://stackoverflow.com/a/49033389
has comment: http://stackoverflow.com/comment/85071013
type: Question

http://stackoverflow.com/comment/85004535
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48999542
has text: This may be of use: https://www.jstatsoft.org/article/view/v015i01/0
score: 0

http://stackoverflow.com/q/49022511
has answer: http://stackoverflow.com/a/49022572
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85050151
has answer: http://stackoverflow.com/a/49022588
has title: Pillow cannot be imported in python
tagged with: python
has answer: http://stackoverflow.com/a/49022568
answer count: 4
has body: Im trying to install pillow on my Mac running macOS Sierra and I used the pip command to install it arunmani$ sudo pip install pillow But when I try to Import it in python I am met with: Aruns-MacBook-Air:~ arunmani$ python Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 11:07:58) [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 pillow Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pillow &gt;&gt;&gt; exit() I tried using the PIL or import from PIL method as suggested by another tack overflow article here. But to no avail I still could not import pillow into python does any one have any idea as to what is happening?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49022571
linked to: http://stackoverflow.com/q/23834663

http://stackoverflow.com/q/49036032
has comment: http://stackoverflow.com/comment/85077002
has comment: http://stackoverflow.com/comment/85078207
downvote count: 4
has comment: http://stackoverflow.com/comment/85076996
upvote count: 0
has title: All possible strings from a given alphabet
has comment: http://stackoverflow.com/comment/85077039
has comment: http://stackoverflow.com/comment/85077164
score: -4
has comment: http://stackoverflow.com/comment/85076967
type: Question
has comment: http://stackoverflow.com/comment/85077008
tagged with: combinations
has comment: http://stackoverflow.com/comment/85077062
has comment: http://stackoverflow.com/comment/85077623
has comment: http://stackoverflow.com/comment/85077439
has comment: http://stackoverflow.com/comment/85077532
has comment: http://stackoverflow.com/comment/85077003
has body: I am trying to generate all possible strings of a specific length from a given alphabet (in the form of a list). I tried using iterools methods(mainly itertools.product) but even though it worked for small lengths, it was, as expected, very expensive for, let's say n=100. I think I let it run for about 1 hour and it still wasn't finished. What is the fastest way to achieve this in a reasonable time frame?
has answer: http://stackoverflow.com/a/49038037
answer count: 1
has comment: http://stackoverflow.com/comment/85078170
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49045481
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/49046121
has comment: http://stackoverflow.com/comment/85095549
score: 0
tagged with: sumo
answer count: 1
has body: SUMO simulator: is it possible to add cars to the simulation dynamically? I wanna do script for counting cars from video input in OpenCV+python
type: UnansweredQuestion
tagged with: python
tagged with: simulation
has title: SUMO + OpenCV + Python = simulation in time? Is it possible
tagged with: dynamic

http://stackoverflow.com/comment/85220781
type: Comment
type: QuestionComment
has text: can you post expected output?
comment on: http://stackoverflow.com/q/49107912
score: 0

http://stackoverflow.com/q/49100810
has comment: http://stackoverflow.com/comment/85948703
type: Question
has body: I am trying to do a simple real-time stock data visualizer using Bokeh. I have created the object data type Candle which has the attributes time, highest, lowest, open and close. candle1, candle2, and candle3 are instances of Candle. I use the following piece of code to show a graph with the data of those 3 instances. If I want to add a 4th candle after I have shown the chart (after calling show(plot)), how should I do it? I think that I do not achieve it because because the html contains static data, but I do not have any clue about how to do what I want. The objective would be to receive a candle per minute and add that to the chart. plot = figure(x_axis_type="datetime", width = 1000, height= 300, title ="Live Chart", sizing_mode ='scale_both') plot.segment(candle1.time, candle1.highest, candle1.time, candle1.lowest, color="black") plot.segment(candle2.time, candle2.highest, candle2.time, candle2.lowest, color="black") plot.vbar(candle1.time, 0.5 *60*60*1000, candle1.open, candle1.close,fill_color="#00ff80", line_color="black") plot.vbar(candle2.time, 0.5 * 60 * 60 * 1000, candle2.open, candle2.close, fill_color="#00ff80", line_color="black") output_file("candlestick.html", title="Candle example") show(plot)
score: 0
has answer: http://stackoverflow.com/a/49659318
answer count: 1
has comment: http://stackoverflow.com/comment/85271920
has comment: http://stackoverflow.com/comment/85995864
tagged with: python
has title: How to add elements to an existing Bokeh chart
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49659318
tagged with: bokeh

http://stackoverflow.com/comment/85022668
has text: @Nae: `place` is almost never the right answer. This is especially true here, where `grid` is the obvious choice.
score: 1
comment on: http://stackoverflow.com/q/49007295
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84981412
has text: Thank you sir, this answered very well to my question.
type: Comment
comment on: http://stackoverflow.com/a/48984757
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84975897
has text: @believesInSanta sorry I didn't understand. DId I say something wrong or did something worked for you because of me?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48985117

http://stackoverflow.com/comment/85183643
type: QuestionComment
has text: We are not going to download your code & work for you. Please post relevant snippets in the question
score: 1
comment on: http://stackoverflow.com/q/49088752
type: Comment

http://stackoverflow.com/a/49009477
answers question: http://stackoverflow.com/q/49009287
type: Answer
score: 1
has body: Make sure the payload is formatted correctly. It appears you are missing an '{' in your second object within your payload. The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
upvote count: 1
has comment: http://stackoverflow.com/comment/85023383
downvote count: 0

http://stackoverflow.com/a/49117795
has body: The problems is that this line reader = PdfFileReader(f) returns an object of type PdfFileReader. You're then passing this object to the extract() function which is expecting a file path and not a PdfFileReader object. Suggestion would be to move the PDF related processing that you currently have in the search() function to the extract function() instead. Then, in the extract function, you would check to see if it is a PDF file and then act accordingly. So, something like this: def extract(file_path, counter): if file_path.lower().endswith(('.pdf')): reader = PdfFileReader(file) contents = reader.getPage(0).extractText().split('\n') counter.update([x for x in contents if x not in ignore and len(x) &gt; 2]) elif file_path.lower().endswith(('.html', '.txt')): words = re.findall('\w+', open(file_path).read().lower()) counter.update([x for x in words if x not in ignore and len(x) &gt; 2]) else: ## some other file type... Haven't tested the code snippet above but hopefully you should get the idea.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49117172
answers question: http://stackoverflow.com/q/49117172

http://stackoverflow.com/a/49109600
answers question: http://stackoverflow.com/q/49108148
score: 0
has comment: http://stackoverflow.com/comment/85225403
has comment: http://stackoverflow.com/comment/85224453
has comment: http://stackoverflow.com/comment/85227971
has comment: http://stackoverflow.com/comment/85225349
has comment: http://stackoverflow.com/comment/85225178
has comment: http://stackoverflow.com/comment/85230365
has comment: http://stackoverflow.com/comment/85225419
has comment: http://stackoverflow.com/comment/85228541
type: Answer
has body: Try the code below and it will work for you. self.canonicalAddressesButton.clicked.connect(self.data_parsed_notification) def data_parsed_notification(self): msgBox = QtWidgets.QMessageBox() msgBox.information(self, Message', 'Data Has Been Parsed!')
has comment: http://stackoverflow.com/comment/85225981

http://stackoverflow.com/a/49116192
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49115507
upvote count: 1
has comment: http://stackoverflow.com/comment/85237854
has body: Look at this simplified condition from django base Model _save_table method - decision to update or insert depends on model pk and force_insert value: def _save_table(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None): updated = False # ... if pk_set and not force_insert: updated = self._do_update() if not updated: result = self._do_insert() # ... return updated And you can go that same way in your overrided save method if you want entirely custom update/insert operations: def save(self, force_insert=False, **kwargs): updated = False if self.pk and not force_insert: updated = self.custom_update() if not updated: self.custom_insert() return updated
downvote count: 0

http://stackoverflow.com/comment/85105346
type: Comment
comment on: http://stackoverflow.com/a/49039812
type: AnswerComment
has text: An individual function/task? No. Tasks contain arbirary Python code and so behave in unpredictable ways.
score: 0

http://stackoverflow.com/comment/85161331
has text: @Bryan Oakley By "didn't work" I mean that the maximum value did not update. The code threw no errors.
comment on: http://stackoverflow.com/q/49077351
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49023265
has body: You have to call the google finance API instead of the URL which should be used by a user - Change your url - base_url = 'https://finance.google.com/finance?q=NASDAQ:' + symbol + '&amp;output=json' Here is the content you now have to parse - [{ "symbol": "AAPL", "exchange": "NASDAQ", "id": "22144", "t": "AAPL", "e": "NASDAQ", "name": "Apple Inc.", "f_reuters_url": "http:\u002F\u002Fstocks.us.reuters.com\u002Fstocks\u002Fratios.asp?rpc=66\u0026symbol=AAPL.O", "f_recent_quarter_date": "Q4 (Dec \u002717)", "f_annual_date": "2017", "f_ttm_date": "2016", "financials": [{ "f_type": "Income\u0026nbsp\u003BStatement", "url": "http://www.google.com/finance?fstype=ii&amp;q=NASDAQ:AAPL", "f_figures": [{ "title": "", "recent_quarter": "88,293.00", "annual": "229,234.00", "ttm": "215,639.00" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "88,293.00", "annual": "229,234.00", "ttm": "215,639.00" }, { "title": "", "recent_quarter": "54,381.00", "annual": "141,048.00", "ttm": "131,376.00" }, { "title": "", "recent_quarter": "33,912.00", "annual": "88,186.00", "ttm": "84,263.00" }, { "title": "", "recent_quarter": "4,231.00", "annual": "15,261.00", "ttm": "14,194.00" }, { "title": "", "recent_quarter": "3,407.00", "annual": "11,581.00", "ttm": "10,045.00" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "62,019.00", "annual": "167,890.00", "ttm": "155,615.00" }, { "title": "", "recent_quarter": "26,274.00", "annual": "61,344.00", "ttm": "60,024.00" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "-", "annual": "-", "ttm": "-" }, { "title": "", "recent_quarter": "38.00", "annual": "-133.00", "ttm": "-1,195.00" }, { "title": "…
answers question: http://stackoverflow.com/q/49022447
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/129143777
has comment: http://stackoverflow.com/comment/85052228
type: Answer
has comment: http://stackoverflow.com/comment/126926787
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49022447
score: 1

http://stackoverflow.com/q/49059182
has body: I'm trying to use BeautifulSoup to scrape .xls tables which are available for download from Xcel Energy's website (https://www.xcelenergy.com/working_with_us/municipalities/community_energy_reports). This function gets the URL links of the tables and attempts to download them: url = 'https://www.xcelenergy.com/working_with_us/municipalities/community_energy_reports' dir = 'C:/Users/aobrien/PycharmProjects/xceldatascraper/' def scraper(page): from bs4 import BeautifulSoup as bs import urllib.request import requests import os import re tld = r'https://www.xcelenergy.com' pageobj = requests.get(page, verify=False) sp = bs(pageobj.content, 'html.parser') xlst, fnms = [], [] links = [a['href'] for a in sp.find_all('a', attrs={'href': re.compile("/staticfiles/")})] for idx, a in enumerate(links): if a.endswith('.xls'): furl = tld + str(a) xlst.append(furl) fnms.append(a.split('/')[4]) naur = zip(fnms, xlst) if not os.path.exists(dir + 'tables'): os.makedirs(dir + 'tables') for name, url in naur: print(url) res = urllib.request.urlopen(url) xls = open(dir + 'tables/' + name, 'wb') xls.write(res.read()) xls.close() scraper(url) The scripts fails when urllib.request.urlopen(url) attempts to access the file, returning "urllib.error.HTTPError: HTTP Error 404: Not Found". The "print(url)" statement prints the url that I had the script construct (https://www.xcelenergy.com/staticfiles/xe-responsive/Working With Us/MI-City-Forest-Lake-2016.xls), and manually pasting that url into a browser downloads the file just fine. What am I missing?
linked to: http://stackoverflow.com/q/120951
has title: Downloading an .xls file results in a "urllib.error.HTTPError: HTTP Error 404: Not Found" error
answer count: 0
tagged with: python-requests
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/85124187
has comment: http://stackoverflow.com/comment/85123644
score: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/xls
tagged with: python

http://stackoverflow.com/q/49094597
has answer: http://stackoverflow.com/a/49094955
has answer: http://stackoverflow.com/a/49617568
has comment: http://stackoverflow.com/comment/85194839
tagged with: pip
tagged with: python
linked to: http://stackoverflow.com/q/60575153
has answer: http://stackoverflow.com/a/65484794
has answer: http://stackoverflow.com/a/52269729
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66568905
has title: Illegal instruction (core dumped) after running import tensorflow
has comment: http://stackoverflow.com/comment/85194706
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/49094955
has answer: http://stackoverflow.com/a/57527826
has answer: http://stackoverflow.com/a/65825435
score: 38
downvote count: 0
has answer: http://stackoverflow.com/a/63721780
has answer: http://stackoverflow.com/a/51777012
upvote count: 38
tagged with: virtualenv
has body: I created a fresh virtual environment: virtualenv -p python2 test_venv/ And installed tensorflow: pip install --upgrade --no-cache-dir tensorflow import tensorflow gives me Illegal instruction (core dumped) Please help me understand what's going on and how I can fix it. Thank you. CPU information: -cpu description: CPU product: Intel(R) Core(TM) i3 CPU M 330 @ 2.13GHz bus info: cpu@0 version: CPU Version capabilities: x86-64 fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 popcnt lahf_lm tpr_shadow vnmi flexpriority ept vpid dtherm arat cpufreq Stacktrace obtained with gdb: #0 0x00007fffe5793880 in std::pair&lt;std::__detail::_Node_iterator&lt;std::pair&lt;tensorflow::StringPiece const, std::function&lt;bool (tensorflow::Variant*)&gt; &gt;, false, true&gt;, bool&gt; std::_Hashtable&lt;tensorflow::StringPiece, std::pair&lt;tensorflow::StringPiece const, std::function&lt;bool (tensorflow::Variant*)&gt; &gt;, std::allocator&lt;std::pair&lt;tensorflow::StringPiece const, std::function&lt;bool (tensorflow::Variant*)&gt; &gt; &gt;, std::__detail::_Select1st, std::equal_to&lt;tensorflow::StringPiece&gt;, tensorflow::StringPieceHasher, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits&lt;true, false, true&gt; &gt;::_M_emplace&lt;std::pair&lt;tensorflow::StringPiece, std::function&lt;bool (tensorflow::Variant*)&gt; &gt; &gt;(std::integral_constant&lt;bool, true&gt;, std::pair&lt;tensorflow::StringPiece, std::function&lt;bool (tensorflow::Variant*)&gt; &gt;&amp;&amp;) () from /media/gerry/hdd_1/ws_hdd/test_venv/local/lib/python2.7/site-packages/tensorflow/python/../libtensorflow_framework.so #1 0x00007fffe5795735 in tensorflow::U…
favorite count: 0
possible better answer: http://stackoverflow.com/a/49617568
answer count: 9

http://stackoverflow.com/comment/85007421
comment on: http://stackoverflow.com/a/48995937
type: AnswerComment
score: 0
has text: Thank you jpp! I am sure your solution would be handy to address the upcoming technical challenges.
type: Comment

http://stackoverflow.com/a/61272903
type: Answer
answers question: http://stackoverflow.com/q/49088408
score: 0
has body: make sure to use the terminal as a previous comment said. In case you use VS Code, you can just type exit() in the python interpreter section to get back to the terminal/Powershell session.

http://stackoverflow.com/comment/85225309
score: 0
type: Comment
has text: I cannot find the same unpublic name in the link you provided, does it mean that the name of these unpublic name has changed by the developers of pytorch. for example: _cudnn_convolution_backward_data（0.1.12） => _cudnn_convolution_backward_input _cudnn_convolution_backward_filer（0.1.12） => _cudnn_convolution_backward_weight I am using the 0.1.12 pytorch, maybe pytorch's version you provided is higher than 0.1.12?
comment on: http://stackoverflow.com/a/49106196
type: AnswerComment

http://stackoverflow.com/a/49056202
score: 1
upvote count: 1
type: Answer
has body: This is one method. It takes a few lines, but building a new dataframe is often more efficient. from itertools import chain df = pd.DataFrame([['user2', [31501, 31502, 31503], 'blogpost']], columns=['user', 'groupIDs', 'report']) lens = list(map(len, df['groupIDs'])) df_out = pd.DataFrame({'user': np.repeat(df['user'].values, lens), 'groupIDs': list(chain.from_iterable(df['groupIDs'].values)), 'report': np.repeat(df['report'].values, lens)}) # groupIDs report user # 0 31501 blogpost user2 # 1 31502 blogpost user2 # 2 31503 blogpost user2
answers question: http://stackoverflow.com/q/49054198
downvote count: 0

http://stackoverflow.com/comment/85102162
type: QuestionComment
comment on: http://stackoverflow.com/q/49048217
has text: That should be sufficient to make it work, are you sure you're using the correct service_account.json keyfile
score: 0
type: Comment

http://stackoverflow.com/q/48997277
answer count: 3
has answer: http://stackoverflow.com/a/61017549
has answer: http://stackoverflow.com/a/74512189
has title: Standard deviation of binned values with `scipy.stats.binned_statistic`
type: UnansweredQuestion
tagged with: python
tagged with: binning
has body: When I bin my data accordingly to scipy.stats.binned_statistic (see here for example), how do I get the error (that is the standard deviation) on the average binned values? For example, if I bin my data as following: windspeed = 8 * np.random.rand(500) boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500) bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed, boatspeed, statistic='median', bins=[1,2,3,4,5,6,7]) plt.figure() plt.plot(windspeed, boatspeed, 'b.', label='raw data') plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5, label='binned statistic of data') plt.legend() how do I get the standard deviation on the bin_means?
has comment: http://stackoverflow.com/comment/85031155
score: 4
has answer: http://stackoverflow.com/a/49023405
type: Question
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/85008943
favorite count: 0
tagged with: statistics

http://stackoverflow.com/q/49108298
has answer: http://stackoverflow.com/a/49111131
type: Question
score: 0
has body: I have coded selenium Python script and now I want to compile it to exe file so it can run on computer without Python installed I've tried to install cx-freeze and pyinstaller but failed to do so and wasn't able to find the patch for the errors I am getting while installing these modules I have installed py2exe but its not able to convert selenium Python to exe Whenever I execute I keep getting error msg I want to use chromedriver, here's the error I am getting FileNotFoundError: [Errno 2] No such file or directory: 'selenium\\webdriver\\re mote\\getAttribute.js'
has title: Any way to compile Python 3.4 program to exe? Except py2exe, pyinstaller or cx-freeze
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/85222632
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85231833
tagged with: python
linked to: http://stackoverflow.com/q/2136837
type: UnansweredQuestion
tagged with: selenium

http://stackoverflow.com/q/49114019
has body: I've run into a problem, where the data passed to my template from the route is in the form of a list of tuples. This format is necessary, I believe, because I need both a unique ID and a person's name, which is not unique, and I must sort the names alphabetically. The list of tuples, sorted, achieves that perfectly. This throws an error, "jinja2.exceptions.UndefinedError: 'item' is undefined": {% for item in student_list %} {{ item[1] }} {% endfor %} This does NOT throw an error, and works perfectly: {% for item in student_list %} {{ item[1] }} {% endfor %} So I've resorted to the second version, but I would like to use the url_for() function if possible. This is the route: @app.route('/') def index(): all_students = get_all_students(PEOPLE) return render_template('index.html', student_list=all_students) This is the format of the list: student_list = [('896-95-9224', 'Jimenez'), ('778-73-1993', 'Ramos'), ('578-92-7338', 'Thomas'), ('003-73-8821', 'Watts')] Repo here There are a number of answered questions in SO about Flask/Jinja2 URL building, but none specifically address this case, where a list or tuple index is needed.
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: jinja2
downvote count: 1
type: Question
score: 1
tagged with: flask
favorite count: 0
tagged with: python
has title: Flask Jinja2 URL with url_for() not working

http://stackoverflow.com/comment/85087577
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49041110
has text: What do you mean by you got stuck? What is it doing? Please also post your code, so we can see what you have tried.
score: 0

http://stackoverflow.com/q/49108274
linked to: http://stackoverflow.com/q/2259382
has title: pygame.image.load() not working
score: 0
answer count: 1
tagged with: pygame
has comment: http://stackoverflow.com/comment/85224123
has body: I am currently learning the code from a tutorial on Pygame Game Development: https://www.youtube.com/watch?v=fcryHcZE_sM I have copied the code exactly into Pycharm and I believe it should work. #Pygame Sprite Example import pygame import random import os WIDTH = 360 HEIGHT = 480 FPS = 30 #Colours BLACK = (0, 0, 0) WHITE= (255, 255, 255) 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, "img") class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert() self.image.set_colourkey(BLACK) self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) def update(self): self.rect.x += 5 if self.rect.left &gt; WIDTH: self.rect.right = 0 #initialise pygame and create window pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("My Game") clock = pygame.time.Clock() all_sprites = pygame.sprite.Group() player = Player() all_sprites.add(player) #Game Loop running = True while running: #keep loop running at right speed clock.tick(FPS) #Process Input/Events for event in pygame.event.get(): #check for closing window if event.type == pygame.QUIT: running = False #Update all_sprites.update() #Draw/Render screen.fill(BLUE) all_sprites.draw(screen) # *after drawing everything, flip the display* pygame.display.flip() pygame.quit() it gives me this error when I run it: C:\Users\George\PycharmProjects\app\venv1\Scripts\python.exe "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py" Traceback (most recent call last): File "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py", line 46, in &lt;module&gt; player = Player() File "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py", line 28, in __init__ self.image = pyg…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60762080
tagged with: python
has comment: http://stackoverflow.com/comment/85249779
type: Question

http://stackoverflow.com/a/48982169
answers question: http://stackoverflow.com/q/48980691
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85201341
type: Answer
has comment: http://stackoverflow.com/comment/85206638
has comment: http://stackoverflow.com/comment/85208822
has body: Here's a reimplementation that avoids the duplication and works for counts from 1 up, to the limit of EVEN_NUMBERS and COLORS: import math from turtle import Turtle, Screen EVEN_NUMBERS = [2, 4, 6, 8, 10, 12] COLORS = ["darkcyan", "purple", "orange", "magenta", "deepskyblue", "green", "black"] def createWaves(amp, count): screen.tracer(False) for x in range(361): y_offsets = [] for i in range(count): turtles[i].showturtle() y_offset = math.sin(math.radians(x * EVEN_NUMBERS[i])) * amp / EVEN_NUMBERS[i] turtles[i].goto(x, y_offset) y_offsets.append(y_offset) if count &gt; 1: turtles[-1].showturtle() turtles[-1].goto(x, sum(y_offsets)) screen.update() screen.tracer(True) screen = Screen() turtles = [] for color in COLORS: turtle = Turtle("turtle", visible=False) turtle.speed('fastest') turtle.color(color) turtle.width(2) turtles.append(turtle) turtles[-1].width(3) # summation turtle createWaves(100, 4) screen.exitonclick()
accepted answer of: http://stackoverflow.com/q/48980691
score: 0

http://stackoverflow.com/comment/85243962
type: AnswerComment
score: 0
type: Comment
has text: Fantastic! Thank you very much
comment on: http://stackoverflow.com/a/49101589

http://stackoverflow.com/comment/84990390
has text: This is `axis=0`.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48988907
type: AnswerComment

http://stackoverflow.com/comment/85164602
has text: My understanding is that the training data and the testing data are the same, except that the testing data has less data and the training data has more
comment on: http://stackoverflow.com/q/49079122
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48982438
accepted answer of: http://stackoverflow.com/q/48982375
type: Answer
has body: This is what you are expecting... score = input("Enter Score: ") try: sr = float(score) assert sr &lt;= 1.0 #needs an assert keyword assert sr &gt;= 0.0 #needs an assert keyword except: print("Number entered must be between 0.0 and 1.0") quit() If you don't write assert the sr &lt;= 1.0, it simply tries to compute the value and discard it as you are not assigning it to anything. Alternatively you can use an if statement and quit in the if the condition doesn't match like this. score = input("Enter Score: ") sr = float(score) if sr &gt; 1.0 or sr &lt; 0.0: print("Number entered must be between 0.0 and 1.0") quit()
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48982375

http://stackoverflow.com/q/49070594
tagged with: arrays
has body: I have a file with multiple (over 1000) columns and rows, and their names do not follow any pattern. The example of it as in below: file1.txt IDs AABC ABC6 YHG.8 D78Ha Ellie 12 48.70 33 Kate 98 34 21 76.36 Joe 22 53 49 Van 77 40 12.1 Xavier 88.85 First, I have to fill the blanks with NA, so that it will look like : file1.txt IDs AABC ABC6 YHG.8 D78Ha Ellie 12 NA 48.70 33 Kate 98 34 21 76.36 Joe 22 53 49 NA Van 77 NA 40 12.1 Xavier NA NA NA 88.85 Then, I am trying to get all combinations for IDs and other column as AABC, ABC6,YHG.8 and D78Ha, such as : Ellie , AABC --&gt; 12 Ellie, ABC6 --&gt; NA Ellie, YHG.8 --&gt; 48.70 ( without rounding ) Ellie, D78Ha --&gt; 33 Kate,AABC --&gt; 98 Kate, ABC6 --&gt; 34 ... So the desired output should be 20 lines (4 columns x 5 IDs) as following: output.txt Ellie AABC 12 Ellie ABC6 NA Ellie YHG.8 48.70 Ellie D78Ha 33 Kate AABC 98 Kate ABC6 34 .. For this reason, I filled the blanks manually with NA, read file with pandas, and indexed the IDs. So that I can reach with the ID names and other column names. But I could not iterate it. My try was: import pandas as pd tablefile = pd.read_csv('file1.txt',sep='\t') print(tablefile) df2=tablefile.set_index("IDs") print("Ellie AABC " , df2.loc["Ellie", "AABC" ]) print("Kate AABC " , df2.loc["Kate", "AABC" ]) print("Xavier AABC " , df2.loc["Xavier", "AABC" ]) It prints: ('Ellie AABC ', 12.0) ('Kate AABC ', 98.0) ('Xavier AABC ', nan) How can I fill the blanks with NAs and iterate in this array without calling the names by writing it one by one? Maybe with increasing i in [i,i]?
tagged with: pandas
has answer: http://stackoverflow.com/a/49071245
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49071245
possible better answer: http://stackoverflow.com/a/49071402
linked to: http://stackoverflow.com/q/17092671
has answer: http://stackoverflow.com/a/49071402
has title: Getting all possible values from an array in python
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
answer count: 2

http://stackoverflow.com/comment/85008450
score: 0
type: Comment
type: QuestionComment
has text: You ARE using a `for` loop though?
comment on: http://stackoverflow.com/q/49001784

http://stackoverflow.com/comment/85186422
comment on: http://stackoverflow.com/a/49090330
score: 0
type: AnswerComment
has text: I have no idea why did you put it in your original template so I didn't temper with it, my point was only the filters.
type: Comment

http://stackoverflow.com/q/48990706
score: 2
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48990748
upvote count: 2
has title: Does Python have a conditional NOT statement
tagged with: boolean-expression
tagged with: python
type: AnsweredQuestion
type: Question
has body: I'd like to filter a list of values. Depending on the state of a variable, I'd like to return the positive or negative result of the filter. Example: def foo(it, my_condition): return [s for s in it if (s.startswith("q") if my_condition else not s.startswith("q"))] foo(["The", "quick", "brown", "fox"], my_condition=True) So on my_condition=True I get ["quick"] and on my_condition=False I get ["The", "brown", "fox"]. What I don't like about the implementation is this part: (s.startswith("q") if filter else not s.startswith("q")). It contains duplicate code and takes up a lot of space in an otherwise concise list comprehension. What I really want is just to insert a not after the if, depending on the state of the filter variable. Is there a more pretty / clean solution to this? If possible, I'd like to avoid the computational overhead of lambda expressions in this case.
has answer: http://stackoverflow.com/a/48990748

http://stackoverflow.com/comment/85072257
type: Comment
comment on: http://stackoverflow.com/a/49023389
has text: If I am not wrong, a `values()` followed by `annotation()` would perform `Group By` operation
score: 0
type: AnswerComment

http://stackoverflow.com/q/49040715
tagged with: python
tagged with: client
accepted answer: http://stackoverflow.com/a/49697646
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/49697646
has body: Does anybody know how to create a C# client for tensorflow serving? My tensorflow serving installation: I installed tensorflow serving using the tensorflow serving dockerfile, then inside the container I did the following: pip install tensorflow pip install tensorflow-serving-api echo "deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" | tee /etc/apt/sources.list.d/tensorflow-serving.list curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | apt-key add - apt-get update &amp;&amp; apt-get install tensorflow-model-server Then I run the tensorflow serving server: tensorflow_model_server --port=9000 --model_name=example_model --model_base_path=/serving/my_model_2 &amp;&gt; my_log &amp; where my_model_2 contains the exported tensorflow model I want to serve. Given this information I have the following questions: Do I need to install tensorflow serving in a different way in order to make a C# client? If I need to install it in a different way; Can you tell me how? Can you give me a general idea of what I have to do in order to accomplish my goal? I mean, I suspect I have to install my tf serving in a different way in order to create a explicit .proto file . I'm a little lost about this if you can give me the general idea and an example I would appreciate it.
type: Question
tagged with: c#
has title: Tensorflow serving
tagged with: grpc
tagged with: tensorflow-serving
linked to: http://stackoverflow.com/q/65869272
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49114286
tagged with: pandas
has comment: http://stackoverflow.com/comment/85234529
has comment: http://stackoverflow.com/comment/85234734
answer count: 0
has title: Filling out missing values in columns?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85235048
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85234182
has body: I have a dataset named as com, and I want to fill the missing values using the appropriate filters in the dataset.. I have replaced the question mark by Nan, by using this line of code: com.replace('?', np.NaN, inplace=True) Now I want to fill the missing values.. I have tried this code but its not working and return the same dataset containing NaN values com.fillna(com.mean(), inplace=True) csv file https://1drv.ms/f/s!Au0AN4RPO4G4g3iFTbFTiEsakKIE view of the csv csv image Output as show by the system:

http://stackoverflow.com/q/49051483
has answer: http://stackoverflow.com/a/51477932
has comment: http://stackoverflow.com/comment/85108546
has comment: http://stackoverflow.com/comment/85107444
has comment: http://stackoverflow.com/comment/85107845
has comment: http://stackoverflow.com/comment/85107949
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/85108388
accepted answer: http://stackoverflow.com/a/49051617
favorite count: 0
has body: I am trying to test (pytest) some code in python. I instantiate a logger object with import logging logging.getLogger() Now I would like to retrieve the logger object created in order to perform some asserts on it. But if I inspect the global variables I cannot see it. Where is the Logger object? EDIT: thanks for the responses below logger=logging.GetLooger() I am now facing the same problem with logging.basicConfig(). And when I do r=logging.basicConfig() , the return value is None. There is still no Logger object in the globals How to find the Logger object in this case?
tagged with: python
has answer: http://stackoverflow.com/a/49051617
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85108655
score: 1
has title: Where is Logger object?
type: Question
has comment: http://stackoverflow.com/comment/85107892
possible better answer: http://stackoverflow.com/a/51477932

http://stackoverflow.com/a/62276750
answers question: http://stackoverflow.com/q/49113497
type: Answer
has body: I had first Upgraded the Anaconda prompt I had then used conda create -n tfp python=3.7 conda activate tfp Then import the tensorflow
score: 0

http://stackoverflow.com/q/49016939
type: Question
tagged with: matplotlib
has body: I am trying to fit Gaussian function to my Python plot. I have attached the code here. Any corrections would be appreciated! import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit import math import random from numpy import genfromtxt data= genfromtxt ('PVC_Cs137.txt') plt.xlim(0,2500) plt.ylim(0,30000) plt.xlabel("Channel number") plt.ylabel("Counts") x = data[:,0] y = data[:,1] n = len(x) mean = sum(x*y)/n sigma = sum(y*(x-mean)**2)/n def gaus(x,a,x0,sigma): return a*exp(-(x-x0)**2/(2*sigma**2)) popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma]) plt.plot(x,gaus(x,*popt)) plt.show() And here is the link to my file: https://www.dropbox.com/s/hrqjr2jgfsjs55x/PVC_Cs137.txt?dl=0
upvote count: 2
linked to: http://stackoverflow.com/q/48226089
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/85039406
has title: Gaussian fit in Python plot
has comment: http://stackoverflow.com/comment/85038923
has answer: http://stackoverflow.com/a/49019803
has comment: http://stackoverflow.com/comment/85044523
score: 1
tagged with: scipy

http://stackoverflow.com/q/48970108
tagged with: mnist
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48970211
possible better answer: http://stackoverflow.com/a/48977778
has title: MNIST data - Cannot feed value of shape (1000, 784) for Tensor 'Placeholder:0', which has shape '(5500, 784)'
has answer: http://stackoverflow.com/a/48977778
has answer: http://stackoverflow.com/a/48970211
tagged with: python
type: AnsweredQuestion
has body: I'm trying to test out the data with 1000 examples while I got 5500 examples for the training data. Although I changed the Placeholder para for (1000,784) for the testing part from (5500, 784) used for the training part, I still got the error ValueError: Cannot feed value of shape (1000, 784) for Tensor 'Placeholder:0', which has shape '(5500, 784)', could anyone please help? import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import random from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) def TRAIN_SIZE(num): print ('Total Training Images in Dataset = ' + str(mnist.train.images.shape)) print ('--------------------------------------------------') x_train = mnist.train.images[:num,:] print ('x_train Examples Loaded = ' + str(x_train.shape)) y_train = mnist.train.labels[:num,:] print ('y_train Examples Loaded = ' + str(y_train.shape)) print('') return x_train, y_train def TEST_SIZE(num): print ('Total Test Examples in Dataset = ' + str(mnist.test.images.shape)) print ('--------------------------------------------------') x_test = mnist.test.images[:num,:] print ('x_test Examples Loaded = ' + str(x_test.shape)) y_test = mnist.test.labels[:num,:] print ('y_test Examples Loaded = ' + str(y_test.shape)) return x_test, y_test def display_digit(num,x_train,y_train): print(y_train[num]) label = y_train[num].argmax(axis=0) image = x_train[num].reshape([28,28]) plt.title('Example: %d Label: %d' % (num, label)) plt.imshow(image, cmap=plt.get_cmap('gray_r')) # plt.show() X_train, Y_train = TRAIN_SIZE(5500) X_test, Y_test = TEST_SIZE(1000) learning_rate = 0.01 train_steps = 2500 # Display 30 random digits for i in range(30): selected = random.randint(0,5500-1) display_digit(selected, X_train, Y_train) # n features, k classes n = 784 k = 10 batch_size = 5500 X = tf.placeholder(tf.float32, [batch_size, 784]) Y = tf.placeholder(tf.float32, [batch_size, 10]) W = tf.Variable(tf.random_normal(…
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/49019371
has body: I have 2 arrays. a = np.zeros(2) b = np.ones(2) I want to combine them so that its output is: array([[0, 1], [0, 1]]) If I had a = np.zeros((2,1)) and b = np.zeros((2,1)), this can done with np.hstack((a,b)) or np.append(a,b,1). But I don't. Any thoughts?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49019448
has answer: http://stackoverflow.com/a/49019405
tagged with: arrays
has title: Python: Add a column to numpy 1d array
has answer: http://stackoverflow.com/a/49020538
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49019405
upvote count: 2
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49019416
has comment: http://stackoverflow.com/comment/85045589
has answer: http://stackoverflow.com/a/49019416

http://stackoverflow.com/q/48970752
has title: If a dictionary key contains a certain word, how would I remove it?
has comment: http://stackoverflow.com/comment/84947245
downvote count: 0
has comment: http://stackoverflow.com/comment/84947110
favorite count: 0
accepted answer: http://stackoverflow.com/a/48970830
upvote count: 2
has body: A simple program about storing rivers and their respective locations in a dictionary. I was wondering how I would go about looping through a dictionary key and looking if the dictionary key (or value) contains a certain word, if the word is present in the key, remove it. EX: rivers_dict = {'mississippi river': 'mississippi'} How would I remove the word 'river' in the dictionary key 'mississippi river'? I know i can assign something such as: rivers_dict['mississippi'] = rivers_dict.pop('mississippi river'). Is there a way to do this in a more modular manner? Thanks in advance.
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/48970792
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48970895
has comment: http://stackoverflow.com/comment/84946975
type: Question
possible better answer: http://stackoverflow.com/a/48970861
has answer: http://stackoverflow.com/a/48970830
has answer: http://stackoverflow.com/a/48970861

http://stackoverflow.com/a/49061184
has body: use numpy's arange instead of range: import numpy as np for x in np.arange(0, 1, 0.1): print(x)
has comment: http://stackoverflow.com/comment/85127865
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 13
upvote count: 13
accepted answer of: http://stackoverflow.com/q/49061171
answers question: http://stackoverflow.com/q/49061171

http://stackoverflow.com/comment/85195728
comment on: http://stackoverflow.com/q/49095208
score: 0
type: Comment
type: QuestionComment
has text: still it's being unclear, you have posted a code where many functions use is not clear to us, also try to mention what are you going to pass and what you want to get, to be; it's unclear with your statements- your desire output is in list but you want to replace it but where? in xml or at runtime?

http://stackoverflow.com/a/48998358
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85002647
answers question: http://stackoverflow.com/q/48998326
has body: Observe these facts and use them to tweak your algorithm: As written, your function will always return an integer, because mid + offset is an integer. If you want to return a None, you'll need a bare return somewhere (the if/elif/else chain will never fall through). You'll need a halting condition for the recursion somewhere. You do have one currently (after the comment "if the item is at mid, we're done"). However, you will need another, different, return for handling the case when the value is not present. If you receive an empty array as input, the mid will be calculated as index 0. Does that seem right...? Slicing array[mid:] includes the item at index mid. Slicing at array[:mid] does not include the item at index mid. Look for any logical overlap in the three branches of your if/elif/else.
accepted answer of: http://stackoverflow.com/q/48998326
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85002467

http://stackoverflow.com/comment/85252271
type: AnswerComment
comment on: http://stackoverflow.com/a/49110332
score: 0
type: Comment
has text: Thanks! I tried to do it, but I get a Memory error. My dataset is too large. Any way to apply the loop in small increments instead of applying y[i] to the whole dataset at one go??

http://stackoverflow.com/a/49065068
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49064948
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85135325
has body: So when you do for a in n: the a variable will be the elements in your list so 2,3,4,7,9,10 in that order So if you wanted to print from your list you would do for a in n: print(a) Or you could do for a in range(len(a)): print(n[a]) In this case a will be 0,1,2,3,4,5

http://stackoverflow.com/comment/85163346
comment on: http://stackoverflow.com/q/49078478
has text: If your computer is freezing due to memory issues, have you considered simply outputting each day of week to a file line by line (e.g. csv or hdf5)? This should have minimal memory overhead.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49030065
type: Answer
answers question: http://stackoverflow.com/q/49029952
has comment: http://stackoverflow.com/comment/85340531
has comment: http://stackoverflow.com/comment/85092211
has comment: http://stackoverflow.com/comment/85092559
accepted answer of: http://stackoverflow.com/q/49029952
has comment: http://stackoverflow.com/comment/85380373
has comment: http://stackoverflow.com/comment/85341312
has body: I think you need first DatetimeIndex and then reindex by date_range - is necessary align values, so was added floor for minute precision: print (df.index) DatetimeIndex(['2018-02-22 14:35:00', '2018-02-22 14:36:00', '2018-02-22 14:37:00', '2018-02-22 14:39:00', '2018-02-22 14:40:00', '2018-02-22 14:41:00', '2018-02-22 14:42:00', '2018-02-22 14:47:00', '2018-02-22 14:48:00', '2018-02-22 14:49:00', '2018-02-22 14:50:00', '2018-02-22 14:51:00', '2018-02-22 14:54:00', '2018-02-22 14:55:00'], dtype='datetime64[ns]', name='TIMESTAMP', freq=None) dates = pd.date_range(start_date, end_date, freq='60S').floor('60S') df = df.reindex(dates) Verifying with changed start and end dates: start_date = '22-02-2018 14:32:29' end_date = '22-02-2018 14:58:29' dates = pd.date_range(start_date, end_date, freq='60S').floor('60S') df = df.reindex(dates) print (df) Temp1 Temp2 2018-02-22 14:32:00 NaN NaN 2018-02-22 14:33:00 NaN NaN 2018-02-22 14:34:00 NaN NaN 2018-02-22 14:35:00 4.34 4.93 2018-02-22 14:36:00 4.35 5.02 2018-02-22 14:37:00 4.35 5.10 2018-02-22 14:38:00 NaN NaN 2018-02-22 14:39:00 4.31 5.23 2018-02-22 14:40:00 4.29 5.26 2018-02-22 14:41:00 4.26 5.24 2018-02-22 14:42:00 4.24 5.17 2018-02-22 14:43:00 NaN NaN 2018-02-22 14:44:00 NaN NaN 2018-02-22 14:45:00 NaN NaN 2018-02-22 14:46:00 NaN NaN 2018-02-22 14:47:00 4.09 4.64 2018-02-22 14:48:00 4.08 4.55 2018-02-22 14:49:00 4.08 4.48 2018-02-22 14:50:00 4.09 4.48 2018-02-22 14:51:00 4.11 4.50 2018-02-22 14:52:00 NaN NaN 2018-02-22 14:53:00 NaN NaN 2018-02-22 14:54:00 4.22 4.66 2018-02-22 14:55:00 4.25 4.72 2018-02-22 14:56:00 NaN NaN 2018-02-22 14:57:00 NaN NaN 2018-02-22 14:58:00 NaN NaN Another solution, especially if duplicate values is add start and end datetimes and resample with some aggregate function, e.g. sum: df.loc[pd.to_datetime(start_date)] = np.nan df.loc[pd.to_datetime(end_date)] = np.nan df = df.resample('60S').sum()
has comment: http://stackoverflow.com/comment/85092599
has comment: http://stackoverflow.com/comment/85340194
has comment: http://stackoverflow.com/comment/85092135
has comment: http://stackoverflow.com/comment/85380418
has comment: http://stackoverflow.com/comment/85381797
has comment: http://stackoverflow.com/comment/85340362
has comment: http://stackoverflow.com/comment/85340218
has comment: http://stackoverflow.com/comment/85382470
has comment: http://stackoverflow.com/comment/85091957
has comment: http://stackoverflow.com/comment/85381892
has comment: http://stackoverflow.com/comment/85380868
score: 0
has comment: http://stackoverflow.com/comment/85065713
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85064494
has comment: http://stackoverflow.com/comment/85092250
has comment: http://stackoverflow.com/comment/85380694
has comment: http://stackoverflow.com/comment/85099013
has comment: http://stackoverflow.com/comment/85342947
has comment: http://stackoverflow.com/comment/85381698

http://stackoverflow.com/comment/85196741
type: QuestionComment
comment on: http://stackoverflow.com/q/49095596
score: 0
has text: I know it is wrong. That's why I asked the question. I do not know "what" is wrong, though. Can you comment on what I wrote please? because I've gotten a bit confused on the web; seeing others' problems. I can't think clearly.
type: Comment

http://stackoverflow.com/q/49038928
upvote count: 2
has title: use row as variable with python and sql
has comment: http://stackoverflow.com/comment/85083285
tagged with: sql
downvote count: 0
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/49039019
tagged with: python
has answer: http://stackoverflow.com/a/49039356
accepted answer: http://stackoverflow.com/a/49039356
answer count: 4
score: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49039035
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49039022
has body: I am trying to update some values into a database. The user can give the row that should be changed. The input from the user, however is a string. When I try to parse this into the MySQL connector with python it gives an error because of the apostrophes. The code I have so far is: import mysql.connector conn = mysql.connector conn = connector.connect(user=dbUser, password=dbPasswd, host=dbHost, database=dbName) cursor = conn.cursor() cursor.execute("""UPDATE Search SET %s = %s WHERE searchID = %s""", ('maxPrice', 300, 10,)) I get this error mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maxPrice' = 300 WHERE searchID = 10' at line 1 How do I get rid of the apostrophes? Because I think they are causing problems.
has comment: http://stackoverflow.com/comment/85083247
has answer: http://stackoverflow.com/a/49039019
tagged with: mysql

http://stackoverflow.com/a/49117847
has comment: http://stackoverflow.com/comment/85245917
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/85246340
has comment: http://stackoverflow.com/comment/85246049
downvote count: 0
has comment: http://stackoverflow.com/comment/85245919
has body: Just use Image.new instead: im = Image.new(mode='RGB', size=(128,64), color=(255,255,255)) If you really want to make it from bytes, it would be like this: Image.frombytes(mode='RGB', size=(128,64), data=b'\xff'*128*64*3) edit: Image.frombytes expects bytes, not a list of integers. To convert a list of integers to the right type, use this: &gt;&gt;&gt; bytes([0,1,2]) # Python 3 b'\x00\x01\x02' &gt;&gt;&gt; bytes(bytearray([0,1,2])) # Python 2 '\x00\x01\x02' edit 2: mode='1' or the docs have bug (see comment thread). Assuming you have a list of zeros and ones, 1024 elements long, and you want to convert this to an 128x64 monochromatic image (one bit per pixel) then you'll have to pack the bytes manually: bits = [int(not (y%13 and x%7)) for x in range(64) for y in range(128)] # asymmetric grid octets = [bits[i:i+8] for i in range(0, len(bits), 8)] def bits2byte(bits8): result = 0 for bit in bits8: result &lt;&lt;= 1 result |= bit return result data = bytes(bytearray([bits2byte(octet) for octet in octets])) im = Image.frombytes(mode='1', size=(128,64), data=data) im.show() Result:
has comment: http://stackoverflow.com/comment/85245980
answers question: http://stackoverflow.com/q/49117783
score: 4
has comment: http://stackoverflow.com/comment/85242932
has comment: http://stackoverflow.com/comment/85245084
has comment: http://stackoverflow.com/comment/85241584

http://stackoverflow.com/q/49080918
has title: SafeConfigParser overriding files
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49081000
downvote count: 1
type: Question
upvote count: 0
tagged with: configuration-files
score: -1
has body: I am making a chat application, and need a conf file for the server and another for the client. However, whenever I run the client its conf properties get transferred to the configuration file of the server even though I am using SafeConfigParser. Is there any way to fix this? Thanks. when server starts: config = configparser.SafeConfigParser() config.read('chatserver.conf') config['PORT']['port'] = str(self.port) with open("chatserver.conf","w") as configfile: config.write(configfile) when a client joins: clientconf = configparser.SafeConfigParser() clientconf.read('chatclient.conf') clientconf['SERVER']['last_server_used'] = str(self.host) clientconf['SERVER']['port_used'] = str(self.port) with open("chatserver.conf","w") as confFile: clientconf.write(confFile) chatclient.conf: [SERVER] last_server_used = '127.0.0.1' port_used = '50000' default_debug_mode = False log = True default_log_file = chat.log chatserver.conf: [PORT] port = '1000' When I run the server, a client joins the chat, and close it, then run the server again, the chatserver.conf file becomes the same as chatclient.conf
has comment: http://stackoverflow.com/comment/85167455
answer count: 1
has comment: http://stackoverflow.com/comment/85167563
has answer: http://stackoverflow.com/a/49081000
favorite count: 0

http://stackoverflow.com/comment/85086896
score: 2
comment on: http://stackoverflow.com/q/49040765
has text: print is a reserved word (at least in python2)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85200610
score: 0
has text: It seems you already know the answer. If you want to use a variable used in another function, you have to declare it as a global variable. See these: https://docs.python.org/3/reference/simple_stmts.html#the-global-statement https://docs.python.org/3/tutorial/classes.html#private-variables
comment on: http://stackoverflow.com/q/49097658
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49081973
has comment: http://stackoverflow.com/comment/85211271
score: 0
has comment: http://stackoverflow.com/comment/85170878
has comment: http://stackoverflow.com/comment/85170609
answers question: http://stackoverflow.com/q/49081752
has comment: http://stackoverflow.com/comment/85188277
has comment: http://stackoverflow.com/comment/85171222
has body: Try adding is_secure = False like below, in order to skip ssl verification, conn = boto.ec2.connect_to_region('cn-north-1',is_secure=False) Try providing the credentials as so, that way you would know if the keys in boto config are old if this works, and if this returns the same issue then you need to check your api-key and secret on aws. API_KEY = 'Actual API_KEY' API_SECRET = 'Actual Secret' conn = boto.ec2.connect_to_region('us-east-2',aws_access_key_id=API_KEY,aws_secret_access_key=API_SECRET,is_secure=False)
has comment: http://stackoverflow.com/comment/85189965
has comment: http://stackoverflow.com/comment/85169673
has comment: http://stackoverflow.com/comment/85170116
has comment: http://stackoverflow.com/comment/85174962
has comment: http://stackoverflow.com/comment/85171434
has comment: http://stackoverflow.com/comment/85171551
type: Answer
has comment: http://stackoverflow.com/comment/85189948

http://stackoverflow.com/a/48991460
answers question: http://stackoverflow.com/q/48985874
has comment: http://stackoverflow.com/comment/84988565
has body: I do not think you are doing anything wrong. It seems to me that, in your first example, matplotlib decided (for a reason unknown to me) not to show any minor ticks, while it does for the second example. One way to solve your issue is to force the display of minor ticks: g = sns.factorplot(...) ax = g.axes.flatten()[0] ax.set_yscale('log') ax.yaxis.set_minor_locator(matplotlib.ticker.LogLocator(base=10.0, subs='all')) ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter()) plt.grid(True,which="both",ls="--",c='gray')
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84989378
downvote count: 0

http://stackoverflow.com/a/53863818
type: Answer
answers question: http://stackoverflow.com/q/49015994
score: 1
upvote count: 1
has body: (It's an old question, but i answer it, maybe help others.) option 1 (recommended) seeing comments, you mentions: In my particular case, wherein its simply a set of scripts downloading data from apis and saving in database, sqlalchemy is suiting well. In some situations (like what you mentioned) you can use django management commands. For example if you want to do some tasks that are related to django models and should run in background. like some crontab jobs like updating database fields every 5 minutes or executing some script related to some apis that should run and update database models. For this, create a management command like below and your good to go: in your app, create a folder management. then add an empty __init__.py file to it. next create another folder called commands in that folder and yet add another empty __init__.py to commands folder. now create your script files in commands folder. for example test_script.py. Now add this in test_script.py: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **kwargs): # Add your script codes here. Now to run it, simply execute this command: python manage.py test_command for more details read this link option 2 There is a powerful ORM for python sqlalchemy. You can use it if you don't want to use any part of django or create another django and add your non-django project's code to it. But remember you need to define your django model design with sqlalchemy too. But it's not that hard to do that. option 3 as my friends suggested in comments, you can config another project to use your existing django project as an app. follow Using Django database layer outside of Django?
downvote count: 0

http://stackoverflow.com/comment/85187986
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49091121
score: 0
has text: @adeora without the -H I get this warning "The directory 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."

http://stackoverflow.com/q/49054375
has title: FOREIGN KEY constraint failed in django admin panel when creating/editing/deleting a user. (Using custom user model.)
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49072280
tagged with: python
has answer: http://stackoverflow.com/a/59332511
possible better answer: http://stackoverflow.com/a/50188460
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/50188460
has body: So I'm using a custom user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, full_name, address, number, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') if not full_name: raise ValueError('Users must have an email address') if not address: raise ValueError('Users must have an email address') if not number: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email.lower()), full_name=full_name, address = address, number=number, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, full_name, address, number, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, full_name, address, numbe, password = password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, full_name, address, number, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, full_name, address, number, password = password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank = False, null = False) address = models.CharField(max_length=255, blank = False, null = False) number = models.CharField(max_length=255, blank = False, null = False) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that's built in. USERNAME_FIELD = 'email' REQUIRED…
tagged with: database
has answer: http://stackoverflow.com/a/49072280
has answer: http://stackoverflow.com/a/56770976
answer count: 4
type: AnsweredQuestion
tagged with: sqlite
downvote count: 0

http://stackoverflow.com/comment/85044523
score: 1
has text: Before fitting, examine a scatterplot of the raw data with "plt.plot(x,y)" and without setting xlim or ylim - that does not appear to be a gaussian to my eyes. Also, you can directly model "y = 0 if x > 7200" without fitting.
comment on: http://stackoverflow.com/q/49016939
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49071922
has comment: http://stackoverflow.com/comment/85149337
has comment: http://stackoverflow.com/comment/85151513
possible better answer: http://stackoverflow.com/a/49072124
type: Question
has comment: http://stackoverflow.com/comment/85149989
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/85150120
has comment: http://stackoverflow.com/comment/85149925
has body: For a recent assessment that I have completed in my studies, I have a piece of code that asks the user for four integers. Then the program must count and display the number of odd and even numbers in the entries. The code is as follows: # xx assignment 02 question 2 a = int(input("Enter an integer number: ")) b = int(input("Enter an integer number: ")) c = int(input("Enter an integer number: ")) d = int(input("Enter an integer number: ")) e = 0 o = 0 if a % 2 == 0: e = e + 1 else: o = o + 1 if b % 2 == 0: e = e + 1 else: o = o + 1 if c % 2 == 0: e = e + 1 else: o = o + 1 if d % 2 == 0: e = e + 1 else: o = o + 1 print("Number of even numbers entered: ", e) print("Number of odd numbers entered: ", o) The code I have works perfectly, I am not looking for a way to fix the code since it works. I would like to know if the reason for this exercise being marked is justified. The reason given for the mark is "Rather use a For loop than a series of if-else statements!!!!" Now, I understand that efficiency is a crucial part of programming, however the mark I got was a negative, although the task's goal was achieved. Since I just started learning Python, am I missing something here i.e. is there a standard approach that requires you to use a for loop when you want to compare user's input and then perform given tasks to receive the desiredoutput? Note: I'm not posting this to prove a point to somebody who is just following what they have done for the past few years, as I am learning and I might be wrong and I would like to know why.
tagged with: python
has title: What Is The Best Practice When it Comes To Determining and Counting Odd and Even Numbers in python
favorite count: 0
has answer: http://stackoverflow.com/a/49072032
downvote count: 1
has comment: http://stackoverflow.com/comment/85151746
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49072124
accepted answer: http://stackoverflow.com/a/49072032
score: -1

http://stackoverflow.com/comment/85219257
type: QuestionComment
has text: Possible duplicate of [Why can't Python increment variable in closure?](https://stackoverflow.com/questions/21959985/why-cant-python-increment-variable-in-closure)
type: Comment
comment on: http://stackoverflow.com/q/49106871
score: 0

http://stackoverflow.com/comment/85141353
type: Comment
comment on: http://stackoverflow.com/q/49068153
type: QuestionComment
has text: Note that you don't need the `i` variable here. The `for` loop does the iteration.
score: 0

http://stackoverflow.com/q/48977688
accepted answer: http://stackoverflow.com/a/48977787
type: AnsweredQuestion
has body: I've created a script for my school project that works with data. I'm quite new to working remotely on a server, so this might seem like a dumb question, but how do I execute my script named stats.py so that it continues executing even after I log off PuTTy? The script file is located on the server. It has to work with a lot of data, so I don't want to just try something and then few days later find out that it has exited right after I logged off. Thank you for any help!
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84960505
score: 0
has answer: http://stackoverflow.com/a/48977787
has title: How to run a python script on a remote server that it doesn't quit after I log off?
answer count: 1
tagged with: putty
tagged with: server

http://stackoverflow.com/comment/88028416
has text: where did u put this call()? before training or before predicting using pretrained weigths?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49019472

http://stackoverflow.com/comment/84948687
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48971745
has text: Also, SO is not a free coding site. What have *you* tried?
score: 1

http://stackoverflow.com/comment/85073729
has text: @LouisSugy Well, considering he knew about the existence of raw strings (since the pattern was raw) for dealing with backspaces, I considered this question more of the "off topic because typo" type. The topic of raw strings is already well covered here, and I don't see this being a likely landing spot for others searching for similar issues.
comment on: http://stackoverflow.com/q/49030188
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49067236
tagged with: create-table
tagged with: python
tagged with: apache-nifi
has comment: http://stackoverflow.com/comment/85219892
has answer: http://stackoverflow.com/a/49140579
type: UnansweredQuestion
has title: Read Avro file with python to create a SQL table
upvote count: 1
type: Question
has body: I'm trying to create an SQL table from AVRO file which contains the structure of my table : { "type" : "record", "name" : "warranty", "doc" : "Schema generated by Kite", "fields" : [ { "name" : "id", "type" : "long", "doc" : "Type inferred from '1'" }, { "name" : "train_id", "type" : "long", "doc" : "Type inferred from '21691'" }, { "name" : "siemens_nr", "type" : "string", "doc" : "Type inferred from 'Loco-001'" }, { "name" : "uic_nr", "type" : "long", "doc" : "Type inferred from '193901'" }, { "name" : "Configuration", "type" : "string", "doc" : "Type inferred from 'ZP28'" }, { "name" : "Warranty_Status", "type" : "string", "doc" : "Type inferred from 'Out_of_Warranty'" }, { "name" : "Warranty_Data_Type", "type" : "string", "doc" : "Type inferred from 'Real_based_on_preliminary_acceptance_date'" }, { "name" : "of_progression", "type" : "long", "doc" : "Type inferred from '100'" }, { "name" : "Delivery_Date", "type" : "string", "doc" : "Type inferred from '18/12/2009'" }, { "name" : "Warranty_on_Delivery_Date", "type" : "string", "doc" : "Type inferred from '18/12/2013'" }, { "name" : "Customer_Status", "type" : "string", "doc" : "Type inferred from 'homologation'" }, { "name" : "Commissioning_Date", "type" : "string", "doc" : "Type inferred from '6/10/2010'" }, { "name" : "Preliminary_acceptance_date", "type" : "string", "doc" : "Type inferred from '6/01/2011'" }, { "name" : "Warranty_Start_Date", "type" : "string", "doc" : "Type inferred from '6/01/2011'" }, { "name" : "Warranty_End_Date", "type" : "string", "doc" : "Type inferred from '6/01/2013'" }, { "name" : "Effective_End_Warranty_Date", "type" : [ "null", "string" ], "doc" : "Type inferred from 'null'", "default" : null }, { "name" : "Level_2_in_function", "type" : "string", "doc" : "Type inferred from '17/07/2015'" }, { "name" : "Baseline", "type" : "string", "doc" : "Type inferred from '2.10.23.4'" }, { "name" : "TC_report", "type" : "string", "doc" : "Type inferred from 'A480140'" }, { "name" : "Last_ver…
score: 1
has comment: http://stackoverflow.com/comment/85182099
tagged with: avro
tagged with: sql
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/86819323
has text: PyGaze is using PsychoPy and I already searched that way. I think it has to do because of the license but I'm not sure. (Anyway, for me it is too late to solve that problem :/)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49011362

http://stackoverflow.com/q/49023222
has comment: http://stackoverflow.com/comment/85051940
tagged with: pandas
has answer: http://stackoverflow.com/a/49023259
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49023259
has comment: http://stackoverflow.com/comment/85053541
tagged with: python
has comment: http://stackoverflow.com/comment/85052931
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85054757
has comment: http://stackoverflow.com/comment/85052328
has comment: http://stackoverflow.com/comment/85051275
upvote count: 2
has body: I have a pandas.Series named matches like this: When I called pandas.Series.str.get method on it, it returns a new Series with its values all NaN: I have read the document pandas.Series.str.get, but still can't understand it.
type: Question
has comment: http://stackoverflow.com/comment/85052145
has title: how does pandas.Series.str.get method work?

http://stackoverflow.com/q/48963935
downvote count: 3
accepted answer: http://stackoverflow.com/a/48966105
upvote count: 1
tagged with: date
type: Question
has comment: http://stackoverflow.com/comment/84935631
has body: I am creating a python app (DASH app) check what is dash here (https://youtu.be/5BAthiN0htc) and I would like insert Today's DATE and TIME. Could you please help me on adding it to my app? Thanks,
tagged with: plotly-dash
score: -2
has title: How to insert today's Date and Time on Dash App (Python Framework)
has comment: http://stackoverflow.com/comment/84937860
has comment: http://stackoverflow.com/comment/84935742
has comment: http://stackoverflow.com/comment/84937912
has comment: http://stackoverflow.com/comment/84937495
answer count: 1
has comment: http://stackoverflow.com/comment/84933817
has comment: http://stackoverflow.com/comment/84933636
has answer: http://stackoverflow.com/a/48966105
linked to: http://stackoverflow.com/q/415511
favorite count: 0
has comment: http://stackoverflow.com/comment/84935585
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/84933927
type: AnsweredQuestion

http://stackoverflow.com/q/49056702
has answer: http://stackoverflow.com/a/49057691
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49057691
tagged with: pip
type: Question
possible better answer: http://stackoverflow.com/a/49056817
has answer: http://stackoverflow.com/a/49056817
has title: Pip installing wrong version on win7,
tagged with: python-2.7
score: 0
answer count: 2
tagged with: package
has body: I have a package that I am trying to install via pip install allen-bradley-toolkit. The package is failing with the following reason. The problem seems to related to the fact that pip is trying to install 1.0a1.post0 instead of the latest release version 2.0.0. Does anyone have any ideas on what to do about this. Perhaps there is something wrong in my deployment script. You can view the Github Library here to see how I am deploying to PyPi. There is an issue opened on the GitHub Tracker #2 that you can also reference for more info. NOTE: The package seems to install fine on my win10 machine. But I am unable to get it to install on a win7 VM. Ive also tried installing with the following commands: pip install --no-cache-dir allen-bradley-toolkit pip install allen-bradley-toolkit==2.0.0 -> this ones throws a 'doesnt exist error`
tagged with: python

http://stackoverflow.com/comment/85420112
has text: Thanks for the solution, I can see that it is a nice variation to the original question's answer. @AdamSmith, most probably I am one of contributors to the under-use of OOP in python.
type: Comment
comment on: http://stackoverflow.com/a/49121427
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85230794
type: AnswerComment
comment on: http://stackoverflow.com/a/49112389
score: 0
type: Comment
has text: At least on my machine the plain Python way is faster than this. Probably due to the overhead of reading the data in to the dataframe first.

http://stackoverflow.com/comment/84964666
comment on: http://stackoverflow.com/q/48979658
type: QuestionComment
has text: @ely By the way, your example really gave me a better insight. The fact that the error will be somewhat proportional to the data set I am using. Thank you.
score: 0
type: Comment

http://stackoverflow.com/a/49135520
score: 0
type: Answer
has body: I don't quite understand. Would this work for you? try: mymodule.foo() except: print("whatever you wanted to do")
upvote count: 1
has comment: http://stackoverflow.com/comment/85277593
has comment: http://stackoverflow.com/comment/85315303
answers question: http://stackoverflow.com/q/49084154
downvote count: 1

http://stackoverflow.com/comment/85175734
type: AnswerComment
comment on: http://stackoverflow.com/a/49085084
score: 0
type: Comment
has text: I get this error:

http://stackoverflow.com/a/49035128
has body: I believe the path to jquery should be /templates/jquery-3.3.1.js On me flask server when i serve jquery it has the full path from the home directory: /static/js/jquery.min.js
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49035043

http://stackoverflow.com/q/49120112
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49120189
type: Question
has answer: http://stackoverflow.com/a/49120189
has title: Grouping and counting data by several columns in Pandas
score: 0
tagged with: pandas
answer count: 1
has body: I have the following dataframe: ks2_question1_cat_df = ks2_question1_df'Results_Disadvantaged', 'Results_Advantaged' It contains just two columns with some text categories as follows: Results_Disadvantaged Results_Advantaged 0 Above Standard Above Standard 1 Below Standard Above Standard 2 Above Standard Above Standard [...] I would like to pivot these columns to have something like this: Above Standard Below Standard 0 Results_Disadvantaged 6530 334 1 Results_Advantaged 5532 555 [...] I tried using a crosstab: pd.crosstab(ks2_question1_df['Results_Disadvantaged'],ks2_question1_df['Results_Advantaged']) But the output is not quite what I'm looking for: Results_Advantaged Above Standard Below Standard Results_Disadvantaged Above Standard 6104 84 Below Standard 2803 489
tagged with: python

http://stackoverflow.com/comment/85271399
score: 0
type: Comment
has text: Hi. It doesn't work. I set trainable to False in all layers before accessing them with get_layer , but I'm still getting the same shape problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/49121612

http://stackoverflow.com/a/49084270
score: 2
has body: Use word breaks (\b) in your regular expression. import re strings_to_search = ['abc', 'def', 'fgh hello'] complete_list = ['abc abc dsss abc', 'defgj', 'abc fgh hello xabd', 'fgh helloijj'] for col_key in strings_to_search: word = r'\b{}\b'.format(col_key) print(list(map(lambda x: re.findall(word, x), complete_list))) Output: [['abc', 'abc', 'abc'], [], ['abc'], []] [[], [], [], []] [[], [], ['fgh hello'], []]
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49084198

http://stackoverflow.com/comment/85059752
comment on: http://stackoverflow.com/a/49026963
has text: Since a seaborn heatmap is nothing else than a `pcolormesh` plot, there shouldn't be any difference. In case you need something specific in your heatmap, it may make sense to ask specifically about this desired feature.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84940911
score: 0
comment on: http://stackoverflow.com/a/48964455
type: AnswerComment
has text: i see the coordinates in the console on chrome, but how do i get the data
type: Comment

http://stackoverflow.com/a/49085725
type: AcceptedAnswer
has body: You can use an if-statement here by checking that the file name is not equal (!=) to "DS_Store": class MySentences(object): def __init__(self, dirname): self.dirname = dirname def __iter__(self): for fname in os.listdir(self.dirname): if fname != '.DS_Store': for line in open(os.path.join(self.dirname, fname)): yield line.split() If the filename does equal this string, then that loop is simply passed-over without the nested for statement being touched.
type: Answer
accepted answer of: http://stackoverflow.com/q/49083791
score: 0
answers question: http://stackoverflow.com/q/49083791

http://stackoverflow.com/a/63717263
type: Answer
answers question: http://stackoverflow.com/q/49084143
has body: Late answer, but for those looking for live video transmission and reception over socket: Here is the snapshot of results: server.py import socket, cv2, pickle,struct # Socket Create server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print('HOST IP:',host_ip) port = 9999 socket_address = (host_ip,port) # Socket Bind server_socket.bind(socket_address) # Socket Listen server_socket.listen(5) print("LISTENING AT:",socket_address) # Socket Accept while True: client_socket,addr = server_socket.accept() print('GOT CONNECTION FROM:',addr) if client_socket: vid = cv2.VideoCapture(0) while(vid.isOpened()): img,frame = vid.read() a = pickle.dumps(frame) message = struct.pack("Q",len(a))+a client_socket.sendall(message) cv2.imshow('TRANSMITTING VIDEO',frame) key = cv2.waitKey(1) & 0xFF if key ==ord('q'): client_socket.close() client.py import socket,cv2, pickle,struct # create socket client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_ip = '192.168.1.20' # paste your server ip address here port = 9999 client_socket.connect((host_ip,port)) # a tuple data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) # 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) cv2.imshow("RECEIVING VIDEO",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break client_socket.close()
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/comment/85192832
comment on: http://stackoverflow.com/a/49090981
score: 0
type: Comment
has text: Thanks it was an issue with the numpy! Given that np.array was made of strs, no lists were generated so that was in fact the problem!
type: AnswerComment

http://stackoverflow.com/comment/85231520
type: Comment
type: QuestionComment
score: 0
has text: Its solved arleady - the `'\t'` is missing its `'\'` - @bipll found it and answered .... so the `writer` uses `t` as delimiter - simple typo
comment on: http://stackoverflow.com/q/49113109

http://stackoverflow.com/comment/85170973
comment on: http://stackoverflow.com/a/49082797
type: AnswerComment
score: 0
type: Comment
has text: Yeah you are working on the index of the list, that's smart!

http://stackoverflow.com/q/49085106
has answer: http://stackoverflow.com/a/62407810
upvote count: 3
has comment: http://stackoverflow.com/comment/85175598
accepted answer: http://stackoverflow.com/a/49085250
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/71977777
tagged with: closures
has answer: http://stackoverflow.com/a/49085250
possible better answer: http://stackoverflow.com/a/61987139
has answer: http://stackoverflow.com/a/63563156
has answer: http://stackoverflow.com/a/61987139
has body: I am trying to write a closure with two inner functions, but I am getting the below error def factory(n=0): #n=0 def current(): return n return current def counter(): n=n+1 return n return counter f_current,f_counter = int(input()) print(f_counter()) print(f_current()) I have the below error: &gt;&gt;4 Traceback (most recent call last): File "C:/Users/lokesh/Desktop/python/closure3.py", line 13, in &lt;module&gt; f_current,f_counter = int(input()) TypeError: 'int' object is not iterable My requirement is after giving input 4,it should display: 4 5 I am new to python, can somebody help me here... thanks in advance
has title: closures with two inner functions python
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/85175536
has comment: http://stackoverflow.com/comment/85175635
tagged with: python
has comment: http://stackoverflow.com/comment/85175481
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/49044835
upvote count: 2
has title: configparser parse string as unicode in python2
has comment: http://stackoverflow.com/comment/85177471
tagged with: python
has body: I am parsing a file with ini format using configparser module in python 2. I am using configparser instead of ConfigParser so that code is compataible with python 3. Problem that with python 2 parsed "value " is coming as unicode string as u'value'. Please note that with python 3 parsed value is same as python2 if I would use ConfigParser instead. Is there a way to resolve this? Sample config file: $ cat test_config [test] field = value Python run $ python Python 2.7.14 (default, Nov 2 2017, 17:39:03) &gt;&gt;&gt; import configparser &gt;&gt;&gt; config_name = "test_config" &gt;&gt;&gt; &gt;&gt;&gt; config_parser = configparser.SafeConfigParser() &gt;&gt;&gt; config_parser.optionxform = str &gt;&gt;&gt; config_parser.read(config_name) &gt;&gt;&gt; config = {} &gt;&gt;&gt; mode = 'test' &gt;&gt;&gt; for item_tuple in config_parser.items(mode): ... config[item_tuple[0]] = item_tuple[1] ... &gt;&gt;&gt; print(config['field']) value &gt;&gt;&gt; config['field'] u'value' &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/85177969
has comment: http://stackoverflow.com/comment/85102926
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: unicode
has comment: http://stackoverflow.com/comment/85102866
tagged with: python-2.7
type: Question
score: 2
has comment: http://stackoverflow.com/comment/85177463
favorite count: 0
has comment: http://stackoverflow.com/comment/85094407
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85192830

http://stackoverflow.com/comment/85153435
score: 0
type: Comment
type: QuestionComment
has text: In any case, GDAL certainly works in python 3.6 as well. How did you install geopandas, fiona, gdal?
comment on: http://stackoverflow.com/q/49040025

http://stackoverflow.com/q/49006033
type: Question
has comment: http://stackoverflow.com/comment/85017024
downvote count: 0
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
has title: Minimize confidence interval usign scipy minimize
has comment: http://stackoverflow.com/comment/85016685
score: 1
has body: My goal is to find shortest interval where area under my probability density function equals to 0.2. My PDF is definite on interval [x_min, x_max]. That means, that i want to minimize function lambda x: x[1] - x[2] satisfying this conditions: 1] x_max - x[1] >= 0 2] x[0] - x_min >= 0 3] integrate(PDF) from x[0] to x[1] - 0.2 = 0 here is my code: from math import exp, log from scipy.stats import logistic, norm import numpy as np from scipy.integrate import quad from scipy.optimize import minimize ###################functions################# #pdf function for logit def pdf1(x_i, intercept, coef, x0): a = (exp(intercept)*coef*((x_i + x0)**(coef - 1)))/(((exp(intercept)* ((x_i+x0)**coef)) + 1)**2) return a #pdf function for logistic distribution def pdf2(x_i, mi, s): return logistic.pdf(x_i, mi, s) #pdf function for normal distribution def pdf3(x_i, loc, scale): return norm.pdf(x_i, loc = loc, scale = scale) def pdf_point(x, p, const, params_logit, params_logistic, params_gauss): p1, p2 = p intercept, coef, x0 = params_logit mi, s = params_logistic loc, scale = params_gauss a = const*(p1 * pdf1(x, intercept, coef, x0) + p2* pdf2(x, mi, s) + (1 - p1 - p2)*pdf3(x, loc, scale)) return a def integrate_pdf(x, p, const, params_logit, params_logistic, params_gauss): x1, x2 = x return quad(pdf_point, x1, x2, args = (p, const, params_logit, params_logistic, params_gauss)) - 0.2 #############parameters############# p = [ 0.22215561, 0.77784439] const = 1.1514406903526164 params_logit = [-654.14149905436966, 109.50138530596364, 362.80446670967461] params_logistic = (32.96514363428475, 2.8362675341927019) params_gauss = (32.12488888888889, 5.4151936960216025) mi = 18.0 ma = 38.399999999999999 ##############code for my goal############## con = ({"type" : "eq","fun" : integrate_pdf, "args" : (p, const, params_logit, params_logistic, params_gauss)}, {"type" : "ineq", "fun" : lambda x : x[0] - mi},{"type" : "ineq", "fun" : lambda x: ma - x[1]}) b = minimize(lambda x: x[1] - x[0], [1,1…
tagged with: scipy

http://stackoverflow.com/comment/85052695
type: AnswerComment
comment on: http://stackoverflow.com/a/48984966
has text: Hi @Giorgio I am able to use docker network to talk between the containers, but still unable to route requests to the specific container based on the URL. Second thing is, I have health-check for both the services. How can I access the /health url on both services?
type: Comment
score: 0

http://stackoverflow.com/q/48996361
tagged with: turtle-graphics
downvote count: 1
type: Question
has body: I wrote this code in python to learn polymorphism. I made a file paint2.txt which has some turtle commands in it as follows (numbers are to show width of pen, circle radius and x,y coordinate for goto): pendown beginfill black circle 20 3 black endfill goto 120 0 1 red beginfill green circle 20 3 yellow endfill penup and this code reads those commands from the file and tries to parse and run them: import turtle class GoToCommand: def __init__(self, x, y, width=1, color='balck'): self.x = x self.y = y self.width = width self.color = color def draw(self,turtle1): turtle1.width(self.width) turtle1.pencolor(self.color) turtle1.goto(self.x,self.y) class CircleCommand: def __init__(self, radius, width=1, color='black'): self.radius = radius self.width = width self.color = color def draw(self, turtle1): turtle1.pencolor = self.color turtle1.width = self.width turtle1.circle(self.radius) class BeginFillCommand: def __init__(self,color='black'): self.color = color def draw(self,turtle1): turtle1.fillcolor = self.color turtle1.begin_fill() class EndFillCommand: def __init__(self): pass def draw(self,turtle1): turtle1.end_fill() class PenUpCommand: def __init__(self): pass def draw(self,turtle1): turtle1.penup() class PenDownCommand: def __init__(self): pass def draw(self,turtle1): turtle1.pendown() class PyList: def __init__(self): self.items=[] def append(self,item): self.items = self.items + [item] def __iter__(self): for c in self.items: yield c def main(): t = turtle.Turtle() screen = t.getscreen() GraphicsCommands = PyList() # paint2.txt is my made up file with turtle commands file = open ('paint2.txt','r') line = file.readline() while line != '': line = line.strip() if line == 'goto': x = int(file.readline().strip()) y = int(file.readline().strip()) width = int(file.readline().strip()) color = file.readline().strip() cmd = GoToCommand(x,y,width,color) elif line == 'beginfill': color = file.readline().strip() cmd = BeginFillCommand(color) elif line == 'pendown': cmd = Pe…
has comment: http://stackoverflow.com/comment/84998560
has title: what is wrong with my turtle python
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48997285
type: UnansweredQuestion
tagged with: python
score: -1

http://stackoverflow.com/q/49056200
downvote count: 1
accepted answer: http://stackoverflow.com/a/49057937
has comment: http://stackoverflow.com/comment/85116973
type: Question
has comment: http://stackoverflow.com/comment/85120357
has title: How do I manipulate a multi dimension array in a python not using a library?
has comment: http://stackoverflow.com/comment/85119943
has answer: http://stackoverflow.com/a/49057937
has comment: http://stackoverflow.com/comment/85117271
score: 0
has comment: http://stackoverflow.com/comment/85117135
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I have this method: def encode(message, rails): result = "" dataRails = [] activeRail = 0 # allocate multi-dimensional array...seems inefficient for r in range(rails): dataRails.append([]) # copy characters from message into one of the arrays, or . for m in message: count = 0 # for each rail either give it the character or a . while count &lt;= rails: print("Count: ", str(count), " Active Rail:", str(activeRail)) if activeRail == count: dataRails[activeRail][count] = m else: dataRails[activeRail][count] = "." count += 1 activeRail += 1 if activeRail &gt;= rails: activeRail = 0 for r in dataRails: print(r) # ill calculate result once I get the above right return result Message is a string of text. Rails is a number. The encode method would be called like this: encode('XOXOXOXOXOXOXOXOXO', 2) In this case, I want to allocate my dataRails as 2 elements, each the same length as input message. I would replace elements in the arrays with either a letter from message or a ".". But, it seems rather inefficient to use a loop to allocate dataRails. When I run this, I get the following error: dataRails[activeRail][count] = m IndexError: list assignment index out of range The print statement looks like valid index values: Count: 0 Active Rail: 0 It feels like there are two problems with my multi-dimensional array. 1) allocation and 2) access. If there is a duplicate question, please post a link. I searched through stackoverflow. Answers that seemed relevant relied on a library, which I did not want to use. I have just started learning python and want to learn the basics of python, not using libraries. Are arrays really that difficult in python or did I make it more difficult than it needs to me? Thanks Matt Edit: Ultimately, if the message input was this "WE ARE DIS", the return of this method would be "WEERDSAI". I am working through a tutorial on exercism.io. I haven't completed the method yet. I am stuck on the array I defined.
upvote count: 1

http://stackoverflow.com/comment/85190075
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49092206
has text: in the `INSTALLED_APPS ` try `server. kleis` instead of `kleis` and see if it works.
score: 0

http://stackoverflow.com/q/49085230
has comment: http://stackoverflow.com/comment/86128840
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49579166
has comment: http://stackoverflow.com/comment/85642665
upvote count: 3
tagged with: django-celery
tagged with: celery
type: Question
possible better answer: http://stackoverflow.com/a/52575655
has answer: http://stackoverflow.com/a/52575655
answer count: 2
has answer: http://stackoverflow.com/a/49579166
has title: django-celery : TypeError: can only concatenate tuple (not "NoneType") to tuple
downvote count: 0
has body: I have recently started using rabbitmq and celery with django. i am using django-celery, django-celery-email and post office to send emails in async way. After installing all these packages my settings.py looks like INSTALLED_APPS = [ #other apps 'djcelery', 'djcelery_email', 'post_office' ] # setup celery import djcelery djcelery.setup_loader() # using post office as the default email backend EMAIL_BACKEND = 'post_office.EmailBackend' # using djcelery's email backend as a backend for post office POST_OFFICE_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' POST_OFFICE = { 'DEFAULT_PRIORITY' : 'now' } EMAIL_HOST = 'YOUR_HOST_NAME' EMAIL_HOST_USER = "YOUR_HOST_USER_NAME" EMAIL_PORT = 25 # default smtp port EMAIL_HOST_PASSWORD = "YOUR_HOST_USER_PASSWORD" EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'testing@example.com' when i am trying to run django-celery via command **python manage.py celeryd** It is throughing below error Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/ubuntu/edyodavirtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/ubuntu/edyodavirtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/edyodavirtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 206, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/ubuntu/edyodavirtual/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/ubuntu/edyodavirtual/local/lib/python2.7/site-packages/djcelery/management/commands/celeryd.py", line 16, in &l…

http://stackoverflow.com/comment/85211934
comment on: http://stackoverflow.com/q/49102849
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc: I updated the answer with an example, as minimal as possible, thank you. @scopchanov I could understand that, my question is not really about "how to fix it" (I can easily understand it), but *why*. I get that a signal calling an QUndoCommand should (could?) not be the same as the slot that the command calls, but, I still don't understand the necessity of executing the command after a `push`.

http://stackoverflow.com/comment/85173701
has text: why are you writing print statement? it won't work in kodi. also note that in kodi stable releases up until now they are using python2; and for any other functionalities like beautifulsoup, requests you need to install addon for that too. mostly try to encode string with .encode('utf-8'), if it won't work you can use exception case handling for it.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49037564
type: QuestionComment

http://stackoverflow.com/q/48971720
has body: Let's say I have a = [1,2,3,4,5] I'm trying to create a dictionary where dictObj = { (key,[]) for key in a} but I'm getting an unhashable type error. This seems weird to me since it's fine if values are lists right? I was wondering if anyone could tell me the correct syntax for creating a hash table where all the keys are the elements in a and each key points to an empty array.
tagged with: dictionary-comprehension
has comment: http://stackoverflow.com/comment/84948651
favorite count: 0
has comment: http://stackoverflow.com/comment/84948703
answer count: 3
tagged with: python
tagged with: dictionary
has title: Create a Dictionary with List Values through a Dict Comprehension?
has comment: http://stackoverflow.com/comment/84948635
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84948631
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84948731
has answer: http://stackoverflow.com/a/48971738
has answer: http://stackoverflow.com/a/48971790
score: 2
has answer: http://stackoverflow.com/a/48971737
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/84948604

http://stackoverflow.com/comment/85099293
score: 0
has text: Python doesn't keep track of where an instance was instantiated. If you need such functionality, you have to implement it yourself (e.g. by passing the module to the constructor). That said, I really can't imagine a reason why anyone would need to do this. Sounds like a code smell to me.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49047336

http://stackoverflow.com/q/49085445
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49085495
accepted answer: http://stackoverflow.com/a/49085495
tagged with: python-3.x
has title: Python 3.4 - Pandas - Extract Rows Based on Column of another Dataframe Including Duplicates
has body: I have two input dataframes in the format of: Word colA colB colC ID python A B C 1 word D E F 1 of G H I 1 python J K L 2 is M N O 2 of P Q R 3 and another one in the format of: V1 V2 V3 V4 the 0.1 0.2 0.3 python 0.4 0.5 0.6 excel 0.6 0.7 0.8 is 0.9 0.10 0.6 access 0.7 0.5 0.6 of 0.5 1.2 7.8 tell 0.9 3.2 4.5 pandas 0.5 0.4 0.3 Lets call the first dataframe df1 and the second one df2. I want to know how to subset df2, based on V1, that have the same terms as df1['Word']. If the term in V1 has no matches in df1['Word'], I would like the rows to be filled with zeros. Also, another key point is that I would like to INCLUDE duplicates. I would also like to copy the 'ID' column to the df2 dataframe. My expected output would be in this format: V1 V2 V3 V4 ID python 0.4 0.5 0.6 1 word 0.0 0.0 0.0 1 of 0.5 1.2 7.8 1 python 0.4 0.5 0.6 2 is 0.9 0.10 0.6 2 of 0.5 1.2 7.8 3 I am able to successfully identify and subset terms in the output dataframe without the duplicates showing. But including duplicates of terms has provided to be somewhat of a challenge to me. I would also need help in successfully copying the df1['ID'] column to the end of the output dataframe as well. I would appreciate any help that I can get. Thanks.
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/85126866
has text: Unfortunately I get the same results when using that `sort_values()` call as well. Maybe I did something wrong in my melt of the original 31 day columns that carried over into the `pd.to_datetime()` to make the resulting datetimes only sortable on the month? When I look at the `df.info()` output it shows the day column as an object, so maybe I need to somehow convert the column to integer before calling `pd.to_datetime()`?
type: Comment
comment on: http://stackoverflow.com/a/49059794
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84952064
type: QuestionComment
has text: Hi @SunnysinhSolanki, thanks for your comment. I'm happy with removing the values but I want to be able to preserve their position and put the NaNs back in once I've calculated the probabilities? Otherwise my gridded array won't be correct.
score: 0
comment on: http://stackoverflow.com/q/48973468
type: Comment

http://stackoverflow.com/comment/85120454
comment on: http://stackoverflow.com/a/49057144
score: 1
type: AnswerComment
type: Comment
has text: `n > m` can still lead to `True`, think of s1 being ['a', 'ab'] and s2 being ['ab']. And the complexities are ignoring the cost of comparing strings during sorting and in `startswith`, though I guess with "normal words" as input that's negligible (they'll differ early).

http://stackoverflow.com/comment/85031532
has text: Do you mean something like [numpy.absolute](https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html)? (It has a shorter alias: `numpy.abs`.)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48995278
type: Comment

http://stackoverflow.com/a/49060303
has body: You first want to get a list of all unique strings in fileA. Then get a similar unique list for fileB. Then compare the two. Using set's makes the comparison easier. def get_strings_from_file(f): return set([s.strip() for s in f.read().split() if s.strip()]) def main(): with open("fileA.txt", 'r') as fileA, open ("fileB.txt") as fileB: stringsA = get_strings_from_file(fileA) stringsB = get_strings_from_file(fileB) return stringsA.intersection(stringsB)
answers question: http://stackoverflow.com/q/49060184
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85128617
type: Answer
upvote count: 1

http://stackoverflow.com/comment/85079100
score: 1
comment on: http://stackoverflow.com/q/49036969
type: Comment
type: QuestionComment
has text: @jpp now edited.

http://stackoverflow.com/comment/85067194
type: Comment
has text: You're welcome. Appreciated the clean code and hence felt no barrier to give a PR :)
score: 0
comment on: http://stackoverflow.com/a/49031025
type: AnswerComment

http://stackoverflow.com/comment/85157085
type: QuestionComment
has text: What exactly are you hoping to do?
score: 0
comment on: http://stackoverflow.com/q/49073842
type: Comment

http://stackoverflow.com/comment/85085493
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49039985
type: Comment
has text: @jonrsharpe I see! Now I'm understanding.

http://stackoverflow.com/comment/85126616
comment on: http://stackoverflow.com/a/49055725
score: 0
type: AnswerComment
has text: I'm taking it set by step thus far, I ran the script in the browser and it outputs "Ok" but it doesn't seem like it actually did what it normally does in the terminal.
type: Comment

http://stackoverflow.com/q/49061066
accepted answer: http://stackoverflow.com/a/49061301
tagged with: python
tagged with: void
type: AnsweredQuestion
has body: I have a large numpy void array loaded from a matlab struct. I can access the arrays stored inside the main array, but accessing their shape returns '()'. Accessing their length returns the error: len() of unsized object. Is there a way for me to access the shape of the sub-arrays? arr = scipy.io.loadmat('mymatfile.mat', squeeze_me=True) sub_arr = arr['a'][0]['b']['c'] print(sub_arr) print(sub_arr.shape) print(len(sub_arr)) returns: [[0 0 0 0] [0 0 0 0]] () TypeError: len() of unsized object Solution: sub_arr.item() returns a sized array
score: 1
upvote count: 1
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/49061301
tagged with: numpy
has title: Array stored in numpy void returns no shape/length
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48972164
accepted answer: http://stackoverflow.com/a/48972174
downvote count: 0
tagged with: join
score: 1
has answer: http://stackoverflow.com/a/48972174
type: AnsweredQuestion
has title: Join a Pandas dataframe with dataframe of lists
tagged with: dataframe
type: Question
tagged with: pandas
upvote count: 1
has body: As illustrated below, I have two panda dataframes that I want to combine. The first holds information on a huge number of products. The second holds the information of the category of the product where each entry in the category column is a list. CatId Date CatId CatName 0 C2 01-15 0 C1 [crime, alt] 1 C1 01-15 1 C2 [crime, bests] 2 C1 01-15 2 C3 [fantasy, american] 3 C3 01-16 . . n C2 02-17 I am interested in the following dataframe: CatId Date 0 [crime, bests] 01-15 1 [crime, alt] 01-15 2 [crime, alt] 01-15 3 [fantasy, american] 01-16 . . n [crime, bests] 02-17 For efficiency (due to the size of the dataset) I try to avoid looping. Is it possible in Python?
answer count: 1
favorite count: 0
tagged with: spyder
tagged with: python

http://stackoverflow.com/a/48991520
type: Answer
score: 2
upvote count: 2
has body: you may can use setsid. use this code process = Popen(['setsid', '/usr/sbin/nginx', '-c', '/etc/nginx/nginx.conf']) man setsid for more info
has comment: http://stackoverflow.com/comment/84987945
has comment: http://stackoverflow.com/comment/85019084
downvote count: 0
has comment: http://stackoverflow.com/comment/85011497
answers question: http://stackoverflow.com/q/48991249

http://stackoverflow.com/a/49060177
has body: Don't forget that in Python, variables are references to values. The iteration variable is a variable, so assigning a new value to this variable do not change the iterable. In this case, why not use lists comprehensions ? import numpy as np my_list = [one, two, three] my_list = [np.column_stack([arr,5*arr[:,2]-arr[:,1])]) for arr in list] And please, don't shadow listtype…
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49059917

http://stackoverflow.com/comment/85203707
score: 0
type: Comment
type: QuestionComment
has text: graphviz pip install graphviz
comment on: http://stackoverflow.com/q/49091644

http://stackoverflow.com/a/48981824
answers question: http://stackoverflow.com/q/48981749
score: 1
has body: You are mixing up the notation for columns and rows. You print O[:,UP] which gives you all the rows and just the "UP"th column (index 0). Your O is: array([[ 0.7, 0.1, 0.2], [ 0.1, 0.6, 0.3], [ 0.3, 0.3, 0.4]]) And O[:,0] is #↓ this column array([[ 0.7, 0.1, 0.2], [ 0.1, 0.6, 0.3], [ 0.3, 0.3, 0.4]]) where O[0,:] would be array([[ 0.7, 0.1, 0.2], #This row [ 0.1, 0.6, 0.3], [ 0.3, 0.3, 0.4]]) And just to make the last part clear, O[:,UNCHANGED] is O[:,2] which is here: #↓ this column array([[ 0.7, 0.1, 0.2], [ 0.1, 0.6, 0.3], [ 0.3, 0.3, 0.4]])
has comment: http://stackoverflow.com/comment/84968798
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84968832
type: Answer
accepted answer of: http://stackoverflow.com/q/48981749
upvote count: 1

http://stackoverflow.com/q/49078761
tagged with: python
type: UnansweredQuestion
tagged with: django
has title: Django login after registration
has answer: http://stackoverflow.com/a/49078835
has body: Im' trying to auto login the user after registration but anything seems to work. Does not work: if registroForm.is_valid(): registroForm.save() user = authenticate(username=registroForm.cleaned_data['username'], password=registroForm.cleaned_data['password1']) request.session['_auth_user_id'] = user.pk request.session['_auth_user_backend'] = user.backend return JsonResponse({}) Does not work: if registroForm.is_valid(): registroForm.save() usuario = authenticate(username=registroForm.cleaned_data['username'], password=registroForm.cleaned_data['password1']) login(request, usuario) return JsonResponse({}) I'm using Django 2.0
type: Question
score: 0
answer count: 1

http://stackoverflow.com/comment/85082813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49038432
score: 1
has text: What I'm suggesting is that for two bodies, you ought to be able to reason about the behaviour on a frame-by-frame basis (you could even compute it by hand) - does everything move in the correct direction in, say, the first frame?

http://stackoverflow.com/comment/84965440
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48979045
has text: Separate note: your protocol is entirely flawed; use TLS 1.2. There is trust in the public key, no authentication of messages and you're vulnerable to padding oracle attacks, to name just some issues.
score: 0

http://stackoverflow.com/q/48999413
has answer: http://stackoverflow.com/a/49000135
score: 0
has body: Using a Raspberry Pi with Raspbian GNU/Linux 9, on a Marty Robot, having installed the Google Assistant SDK as described on the official page https://developers.google.com/assistant/sdk/guides/library/python/ Trying to execute the last step: https://developers.google.com/assistant/sdk/guides/library/python/embed/run-sample I expect it to work, simply to work. But I've got the following Error: (env) pi@martina:~ $ googlesamples-assistant-hotword --project_id "martinaaiy" --device_model_id "Martina" device_model_id: Martina device_id: 8375BDBA056A04CCB8EBDAF685DC07B5 https://embeddedassistant.googleapis.com/v1alpha2/projects/martinaaiy/devices/8375BDBA056A04CCB8EBDAF685DC07B5 403 [6130:6148:ERROR:assistant_nupnp_client.cc(103)] Cloud discovery nupnp request failed: [60] Peer certificate cannot be authenticated with given CA certificates [6130:6148:ERROR:assistant_nupnp_client.cc(103)] Cloud discovery nupnp request failed: [60] Peer certificate cannot be authenticated with given CA certificates ON_MUTED_CHANGED: {'is_muted': False} ON_START_FINISHED [6130:6148:ERROR:assistant_nupnp_client.cc(103)] Cloud discovery nupnp request failed: [60] Peer certificate cannot be authenticated with given CA certificates Any help will be welcome.
answer count: 1
tagged with: google-assistant-sdk
type: UnansweredQuestion
tagged with: python
has title: Google Assistant on Raspberry Pi 3 - Running sample code - error Peer certificate cannot be authenticated with given CA certificates
type: Question
tagged with: raspberry-pi3
tagged with: ssl-certificate

http://stackoverflow.com/q/49020321
has title: One-to-one relationship DB Model not working
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49020421
tagged with: flask-sqlalchemy
favorite count: 0
has body: Background: I have a project where users are able to upload files. In the database, I want to store the file path to the uploaded file. There are 2 tables within the DB; a Users &amp; FileUploadPath. These tables have a one-to-one relationship. The Flask-SQLAlchemy model I have currently is: import os from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////{}'.format(os.path.join(os.getcwd(), "test.db")) db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'Users' userid = db.Column(db.Integer, primary_key=True, autoincrement=True) fname = db.Column(db.String(80), nullable=False) lname = db.Column(db.String(80), nullable=False) phonenum = db.Column(db.String(10), nullable=False) email = db.Column(db.String(60), nullable=False) password = db.Column(db.String(60), nullable=False) validated = db.Column(db.Boolean, default=False) child = db.relationship('FileUploadPath', uselist=False, backref='Users') class FileUploadPath(db.Model): __tablename__ = 'FileUploadPath' fileUploadID = db.Column(db.Integer, primary_key=True, autoincrement=True) w9FilePath = db.Column(db.String(60), nullable=False) gcFilePath = db.Column(db.String(60), nullable=False) livescanFilePath = db.Column(db.String(60), nullable=False) gcaFilePath = db.Column(db.String(60), nullable=False) userID = db.Column(db.Integer, db.ForeignKey('Users.userid')) To create a new user I use the following: newuser = User(fname='Bob', lname='Smith', phonenum='6551234567', email='bobsmith@gmail.com', password='fe287943hfbwiqey281') With this command I would expect to see a userID within the FileUploadPath table; currently seeing only the created user in the Users table, but NULL inside the userID column. With a query I would also want to see all the uploaded file paths information related to a specific user. Is the relationship between the model's setup correctly? If not, how would I go about declaring the relationship? EDIT: What …
tagged with: python
has answer: http://stackoverflow.com/a/49020421
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/84976130
type: QuestionComment
has text: Do you mean you want a regular and reproducible output format?
comment on: http://stackoverflow.com/q/48985717
score: 0
type: Comment

http://stackoverflow.com/q/48994388
tagged with: pandas
linked to: http://stackoverflow.com/q/22963263
answer count: 1
duplicate of: http://stackoverflow.com/q/22963263
tagged with: python
tagged with: dictionary
has body: Say I have a dictionary d. And I want to create a pandas DataFrame, with all keys in d as column labels. And the number of rows lets say is n. How would I go about this? example n = 4 d = {'what': 5, 'where': 10, 'who': 66} I want something like this what where who 0 0 0 0 0 0 0 0 0 0 0 0
has comment: http://stackoverflow.com/comment/84994278
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48994426
has title: Dictionary keys as pandas column labels
type: Question
tagged with: dataframe
tagged with: numpy
score: 0
accepted answer: http://stackoverflow.com/a/48994426

http://stackoverflow.com/comment/85141290
has text: Is there a specific reason to use [Python2.x as a beginner](https://pythonclock.org/)? And FWIW, SOpython is [not really fond of Learn Python The Hard Way](https://sopython.com/wiki/What_tutorial_should_I_read%3F).
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49068121

http://stackoverflow.com/q/49088748
downvote count: 0
score: 4
tagged with: pywin32
answer count: 1
tagged with: ms-word
favorite count: 0
has answer: http://stackoverflow.com/a/49134951
has body: I'm using win32com.client from the pywin32 module to accept all tracked changes in a word document (Python 3.6.4 on Windows 10 64 bit). Specifically the code I'm using is the following: import win32com.client as win32 word = win32.gencache.EnsureDispatch("Word.Application") word.Visible = False doc = word.Documents.Open(PATH TO WORD FILE) doc.Activate() word.ActiveDocument.TrackRevisions = False # Maybe not need this try: word.WordBasic.AcceptAllChangesInDoc() except TypeError: pass word.ActiveDocument.Save() doc.Close(False) word.Application.Quit() I have two questions. 1.) Is there a better way to accept all changes rather than using the try-except block? Using this method produces a TypeError so a try-except block is required to finish the program. 2.) Do you know how you can delete comments left from users?
tagged with: python
type: AnsweredQuestion
tagged with: win32com
has title: Python - Using win32com.client to accept all changes in Word Documents
linked to: http://stackoverflow.com/q/65980692
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/49134951

http://stackoverflow.com/comment/85054977
comment on: http://stackoverflow.com/q/49025207
score: 0
type: Comment
type: QuestionComment
has text: Is there a question here? I just see a code dump and error message.

http://stackoverflow.com/a/49143162
accepted answer of: http://stackoverflow.com/q/48972683
type: AcceptedAnswer
has body: Option one: use wxgrid from wxpython. It's an excel like grid writen in c++ that can be used in python, so (it's by nature) faster than the second option. And supports larger data sets. Iv'e installed it by puting this in CMD (windows): pip install -U wxPython But if you have other versions of python 2 alongside python 3, you need to put "pip3" instead of "pip" to point to your python 3.X installation if its the case. here's an example: Example Option2: Use pandastable (only for python 3.x). It is entirely written in python, so may be just a little more slow by nature, although uses numpy (that is written in C++ ). In addition, supported data set size is limited by RAM. you need to install all dependencies (numpy, matplotlib, numexpr, pandas) before install: pip install pandastable if you have other versions of Pyton 2, you need to put "pip3". for more information visit : install pandastable Here is an example of how it looks like: example table
downvote count: 0
answers question: http://stackoverflow.com/q/48972683
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/49037667
accepted answer of: http://stackoverflow.com/q/49037286
answers question: http://stackoverflow.com/q/49037286
has body: There are several ways to encode categorical features. The best way really depends on your dataset and which ML algorithm you are going to use, so you could try different encoding schemes and pick the one that has the best results. I've worked with categorical features with hundreds of unique values (e.g. Product Brands) and with tree-based algorithms and a label-encoder worked well with the algorithm. For example you could use the scikit-learn label encoder: &gt;&gt;&gt; le = preprocessing.LabelEncoder() &gt;&gt;&gt; le.fit(["paris", "paris", "tokyo", "amsterdam"]) LabelEncoder() &gt;&gt;&gt; list(le.classes_) ['amsterdam', 'paris', 'tokyo'] &gt;&gt;&gt; le.transform(["tokyo", "tokyo", "paris"]) array([2, 2, 1]...) &gt;&gt;&gt; list(le.inverse_transform([2, 2, 1])) ['tokyo', 'tokyo', 'paris'] You can do that in pandas as well, for example, if you have a column with the string categories you want to encode you could try this: df["categorical_feature"] = df["categorical_feature"].astype('category') df["categorical_feature_enc"] = df["categorical_feature"].cat.codes Another useful encoding you could try is the one-hot encoding. However, since you have a lot of categories to encode that would result in an addition of n columns to your dataset per categorical feature (n = number of categories). Check the pandas get_dummies to see an example.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/48979691
favorite count: 0
has answer: http://stackoverflow.com/a/49355161
has body: Note: I figured out a solution to this question while writing it. My answer is below. Is there an easy way to get sub-pixel antialiased placement of circles using matplotlib? I was able to create the following .gif but the fact that the motion of the circles steps by integer pixels is really bugging me. I can of course render a large image (plt.savefig("image.png",dpi=1000)) and scale down, but the added complexity is a pain (this is an example for students, so importing extra tools will annoy the students and installing extra tools will annoy campus IT!) import matplotlib.pyplot as plt from math import sin,cos x=[] y=[] #Create 41**2 particles in the unit square for i in range(41): for j in range(41): x.append(i*0.05-1.0) y.append(j*0.05-1.0) #5 second video at 30 fps = 150 frames for n in range(150): plt.close('all') fig, axes = plt.subplots(figsize=(5,5)) #some cool motion for i in range(len(x)): x[i]+=0.001*cos(x[i]+3*y[i]) y[i]+=0.001*sin(6*x[i]-4*y[i]) #create the scatter plot axes.scatter(x,y,s=3,antialiased=True) axes.set_xlim(-1.4,1.4) axes.set_ylim(-1.4,1.4) axes.set_aspect('equal') plt.savefig("out/fig%03d.png"%n,dpi=80)
downvote count: 2
has answer: http://stackoverflow.com/a/49348512
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 3
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49355161
type: Question
possible better answer: http://stackoverflow.com/a/48979692
has title: Sub-pixel accuracy scatter plots with matplotlib?
has answer: http://stackoverflow.com/a/48979692
upvote count: 5
has comment: http://stackoverflow.com/comment/85688088
answer count: 3
tagged with: antialiasing

http://stackoverflow.com/a/70580238
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Try this, remove 's' in 'results' in particularly name = results your error code "name = results.find('div', attrs={'class':'name'}).text" with one changes "name = result.find('div', attrs={'class':'name'}).text" well, nice try! import requests r = requests.get('https://www.example.com') from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'}) records = [] for result in results: name = result.find('div', attrs={'class':'name'}).text price = result.find('div', attrs={'class':'price'}).text[13:-11] records.append((name, price,))
answers question: http://stackoverflow.com/q/49002709

http://stackoverflow.com/a/49078486
accepted answer of: http://stackoverflow.com/q/49078472
score: 1
answers question: http://stackoverflow.com/q/49078472
has body: You can use the .split() function to split a string by spaces and that will give you back a list of words that you can then loop and print them out. The function accepts a string that will be used as the delimiter (e.g ",") if this argument is not specified or is None it will run an algorithm that will consider a sequence of whitespaces as a single separator and hence, as a result, no matter how many spaces there are between the words you will get a list of words with no whitespaces at the start or the end of each substring. phrase = input("Enter a phrase: ") words = phrase.split() # ['I', 'need', 'practice'] for word in words: print(word)
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/49005906
answers question: http://stackoverflow.com/q/49005177
has comment: http://stackoverflow.com/comment/85016932
type: Answer
accepted answer of: http://stackoverflow.com/q/49005177
has comment: http://stackoverflow.com/comment/85016727
score: 4
upvote count: 4
has body: SSL_CERT_DIR and SSL_CERT_FILE are not features of urllib2 or requests but of the underlying OpenSSL library. But, it is not enough to just throw a new certificate into the given directory, you need to use a proper filename with the hash of the certificate. See rehash for more information.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49100554
has body: I'm trying to embed a glibc rand() function into python. My purpose is to predict the next values of rand() basing on the assumption that is uses an LCG. I've read that it only uses LCG if it's operating on an 8-byte state, so I'm trying to use the initstate method to set that. I have the following code in my glibc_random.c file: #include &lt;stdlib.h&gt; #include "glibc_random.h" void initialize() { unsigned int seed = 1; char state[8]; initstate(seed, state, sizeof(state)); } long int call_glibc_random() { long r = rand(); return r; } And the following in the respective glibc_random.h: void initialize(); long int call_glibc_random(); Code in python: def test(): glibc_random.initialize() number_of_initial_values = 10 number_of_values_to_predict = 5 initial_values = [] for i in range(number_of_initial_values): initial_values.extend([glibc_random.call_glibc_random()]) When invoked in python, the code above keeps adding 12345 to my list of initial_values. However, when running the C code in www.onlinegdb.com I get a more reasonable list of numbers (11035275900, 3774015750, etc.). I can only reproduce my problem in onlinegdb when I use setstate(state) after the call to initstate(seed, state, sizeof(state)) in the initialize() method. Can anybody suggest what is wrong here? I'm using swig and python2.7, btw.
type: Question
tagged with: swig
downvote count: 0
has answer: http://stackoverflow.com/a/49100676
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49100676
type: AnsweredQuestion
has title: glibc rand() doesn't work with python but works fine in online compiler
score: 1
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/comment/84937673
type: Comment
type: QuestionComment
has text: @JohnGordon Yes, but results were not good (maybe I am not using it right) that's why I posted the code using permutations since it worked better to my goals.
comment on: http://stackoverflow.com/q/48965940
score: 0

http://stackoverflow.com/q/48975046
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9311996
tagged with: django-models
has title: how to add multiple customer address from django admin
type: Question
has body: Okay, newbie here. So I am working on a project where the requirement is : I have to make a Customer model ,where admin/staff can add the customer's details. Now the problem is admin/staff can add multiple address against a customer.I can't find any proper idea ,how would I make it. But still I made a plan .. and I added some code. customer-models.py from __future__ import unicode_literals from django.contrib.postgres.fields import JSONField from decimal import Decimal from django.db import models from django.utils.safestring import mark_safe # Create your models here. class customer(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) profile_image = models.FileField() phone_number = models.BigIntegerField() def profile(self): if self.profile_image!="": return mark_safe('&lt;img src="/media/%s" width="150" height="150" /&gt;' % (self.profile_image)) else: return ""; profile.short_description = 'Image' # profile.allow_tags = True Customer_address-models.py from __future__ import unicode_literals from customer.models import customer from django.db import models # Create your models here. class Address(models.Model): customer = models.ForeignKey(customer,default=0) country = models.CharField(max_length=150) state = models.CharField(max_length=150) city =models.CharField(max_length=150) pin_code = models.BigIntegerField() # def customer_address(self): # return fields = ["country","state","city","pin_code"] customer - admin.py from __future__ import unicode_literals from .models import customer from customer_address.models import Address from django.contrib import admin # Register your models here. class CustomerAddressInline(admin.StackedInline): model = Address class CustomerAdmin(admin.ModelAdmin): list_display = ["first_name","last_name","phone_number","profile"] list_select_related = True inlines = [ CustomerAddressInline, ] search_fields = ["first_name","last_name","phone_number"] fields = ( "first_name","last_n…
has answer: http://stackoverflow.com/a/48978673
tagged with: django-admin
answer count: 1
score: 0
tagged with: python

http://stackoverflow.com/q/49035792
tagged with: python
accepted answer: http://stackoverflow.com/a/49035840
has comment: http://stackoverflow.com/comment/85115109
score: 0
has body: I am new to Python. However, I am trying to run the code (Found here) using the command prompt and I am getting the following error: usage: vogon.py [-h] [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [--youtube_upload] [--preview_line PREVIEW_LINE] config_file vogon.py: error: argument --youtube_upload: ignored explicit argument 'Yes' The command I used to execute it is : &gt;python vogon.py --config_file=sample_win.json --auth_host_name=http://localhost/ --auth_host_port=8080 --logging_level=DEBUG --youtube_upload=Yes --preview_line=2 How can I solve this ? UPDATE &gt; File "vogon.py", line 351, in &lt;module&gt; &gt; main() File "vogon.py", line 348, in main &gt; generate_videos(args.config_file, args.youtube_upload, args.preview_line, args) File "vogon.py", line 68, in &gt; generate_videos &gt; video = generate_video(config, row, (i + 1)) File "vogon.py", line 100, in generate_video &gt; filters = filter_strings(image_overlays, text_overlays) File "vogon.py", line 127, in filter_strings &gt; ovr['y'], ovr['h_align'], ovr['start_time'], KeyError: 'h_align '
tagged with: youtube
answer count: 1
has comment: http://stackoverflow.com/comment/85076524
has comment: http://stackoverflow.com/comment/85115208
has answer: http://stackoverflow.com/a/49035840
type: AnsweredQuestion
has title: Python passing arguments using command prompt
has comment: http://stackoverflow.com/comment/85102387
type: Question
has comment: http://stackoverflow.com/comment/85114795

cloud-hosting
type: Tag
tag name: cloud-hosting
tags question: http://stackoverflow.com/q/49118477

http://stackoverflow.com/q/48971233
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/48971462
has body: I am grouping items and make tests on these groups. I use the following code segment to group 10 items into 3 groups. # grouping into 3 clusters and getting the distribution of the elements node_cluster_labels = sm.cluster(n_clusters=3) data_cluster_labels =node_cluster_labels[bmus] print(data_cluster_labels) This following output specifies the first element is in cluster 2 and second element is in cluster 0 and so on.. output: array([2, 0, 1, 0, 2, 1, 0, 0, 1, 0], dtype=int32) # Formatting clusters to use them for later tests count = 0; [inputsSize,y] = myarray.shape cm = ['cluster 0: '] cm1 = ['cluster 1: '] cm2 = ['cluster 2: '] while(count &lt; inputsSize): b = data_cluster_labels[count] if (b==0): cm.append(arr[count,:]) elif (b==1): cm1.append(arr[count,:]) else: cm2.append(arr[count,:]) count += 1 Output: ['cluster 0: ', array([0, 0, 0, 1, 0]), array([0, 0, 1, 1, 1]), array([0, 0, 1, 1, 0]), array([0, 1, 0, 1, 0]), array([0, 0, 0, 0, 1])] ['cluster 1: ', array([1, 0, 0, 0, 1]), array([0, 0, 1, 0, 0]), array([1, 0, 1, 0, 1])] ['cluster 2: ', array([1, 1, 0, 0, 1]), array([1, 1, 1, 0, 1])] My question is: If the number of clusters is variable and context-dependent (i.e., 4 clusters, 10 clusters, 90 clusters, and so on), how can I generate them better than the above code?
tagged with: numpy
answer count: 1
tagged with: arrays
has title: Creating array clusters in numpy dynamically
downvote count: 0
has comment: http://stackoverflow.com/comment/84948925
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84947944
accepted answer: http://stackoverflow.com/a/48971462

test-reporting
tags question: http://stackoverflow.com/q/49031746
tag name: test-reporting
type: Tag

http://stackoverflow.com/comment/85097819
comment on: http://stackoverflow.com/a/49046596
type: Comment
has text: I don't want to look for the instance in the loop. I want to be able to access instances outside the loop, by referring to some of their properties, whitout saving them into a list. The instances exist in the memmory, but not as a variable (like your "a_class"), but under some self generated string of randome letters and numbers
score: 0
type: AnswerComment

http://stackoverflow.com/q/49040633
tagged with: networkx
linked to: http://stackoverflow.com/q/18515529
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49048777
tagged with: pydot
has title: converting network graph to graphviz
type: Question
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/1806870
tagged with: graphviz
has answer: http://stackoverflow.com/a/62026147
favorite count: 0
type: UnansweredQuestion
has body: I am having trouble visualizing a multidirectional graph with parallel edges in networkx so I have resorted to using pydot, but I am having two issues 1) I cant seem to understand why the node positions are not being fixed I would like to plot them at the x and y specified coordinates 2) How do I set the size of the figure being plotted the plt.figure command does not really work 3) How do I add edge labels (if I had them) many thanks import networkx as nx from io import StringIO from io import BytesIO import matplotlib.pyplot as plt import matplotlib.image as mpimg import networkx as nx graph= nx.MultiGraph() #add 4 nodes in the vertexs of a square. X and Y are the coordinates graph.add_node(1,x=100,y=100) graph.add_node(2,x=100,y=200) graph.add_node(3,x=200,y=100) graph.add_node(4,x=200,y=200) graph.add_edge(1,2) graph.add_edge(2,1) graph.add_edge(3,1) graph.add_edge(3,4) graph.add_edge(4,1) # assign positions for n in graph: graph.node[n]['pos'] = '"%d,%d"'%(graph.node[n]['x'], graph.node[n]['y']) p = nx.drawing.nx_pydot.to_pydot(graph) # render pydot by calling dot, no file saved to disk png_str = p.create_png(prog='C:\\Anaconda3\\Library\\bin\\graphviz\\dot.exe') # treat the dot output string as an image file sio = BytesIO() sio.write(png_str) sio.seek(0) img = mpimg.imread(sio) plt.figure(figsize = (10,10)) imgplot = plt.imshow(img)
tagged with: python

http://stackoverflow.com/a/48970076
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48969151
downvote count: 0
has body: This is new way s=pd.crosstab(df.Sou,df.Des) b = np.random.random_integers(-2000,2000,size=(len(s),len(s))) sy = (b + b.T)/2 s.mul(sy).replace(0,np.nan).stack().reset_index() Out[292]: Sou Des 0 0 1 3 -60.0 1 1 4 -867.0 2 2 3 269.0 3 2 4 1152.0 4 3 1 -60.0 5 3 2 269.0 6 4 1 -867.0 7 4 2 1152.0

http://stackoverflow.com/q/49107716
upvote count: 2
tagged with: image-processing
type: Question
tagged with: matplotlib
tagged with: resize
tagged with: image
answer count: 2
has answer: http://stackoverflow.com/a/49108263
downvote count: 0
favorite count: 0
has title: changing the depth of an image?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/12201577
has answer: http://stackoverflow.com/a/49108318
tagged with: python
score: 2
has body: I am trying to make my own dataset of handwritten images to test my hand written digit classifier. so to make it I wrote the images in a paint box and resized the images to 28x28 pixels same as the train test pixels. but when I loaded it to the python the image shape is (28,28,3) I know these are the RGB values. But I don't know how to get rid of them. should I change my image to gray scale to get an image of size (28,28). I don't know what it is called so the question title can be wrong. The code used to upload the image to environment import matplotlib.pyplot as plt import matplotlib.image as mpimg img=mpimg.imread('0.png') imgplot = plt.imshow(img) Xts_n=img can somebody give me a hint on how to get it done.
duplicate of: http://stackoverflow.com/q/12201577

http://stackoverflow.com/q/49031548
tagged with: python
has comment: http://stackoverflow.com/comment/85067651
downvote count: 6
has comment: http://stackoverflow.com/comment/85067967
has comment: http://stackoverflow.com/comment/85067868
upvote count: 1
has comment: http://stackoverflow.com/comment/85067826
answer count: 1
has title: recursion code should go infinitely?
has answer: http://stackoverflow.com/a/49031696
has body: So, i am trying to learn python and i come across this code to demonstrate recursion in python. Now , I know c++ and I thought this code should create an infinte loop but it doesn't. Any help would be greatly appreciated. This is an program to sort a list by insertion sort. def InsertionSort(seq): isort(seq, len(seq)) def isort(seq, k): # Sort slice seq[0:k] if k &gt; 1: isort(seq, k - 1) #1 insert(seq, k - 1) #2 def insert(seq, k): # Insert seq[k] into sorted seq[0:k-1] pos = k while pos &gt; 0 and seq[pos] &lt; seq[pos - 1]: (seq[pos], seq[pos - 1]) = (seq[pos - 1], seq[pos]) pos = pos - 1 Shouldn't the compiler got to #1 and again call isort and thus return in a infinite loop and never go to #2. Thank you for your help.
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/85067627
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49031696

http://stackoverflow.com/q/49033171
has comment: http://stackoverflow.com/comment/85071126
has comment: http://stackoverflow.com/comment/85071277
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/zip
type: Question
has comment: http://stackoverflow.com/comment/85071330
has answer: http://stackoverflow.com/a/49033566
accepted answer: http://stackoverflow.com/a/49033566
has title: AttributeError when opening locked zip file in Python
score: 0
has body: I'm trying to check the password of zip file is correct using a function: import zipfile def isCorrectPassword(zip_file, password): try: zip_file.extractall(pwd=bytes(password,'utf-8')) print("Success") return True except: print("Fail") return False However, when I run this, it returns False. I know for sure the password is correct. I've tried re-running this script with just this: zip_file.extractall(pwd=bytes(password,'utf-8')) including all necessary variables, but it still doesn't work - it produces this error: AttributeError: 'str' object has no attribute 'extractall' What have I done wrong?
answer count: 1
has comment: http://stackoverflow.com/comment/85071661

http://stackoverflow.com/a/49109217
answers question: http://stackoverflow.com/q/49109150
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85223761
has body: Try this: text = "Today is a bright sunny day in New York" new_list = list(map(str, text.split(" "))) This should give you the following output ['Today', 'is', 'a', 'bright', 'sunny', 'day', 'in', 'New', 'York'] Same for the next string: hello = "This is a hello world program." yet_another_list = list(map(str, hello.split(" "))) Gives you ['This', 'is', 'a', 'hello', 'world', 'program.']
has comment: http://stackoverflow.com/comment/85223249
has comment: http://stackoverflow.com/comment/85223452
has comment: http://stackoverflow.com/comment/85223274
downvote count: 0
type: Answer

http://stackoverflow.com/a/49055288
has comment: http://stackoverflow.com/comment/85139572
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49046956
type: Answer
has body: Presumably the graph you exported contains a decode_csv op to read inputs. How quotes are handled will depend on the setting to the parameter use_quote_delim. To illustrate, consider the following: import tensorflow as tf data = ['some text', '"some text"'] with tf.Session() as sess: use_delim = tf.decode_csv(data, [['']], use_quote_delim=True) dont = tf.decode_csv(data, [['']], use_quote_delim=False) out = sess.run([use_delim, dont]) print("use", out[0]) print("dont", out[1]) &gt;&gt;&gt; ('use', [array(['some text', 'some text'], dtype=object)]) &gt;&gt;&gt; ('dont', [array(['some text', '"some text"'], dtype=object)]) To get the behavior you are expecting, you want your exported model to set use_quote_delim=True (which is the default).
downvote count: 0

http://stackoverflow.com/comment/85195374
has text: Thanks a lot Seb. You saved my life. I was desperate.Though I am new to Python & Selenium, I could not understand why following the recipe would not work. At some stage, I thought I was dumb ;) My journey can continue...
type: Comment
comment on: http://stackoverflow.com/a/49094309
score: 0
type: AnswerComment

http://stackoverflow.com/a/49119776
has comment: http://stackoverflow.com/comment/130152596
score: 22
accepted answer of: http://stackoverflow.com/q/49117963
answers question: http://stackoverflow.com/q/49117963
has comment: http://stackoverflow.com/comment/108614999
upvote count: 22
has body: Simply pass a list of numpy arrays into seaborn's boxplot as it mentions from your very link, the data argument can consist of: data : DataFrame, array, or list of arrays, optional import numpy as np import seaborn as sns np.random.seed(111) all_arr = [np.random.uniform(size=20), np.random.uniform(size=20), np.random.uniform(size=20), np.random.uniform(size=20), np.random.uniform(size=20)] sns.boxplot(data=all_arr)
has comment: http://stackoverflow.com/comment/109885301
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/109885317
type: Answer
has comment: http://stackoverflow.com/comment/130152578

http://stackoverflow.com/q/49118592
has comment: http://stackoverflow.com/comment/85242788
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/49118837
tagged with: pandas
type: AnsweredQuestion
has title: Load Json from http into postgres via python
linked to: http://stackoverflow.com/q/29461933
tagged with: postgresql
type: Question
has body: I have a link which consist of json data as below: http://www.bom.gov.au/fwo/IDQ60801/IDQ60801.94182.json Sample Data from link : "header": [ { "refresh_message": "Issued at 12:02 pm EST Thursday 1 March 2018", "ID": "IDQ60801", "main_ID": "IDQ60800", "name": "Coconut Island", "state_time_zone": "QLD", "time_zone": "EST", "product_name": "Weather Observations", "state": "Queensland" } ], How can I load the above data into postgres table via python? Should I load it into a dataframe first before loading it into postgres? I'm new to dataframe and pandas so would like to seek your help on it. My expected table in postgres would be something like below: ID | main_id| name | state_timezone | time_zone | product_name | state IDQ60801|IDQ60800|Coconut Island| QLD | EST |Weather Observations| Queensland Thanks for your help in advance
tagged with: python
has answer: http://stackoverflow.com/a/49118837
tagged with: http://stackoverflow.com/tag/json
score: 0
answer count: 1

http://stackoverflow.com/comment/85049582
has text: login is okay and i add a jsession in header that is fine. but last post api is not working
comment on: http://stackoverflow.com/a/49000843
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85002502
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48997785
has text: thanks @DanielRoseman your solution worked and is very elegant! I never thought of that
type: Comment

http://stackoverflow.com/comment/85207788
type: Comment
comment on: http://stackoverflow.com/a/49101212
has text: That’s okay. I’ll flag it as a duplicate and it should get closed.
score: 1
type: AnswerComment

http://stackoverflow.com/q/49120178
tagged with: python
has comment: http://stackoverflow.com/comment/116897799
upvote count: 5
downvote count: 0
type: UnansweredQuestion
has body: I was using the pandasql package to do some data manipulations with Pandas. My dataframe is enormous so I've been looking into ways to speed up my computations. One blog (found here) claims that the pysqldf package is much faster. However, I can't get it to work with a Pandas dataframe. Specifically, here's what I have: from pysqldf import SQLDF sqldf = SQLDF(globals()) #also tried with locals(), doesn't make a difference #I know the sql is good, I've used it elsewhere (in R) result = sqldf.execute("Select * from data where blah") Here, data is a Pandas dataframe that I know exists, but I keep getting the error: sqlite3.OperationalError: no such table: data It appears from my web search, including the link above, that the usual operation of this package is with a sqlite db that has been stored in memory. However, the documentation (found here) makes it seem like it can be used directly on a dataframe, like pandasql or R's sqldf. The question: If the pysqldf package can really be used like this, how can I make it recognize my dataframe?
has answer: http://stackoverflow.com/a/57500532
type: Question
score: 5
tagged with: pandas
answer count: 1
has title: Using pysqldf with Pandas
favorite count: 0

http://stackoverflow.com/q/48964836
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84937269
score: 2
tagged with: conv-neural-network
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
has title: Multi-class multi-label classification in Keras
answer count: 1
tagged with: keras-2
favorite count: 0
has body: I am trying to train a multi-task multi-label classifier using Keras. The output layer is a fork of two outputs. The task of each output layer is to predict the categories of its task. The y vectors are OneHot encoded. I am using a custom generator for my data that yields the y arrays in a list to the fit_generator function I am using a categorigal_crossentropy loss function at each layer fork1.compile(loss={'O1': 'categorical_crossentropy', 'O2': 'categorical_crossentropy'}, optimizer=optimizers.Adam(lr=0.001), metrics=['accuracy']) The problem: The loss doesn't decrease with this setup. However, if I train each task separately, I have low loss and high accuracy. So what could be the problem ?
has answer: http://stackoverflow.com/a/51817937
upvote count: 2

http://stackoverflow.com/q/49083939
has body: I am trying to write a python script to read data from a domotic regulator, which uses serial port to communicate. I use this shell command from my raspberry py: cu -l /dev/ttyUSB1 -s 115200 and then I am able to pass some commands and read the answers fine. example: si&gt;test_showw get this answer: Raw values of OTS2/RTS/PDS/SRS: 0xffffffff/0x0000780f/0xffffffff/0xffffffff Converted values of OTS2/RTS/PDS/SRS: -99.0/21.2/0/-99.0 RSSI (dBm) values of OTS2/RTS/PDS/SRS: -255/-67/-255/-255 Seconds since last telegram of OTS2/RTS/PDS/SRS: 5091450/4/5091450/5091450 if command is not known, regulator answer: Unknown command... Answer are usually up to 200 char long. So I have tried to run following code from my raspberry: import serial ser = serial.Serial('/dev/ttyUSB1', baudrate=115200, timeout=0) ser.write('test_showw'.encode('utf-8')) #ser.write(b'test_showw') s = ser.readline() #ser.read(), ser.read(10), ser.read(size=10) print(s) ser.close() But All I can get with read function is 'test_showw', the command I have written to the port. I have read common issue and tried timeout with 0,1,2,None values and read with different signatures, but result remains identical. The read-buffer contains only what I sent in write function PS: I actually found a shell that succeed to retrieve datas, which is here. ... system "stty 115200 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke &lt; $dev" spawn -open [ open $dev r+ ] send "login $password\r" expect { -re "Login OK\r\n(by|si|man)&gt;" { send "$command\r" } -re "Login DENIED*" { exit 1 } timeout { puts "\nTimeout" close exit 1 } } ... Apparently, a login is involved. I know $password, $dev and $command ('showw' in this case), but I have issue translating this into python. I can't understand how 'expect' and 'spawn' commands work.
favorite count: 0
type: UnansweredQuestion
tagged with: serial-port
tagged with: python
has title: pyserial read only what was written
score: 2
downvote count: 0
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85175263
tagged with: raspberry-pi
tagged with: pyserial
has comment: http://stackoverflow.com/comment/85173797
upvote count: 2

http://stackoverflow.com/q/49014660
has body: I'm looking on how to tint an image in Pygame in a similar fashion of how Monogame does it. I've been trying to get custom flags like BLEND_ADD to work but it's been hard to find concise examples of what I'm looking for, it's mostly been people trying to "darken" or work with the alpha levels in a way. Question: How do I tint an image to a certain RGBA value in the same way that MonoGame does it?
has comment: http://stackoverflow.com/comment/85036134
has title: Tinting an image in Pygame
has comment: http://stackoverflow.com/comment/85036183
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85036856
has answer: http://stackoverflow.com/a/49017847
score: 6
tagged with: python
tagged with: pygame
upvote count: 6
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85035983
accepted answer: http://stackoverflow.com/a/49017847

http://stackoverflow.com/comment/85048500
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49008632
has text: Yeah I was wrongly using __init__().

http://stackoverflow.com/comment/84999366
comment on: http://stackoverflow.com/q/48996637
has text: You probably need to run your code with multiple threads in parallel. My guess is that at some point you will either bottleneck on CPU utilization (in gzip decompress), disk I/O (reading bytes off of local storage) or network I/O (pushing bytes to S3). Which one you get stuck at determines what you need to move forward. But to get stuck at any of them you'll need to start operating on multiple files in parallel.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49019824
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49015016
has body: The url template tag needs to be converted to a full URL during template rendering inside the server. Once the HTML reaches the client browser, javascript cannot make that transformation from url tag to full URL. You could render the URL in a hidden part of your HTML document, so that javascript can access the URL later (in the browser) and place it inside a table, for example (like the other answer to this question shows in the example).

http://stackoverflow.com/q/49031894
tagged with: python
has body: I have a dataframe from web scraping all pages from the website animeka website: import pandas as pd import requests from bs4 import BeautifulSoup for page_no in range(1, 467): url = 'http://www.animeka.com/animes/~_{}.html'.format(page_no) titles, studios, genres, durations = [], [], [], [] for page_no in range(1, 467): url = 'http://www.animeka.com/animes/~_{}.html'.format(page_no) r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') for table in soup.find_all('table', class_='animesindex'): td = table.find_all('td', class_='animestxt') titles.append(td[1].text.split(':')[1]) studios.append(td[3].text.split(':')[1]) genres.append(td[4].text.split(':')[1]) durations.append(td[6].text.split(':')[1]) headers = ['Title', 'Studio', 'Genres', 'Duration'] df = pd.DataFrame(dict(zip(headers, [titles, studios, genres, durations]))) df = pd.DataFrame({'duration':df["Duration"], "genre" : df["Genres"], 'studio':df["Studio"], "titre" : df["Title"]}) And I would like to get user_id and rating they put for each anime but this is in picture in "detail" subsection and I do not know how to do to gather that information. This is a picture code where rating is: &lt;img src="/animes/13498.png" width="400" height="100" alt="graph"&gt;
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85079099
tagged with: web-scraping
type: Question
has title: get user_id, rating from webscraping pictures
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49034964

http://stackoverflow.com/comment/85039258
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49000617
has text: so how would that look like in the context of the code?
score: 0

http://stackoverflow.com/a/49116409
type: Answer
accepted answer of: http://stackoverflow.com/q/49116315
has body: You can try this:- def get_letter_grade(score): if isinstance(score,int): if score &gt;= 90: return "A" elif score &gt;= 80: return "B"
answers question: http://stackoverflow.com/q/49116315
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85153847
type: Comment
comment on: http://stackoverflow.com/q/49073915
score: 0
has text: Second row would be stddev in a list of 200 ones and no zeros.
type: QuestionComment

http://stackoverflow.com/comment/85057849
score: 0
type: Comment
type: QuestionComment
has text: Numbers of days… from what? The beginning of the year? The year 1? Your birth day?
comment on: http://stackoverflow.com/q/49026570

http://stackoverflow.com/comment/85073428
type: Comment
comment on: http://stackoverflow.com/a/49033782
score: 0
type: AnswerComment
has text: Nah, it kinda goes against the zen of python -- don't make things too complicated for no reason. And btw, I will edit my answer to add the function I mentioned before, because why not? :)

http://stackoverflow.com/comment/85203484
comment on: http://stackoverflow.com/q/49099101
has text: Could we have an error message ?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84961143
type: QuestionComment
has text: which one should that be?
comment on: http://stackoverflow.com/q/48978035
score: 0
type: Comment

http://stackoverflow.com/q/49075139
score: 0
has comment: http://stackoverflow.com/comment/85156208
has comment: http://stackoverflow.com/comment/85156363
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
has comment: http://stackoverflow.com/comment/85156418
answer count: 0
has title: multiplying lists function, did not understand the output.python
has body: I have encountered this function: def square_it(var): return [var *2] *2 zoo = (square_it([1])) zoo[1][0] +=1 print(zoo) I dont understand why the output is: [[2, 1],[2,1]] and not [[1, 1], [2, 1]] can someone please explain this? Thanks.
has comment: http://stackoverflow.com/comment/85156234
type: Question
has comment: http://stackoverflow.com/comment/85156178
duplicate of: http://stackoverflow.com/q/240178

http://stackoverflow.com/comment/85236819
has text: Did the changes. Thank you
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49114995

http://stackoverflow.com/q/49018833
tagged with: python
has body: How can I change windows using buttons? from appJar import gui def press(btn): def revision(rvs): app = gui("Revision page", "500x200") app.setBg("green") app.setFont(18) app.addLabel("title2", "Please select a topic you would like to rveise") app.go() def menu(): app = gui("Menu", "500x200") app.setBg("green") app.setFont(18) app.addLabel("title1", "Menu") app.addButtons(["Revision", "Quiz", "Progress"], press) app.go() menu()
type: Question
score: 0
has answer: http://stackoverflow.com/a/49082865
answer count: 1
has title: Appjar: How can I change windows using buttons?
type: UnansweredQuestion

http://stackoverflow.com/q/49052687
type: Question
score: 0
has body: Dict = {'Things' : {'Car':'Lambo', 'Home':'NatureVilla', 'Gadgets':{'Laptop':{'Programs':{'Data':'Excel', 'Officework': 'Word', 'Coding':{'Python':'PyCharm', 'Java':'Eclipse', 'Others': 'SublimeText'}, 'Wearables': 'SamsungGear', 'Smartphone': 'Nexus'}, 'clothes': 'ArmaaniSuit', 'Bags':'TravelBags'}}}} d = {(i,j,k,l,m,n): Dict[i][j][k][l][m][n] for i in Dict.keys() for j in Dict[i].keys() for k in Dict[j].keys() for l in Dict[k].keys() for m in Dict[l].keys() for n in Dict[n].keys() } mux = pd.MultiIndex.from_tuples(d.keys()) df = pd.DataFrame(list(d.values()), index=mux) print (df) What I have already done: I tried to Multiindex this Irregular Data using pandas but I am getting KeyError at 'Car'. Then I tried to handle exceptions and tried to PASS it but then it results in a Syntax Error. So May be I lost the direction. If there is any other module or way I can index this irregular data and put it in a table somehow. I have a chunk of raw data like this. What I am trying to do: I wanted to use this data for printing in QTableView which is from PyQt5 (Making a program with GUI). Conditions: This Data keeps on updating every hour from an API. What I have thought till now: May be I can append all this data to MySQL. But then when this data updates from API, only Values will change, rest of the KEYS will be the same. But then It will require more space. References: How to convert a 3-level dictionary to a desired format? How to build a MultiIndex Pandas DataFrame from a nested dictionary with lists Any Help will be appreciated. Thanks for reading the question.
answer count: 2
tagged with: python
tagged with: dictionary
tagged with: qtableview
linked to: http://stackoverflow.com/q/47416113
accepted answer: http://stackoverflow.com/a/49057668
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/49053688
linked to: http://stackoverflow.com/q/41278428
has answer: http://stackoverflow.com/a/49053688
has answer: http://stackoverflow.com/a/49057668
tagged with: pandas
type: AnsweredQuestion
has title: How to convert Multilevel Dictionary with Irregular Data to Desired Format

http://stackoverflow.com/q/49058273
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/74337986
score: -1
tagged with: psutil
tagged with: python-2.7
answer count: 3
upvote count: 0
has title: Using python how to display dns
favorite count: 0
has answer: http://stackoverflow.com/a/49058502
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49059287
has body: Using Python, is there a way using psutil or something else to return the output of "ipconfig /displaydns" or something similar? Spawning a cmd process and running the command is not an option.

http://stackoverflow.com/comment/85082250
score: 0
has text: It's actually a bad thing to use `.split` on CSV, since this is perfectly valid in CSV: `val1,val2,"val3,right here"` - this has 3 values, the third one contains a comma. The csv module would do the right thing, `.split(',')` would mess this up. Avoid.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49038137

http://stackoverflow.com/comment/130741107
comment on: http://stackoverflow.com/a/49068673
type: Comment
score: 2
has text: For future coders: only the second one actually worked for me. `list_widget.takeItem(list_widget.indexAtItem(item).row())`
type: AnswerComment

http://stackoverflow.com/a/49678536
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49058067
has comment: http://stackoverflow.com/comment/86368670
type: Answer
has comment: http://stackoverflow.com/comment/86368649
has body: This is the solution to my specific problem: export fields organized per the items class definition as defined in the items.py of a scrapy spider project. So after tinkering with this problem and implementing @stranac's suggestion of getting rid of the list comprehension, I came up with the following solution, allowing to export all fields in order into their relative csv files: from scrapy.exporters import CsvItemExporter from scrapy import signals from pydispatch import dispatcher def item_type(item): # just want "first_class_def.csv" not "first_class_def_Item.csv" return type(item).__name__.replace('_Item','') class SomeSitePipeline(object): fileNamesCsv = ['first_class_def','second_class_def'] def __init__(self): self.files = {} self.exporters = {} dispatcher.connect(self.spider_opened, signal=signals.spider_opened) dispatcher.connect(self.spider_closed, signal=signals.spider_closed) def spider_opened(self, spider): self.files = dict([ (name, open("/somefolder/"+name+'.csv','wb')) for name in self.fileNamesCsv ]) for name in self.fileNamesCsv: self.exporters[name] = CsvItemExporter(self.files[name]) if name == 'first_class_def': self.exporters[name].fields_to_export = ['f1','f2','f3'] self.exporters[name].start_exporting() if name == 'second_class_def': self.exporters[name].fields_to_export = ['f1','f4','f5','f6'] self.exporters[name].start_exporting() def spider_closed(self, spider): [e.finish_exporting() for e in self.exporters.values()] [f.close() for f in self.files.values()] def process_item(self, item, spider): typesItem = item_type(item) if typesItem in set(self.fileNamesCsv): self.exporters[typesItem].export_item(item) return item Now, everything works as I originally intended to.
answers question: http://stackoverflow.com/q/49058067
has comment: http://stackoverflow.com/comment/105028088
has comment: http://stackoverflow.com/comment/105028194

http://stackoverflow.com/comment/85076522
has text: But the class is passed implicitly when calling class method. Do you know when it's passed implicitly and when it's not?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49034210
type: Comment

http://stackoverflow.com/a/49057144
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85119783
has body: The question is: Check if all words in a list appear as the start of at least one word in the words in another list. Assuming that op wants all words in S1 to appear at least once as the beginning of an word in S2. You can sort both input def contain(s1, s2): count = 0 for i in s1: while ( count &lt; len(s2) and s2[count].startswith(i) == False ): count += 1 if (count &gt;= len(s2)): return False return True s1 = sorted(set(['red', 'gold', 'black', 'gold', 'red', 're'])) s2 = sorted(['golden', 'blackstone', 'golden', 'goldlike', 'blackstone', 'golden', 'redline', 'red']) print( contain(s1, s2) ) Output: True Edit to include complexity: Let’s assume S1 has n elements and S2 has m elements. A naive solution that have nested loops to iterate through both list will have the complexity of O(n*m). By sorting both S1 and S2 we can reduce the complexity of the solution. Sort S1: O(n*log n), Sort S2: O(m*log m) and Contain: O(m) (m if m &gt; n else n) As pointed out in the comments by Stefan, by sorting it will have better complexity than the naive approach.
has comment: http://stackoverflow.com/comment/85120454
accepted answer of: http://stackoverflow.com/q/49056976
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49056976
type: Answer

http://stackoverflow.com/comment/85060581
type: AnswerComment
has text: dicts are unordered, so this won't preserve the (eventual) ordering implied by the keys... Might or not be an issue for the the OP...
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49027927

http://stackoverflow.com/a/49017847
accepted answer of: http://stackoverflow.com/q/49014660
answers question: http://stackoverflow.com/q/49014660
type: AcceptedAnswer
downvote count: 0
has body: Fill your image with a color and pass one of the BLEND constants as the special_flags argument, e.g. your_image.fill((190, 0, 0, 100), special_flags=pygame.BLEND_ADD). Note that BLEND_RGB_ADD is just an alias for BLEND_ADD (and the same applies to the other modes). The RGBA modes will also modify the alpha channel (ADD and MAX make transparent parts visible). Here's a table that shows you the effects of the different blending modes (I've also added the names of the modes in Photoshop):
upvote count: 8
has comment: http://stackoverflow.com/comment/85041130
type: Answer
score: 8

http://stackoverflow.com/comment/85238657
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49116642
type: Comment
has text: [Is this really a problem of `Sales_Applications_breakout_percent_after`](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)?

http://stackoverflow.com/q/48972752
has title: Unable to remove TypeError: unhashable type: 'numpy.ndarray'
downvote count: 1
tagged with: tensorflow
type: Question
score: 3
upvote count: 4
has answer: http://stackoverflow.com/a/48972816
answer count: 1
tagged with: neural-network
favorite count: 0
has body: I have just started learning tensorflow coding and I am stuck with very basic code for creating a neural network. Below is the the code: import tensorflow as tf import numpy as np a = tf.placeholder(shape=(1,1),dtype=tf.float16) b = tf.placeholder(shape=(1,1),dtype=tf.float16) y= tf.placeholder(shape=(1,1),dtype=tf.float16) addition = tf.add(a, b) correct_prediction = tf.equal(addition,y,name=None) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) a1=[[0.2]] b1=[[0.3]] y1=[[0.5]] a = sess.run(addition, feed_dict={a: a1, b: b1}) b = sess.run(correct_prediction, feed_dict={a: a1, b: b1, y: y1}) sess.close() It is giving me the following error *Traceback (most recent call last): File "D:/NN/pyNN/new_main.py", line 35, in &lt;module&gt; b = sess.run(correct_prediction, feed_dict={a: a1, b: b1, y: y1}) TypeError: unhashable type: 'numpy.ndarray'* I have tried multiple ways for providing the input and output but I end up with the same error. Any help will be highly appreciated
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48972816

http://stackoverflow.com/comment/85171287
score: 0
comment on: http://stackoverflow.com/q/49082945
type: Comment
type: QuestionComment
has text: The strange thing is that in debug mode it runs fine but when I right click and select run python file in terminal i get the error

http://stackoverflow.com/q/48968054
answer count: 2
linked to: http://stackoverflow.com/q/10880813
has answer: http://stackoverflow.com/a/48968153
tagged with: python
tagged with: list
duplicate of: http://stackoverflow.com/q/10880813
has comment: http://stackoverflow.com/comment/84941953
has title: Joining integer list
has answer: http://stackoverflow.com/a/48968083
has comment: http://stackoverflow.com/comment/84941714
tagged with: arrays
type: UnansweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/84941693
favorite count: 0
upvote count: 8
type: Question
has body: I have an integer list that is supposed to represent binary: x = [1, 0, 1, 1, 0, 0, 0, 0] y = ''.join(x[:4]) I can't seem to join it, I get 'sequence item 0: expected str instance, int found' However if I do x = [str(1), str(0), str(1), str(1), str(0), str(0), str(0), str(0)] y = ''.join(x[:4]) I get 'type error int object is not subscriptable' however I am not trying to to access ints. Anyone know whats going on?
downvote count: 2

http://stackoverflow.com/q/49053858
has title: How do i change what the the values contain within the variables such as using a percentage?
has answer: http://stackoverflow.com/a/49054330
type: Question
answer count: 1
has body: The below code is supposed to be a stock management system for a business so the user is able to change the price of goods that have stayed too long within the business (unable to sell) from tkinter import* from tkinter import Tk, StringVar, ttk #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# import random import datetime import time; #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# start = Tk() start.geometry("100x600+0+0") start.title ("R.E.D Inventory Control System") #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# Heading = Frame(start, width = 1000, height = 100, bd = 10, relief = 'raise') Heading.pack(side = TOP) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# LowerHeading = Frame(start, width = 500, height = 100, bd = 20, relief = 'raise') LowerHeading.pack(side = BOTTOM) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# LMiddle = Frame(start, width = 500, height = 1000, bd = 12, relief = 'raise') LMiddle.pack(side = LEFT) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# RMiddle = Frame(start, width = 500, height = 1000, bd = 12, relief = 'raise') RMiddle.pack(side=RIGHT) #-------------------------------------------------------------------------------------------------------…
has comment: http://stackoverflow.com/comment/85113876
tagged with: python
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85082435
score: 0
has text: Your `.*` is too greedy. If you change the end of the first `active` line to `up`, it will include the first word as well. Use `\S+` instead.
type: Comment
comment on: http://stackoverflow.com/a/49038393
type: AnswerComment

http://stackoverflow.com/a/48991071
has comment: http://stackoverflow.com/comment/85013855
downvote count: 0
has comment: http://stackoverflow.com/comment/84991550
has comment: http://stackoverflow.com/comment/85013165
has body: You would need to write a udf function to return the event_type and event_date strings after you have selected the required raw column. import re def searchUdf(regex, dateRegex, x): list_return = [] string = re.search(regex, x) if string: dates = re.findall(dateRegex, string.group()) for date in dates: date_string = datetime.strptime(date, '%Y-%m-%d').date() list_return.append(date_string) return list_return from pyspark.sql import functions as F udfFunctionCall = F.udf(searchUdf, T.ArrayType(T.DateType())) The udf function would parse the raw column string with the regex and dateRegex passed as arguments and return eventType and data_string as arrayType column You should be calling the udf function defined and filter out the empty rows and then separate the columns as event_type and event_date columns df = df.select("raw") adf = df.select(F.lit(1).alias("event_type"), udfFunctionCall(F.lit(a_regex), F.lit(date_regex), df.raw).alias("event_date"))\ .filter(F.size(F.col("event_date")) &gt; 0) bdf = df.select(F.lit(2).alias("event_type"), udfFunctionCall(F.lit(a_regex), F.lit(date_regex), df.raw).alias("event_date")) \ .filter(F.size(F.col("event_date")) &gt; 0) The regex used are provided in the question as a_regex = r'\"new\":{(.*?)}{2}|\"new\":\[(.*?)\]' b_regex = r'\"removed\":{(.*?)}{2}|removed\":\[(.*?)\]' date_regex = r'\"start\":\"(\d{4}-\d{2}-\d{2})\"' Now that you have two dataframes for both event_type, final step is to merge them together adf.unionAll(bdf) And thats it. Your confusion is all solved. With the following raw column +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------…
upvote count: 1
has comment: http://stackoverflow.com/comment/85014147
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84991792
has comment: http://stackoverflow.com/comment/84992493
type: Answer
has comment: http://stackoverflow.com/comment/85014469
has comment: http://stackoverflow.com/comment/84995656
accepted answer of: http://stackoverflow.com/q/48986917
has comment: http://stackoverflow.com/comment/84987336
answers question: http://stackoverflow.com/q/48986917
score: 1
has comment: http://stackoverflow.com/comment/84992329
has comment: http://stackoverflow.com/comment/85014198
has comment: http://stackoverflow.com/comment/84990859

http://stackoverflow.com/q/49098670
answer count: 1
favorite count: 0
has title: Loadlibrary MATLAB function
type: UnansweredQuestion
tagged with: python
tagged with: matlab
has body: I am trying to translate a Python code to MATLAB. The Python code use de function "cdll.LoadLibrary" from the library CTYPES. This function doesn't need headers like loadlibrary MATLAB function: PYTHON CODE: from ctypes import * myDLL = cdll.LoadLibrary("cdb_w31.dll") but when I try to do that with MATLAB, I obtain several problems: MATLAB CODE: loadlibrary('cdb_w31.dll','myheader.h', 'mfilename', 'myproto',... 'addheader', 'cdbase',... 'addheader', 'cdbtypeall',... 'addheader', 'cdbtypecon',... 'addheader', 'cdbtypegeo',... 'addheader', 'cdbtypelfc',... 'addheader', 'cdbtypemat',... 'addheader', 'cdbtypesct',... 'addheader', 'cdbtypesys',... 'addheader', 'cdbtypeten') where the file "myheader.h" contain the following code: //myheader.h #include "cdbase.h" #include "cdbtypeall.h" #include "cdbtypecon.h" #include "cdbtypegeo.h" #include "cdbtypelfc.h" #include "cdbtypemat.h" #include "cdbtypesct.h" #include "cdbtypesys.h" #include "cdbtypeten.h" because the DLL library seems to have more than one header, so I create one with all of them. The Command Window message is the following: &gt;&gt; DLL_test Warning: Warnings messages were produced while parsing. Check the functions you intend to use for correctness. Warning text can be viewed using: [notfound,warnings]=loadlibrary(...) &gt; In loadlibrary In DLL_test (line 10) Error loading library intermediate output follows. The actual error is at the end of this output. ********* Failed to parse type 'union taguMAT { int m_id ; typeCDB_MAT m_mat ; typeCDB_MAT_USER m_mat_user ; typeCDB_MAT_FLUI m_mat_flui ; typeCDB_MAT_CONS m_mat_cons ; typeCDB_MAT_UNDR m_mat_undr ; typeCDB_MAT_FAUL m_mat_faul ; typeCDB_MAT_SWEL m_mat_swel ; typeCDB_MAT_CONC m_mat_conc ; typeCDB_MAT_STEE m_mat_stee ; typeCDB_MAT_TIMB m_mat_timb ; typeCDB_MAT_BRIC m_mat_bric ; typeCDB_MAT_SERV m_mat_serv ; typeCDB_MAT_ULTI m_mat_ulti ; typeCDB_MAT_NONL m_mat_nonl ; typeCDB_MAT_BED m_mat_bed ; typeCDB_MAT_LAY m_mat_lay ; typeCDB_MAT_HYD m_mat_hyd ; typeCDB_M…
type: Question
has answer: http://stackoverflow.com/a/49098791
tagged with: ctypes
tagged with: dll
score: 0
upvote count: 1
tagged with: loadlibrary
downvote count: 1

http://stackoverflow.com/q/49092899
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/49094645
has title: How to create pre_populated_field in admin django like slug
linked to: http://stackoverflow.com/q/862522
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/855816
has body: i want create a custum auto populated field in admin django like slug but calculate another thing , not slugify. how do this ?
tagged with: auto-populate
favorite count: 0

http://stackoverflow.com/comment/84970401
has text: The scipy sparse module is not a subclass of `np.matrix`. It's modeled in many ways on `np.matrix`, and some operations return a dense matrix. But internally all sparse formats use `ndarrays` to store their attributes. Dense arrays don't have to be converted to `np.matrix` to interact with sparse matrices.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48981856

http://stackoverflow.com/comment/85061083
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49027736
has text: Yes, you are right, Thank you for completing the question.
score: 0

http://stackoverflow.com/q/48966662
type: Question
has body: I'm new to the selenium/python field. I have been trying to make test cases using python with selenium to test the login form of a particular webpage. I have 10 test cases testing various scenarios so far. What I want to do is reduce the amount of repetition that's in the code. this is the login_form_base I use as a module for the testcases: from expects import expect, contain from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Login(): def __init__(self, driver): self.driver = driver def Username(self, user_name): self.driver.find_element_by_name('email').send_keys(user_name) def Password(self, password): self.driver.find_element_by_name('password').send_keys(password) def Submit_wait_confirm_error(self): driver = self.driver self.driver.find_element_by_class_name('fw-button').click() WebDriverWait(driver, 5).until( EC.presence_of_all_elements_located(('id', 'body-wrapper-full'))) error_signing_in = self.driver.find_element_by_id("body-wrapper-full") expect(error_signing_in.text).to(contain("Invalid username/password")) def Confirm_signed_in(self): error_signing_in = self.driver.find_element_by_id("body-wrapper-full") expect(error_signing_in.text).not_to(contain( "Invalid username/password")) And this is the code with the testcases: from unittest import main, TestCase from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from login_form_base import Login class SomePageLoginTest(TestCase): def setUp(self): self.driver = webdriver.Chrome() def tearDown(self): self.driver.quit() def test_strings(self): driver = self.driver self.driver.get("some url") login = Login(driver) login.Username("wrong username") login.Password("wrong password") login.Submit_wait_confirm_error() def test_long_strings(self): driver = self.driver self.driver.get("some url") login = Login(driver) login.Username("abcdefghijklmn…
has answer: http://stackoverflow.com/a/48966958
score: 0
answer count: 2
has title: Trying to reduce code repetition in my Python selenium code
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48967014
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium

http://stackoverflow.com/q/48968818
has answer: http://stackoverflow.com/a/48970009
has body: Good day! I've run into a head burner. My client requires me to repurpose a python program to work with MySQL instead of Microsoft's SQL Server. I'm having trouble finding an equivalent solution in SQL. I can't seem to create a proper update lock on a row. When two identical transactions execute simultaneously, they both read the row despite opening a transaction at the serialize isolation level, and with SELECT ... FOR UPDATE. Maybe my code will explain it better: execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE") execute("START TRANSACTION") execute("SELECT * FROM job WHERE status = %s LIMIT 1 FOR UPDATE", jobStatus.imported) job_data = cursor.fetchone() if not job_data: connection.rollback() else: execute("UPDATE job SET status = %s WHERE jobID = %s", jobStatus.ingesting, job_data['jobID']) # Update the job data if job_data['jobUUID'] == None: job_data['jobUUID'] = new_unused_uuid().bytes execute("UPDATE job SET jobUUID = %s WHERE jobID = %s LIMIT 1", job_data['jobUUID'], job_data['jobID']) if job_data['dateAdded'] == None: job_data['dateAdded'] = datetime.datetime.now() execute("UPDATE job SET dateAdded = %s WHERE jobID = %s LIMIT 1", job_data['dateAdded'], job_data['jobID']) execute("INSERT INTO ingestJob (fk_jobUUID, fk_nodeUUID, status) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE fk_nodeUUID = %s, status = %s", job_data['jobUUID'], unique_id.bytes, smallJobStatus.running, unique_id.bytes, smallJobStatus.running) connection.commit() The process is as follows: Select one possible job, with FOR UPDATE Rollback (release the lock) if no jobs, or... ...update the row so it can't be reselected, make some unrelated changes Commit They both do their own thing, ignoring each other's lock and transaction What scares me is that it's random. It happens roughly every other run. When trying the same queries in an isolated environment, with sufficient delay, I get the exact result I want. As soon as SELECT ... FOR UPDATE is called by Alice, Barry can't read the row, and…
has answer: http://stackoverflow.com/a/49137392
tagged with: python
linked to: http://stackoverflow.com/q/48974420
type: AnsweredQuestion
tagged with: transactions
possible better answer: http://stackoverflow.com/a/49137392
has answer: http://stackoverflow.com/a/48974517
accepted answer: http://stackoverflow.com/a/48974517
type: Question
tagged with: database-deadlocks
score: 0
answer count: 3
tagged with: sql
tagged with: mariadb
has title: SQL Simultaneous transactions ignore each other's locks??? DEADLOCK [InnoDB, Python]

http://stackoverflow.com/a/49080082
accepted answer of: http://stackoverflow.com/q/49013924
score: 0
type: AcceptedAnswer
has body: Okay, so I came to a solution which worked for me, I split the columns into new data frames, edited each set of columns as needed and then used the following line at the end: finaldf = pd.concat([df, df1, df2, df3, df4, df5], axis=1) There is probably a slicker way to get this done, and i'll most likely laugh at this post a few months down the line, but I guess this was a fix for now.
answers question: http://stackoverflow.com/q/49013924
type: Answer

http://stackoverflow.com/a/49040829
downvote count: 0
has body: I tried your code on Python 3 like this: class MyClass: def print(self): print ('MyClass') a = MyClass() a.print() It worked !! Output: MyClass Running your code as is gives me Syntax Error. Because of missing parenthesis in print. Also, note that print is a reserved keyword in Python 2 but a built-in-function in Python 3.
upvote count: 2
answers question: http://stackoverflow.com/q/49040765
type: Answer
score: 2

http://stackoverflow.com/comment/85149998
score: 0
comment on: http://stackoverflow.com/a/49071793
type: Comment
has text: Yes, several files having the same template could be pushed into the directory over time. Processed files will be deleted
type: AnswerComment

http://stackoverflow.com/q/49087317
linked to: http://stackoverflow.com/q/18171739
linked to: http://stackoverflow.com/q/2953834
has title: Errors while Importing a csv file in Jupyter
has answer: http://stackoverflow.com/a/62007269
has answer: http://stackoverflow.com/a/76897363
type: Question
has answer: http://stackoverflow.com/a/69898070
has body: I am trying to import a csv file into the jupyter notebook using the following syntax time_taken=pd.read_csv("C:\Users\intarvo\Desktop\complaints_data.csv") But whenever I use this syntax there is an error message occurring File "<ipython-input-37-85ee89655ddb>", line 1 time_taken=pd.read_csv("C:\Users\intarvo\Desktop\complaints_data.csv") ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape As indicated in some of the documents where people faced similar errors I tried using the other slash but unfortunately even that did not work. I also used time_taken=open(r'''C:/Users/intarvo/Desktop/complaints_data.csv''') but when I try reading time taken, it raises an error <_io.TextIOWrapper name='C:/Users/intarvo/Desktop/complaints_data.csv' mode='r' encoding='cp1252'> Can someone please suggest how this error can be resolved?
has comment: http://stackoverflow.com/comment/123557981
score: 0
answer count: 4
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/69898070
tagged with: python
possible better answer: http://stackoverflow.com/a/49089074
has answer: http://stackoverflow.com/a/49089074
type: AnsweredQuestion

http://stackoverflow.com/a/50503231
has body: Attaching To or from should be a string and sendmail should always be in the form of the list. cc=['abc.xyz@dfa.com', 'sdf.xciv@lfk.com'] to=['sadf@sdfa.com','123.lfadf@fa.com'] msg['To'] =','.join(to) msg['Cc']=','.join(cc) toAddress = to + cc smtp.sendmail(strFrom, toAddress, msg.as_string())
upvote count: 7
type: Answer
has comment: http://stackoverflow.com/comment/88023611
answers question: http://stackoverflow.com/q/49062924
has comment: http://stackoverflow.com/comment/88024711
downvote count: 0
score: 7

kivy
tags question: http://stackoverflow.com/q/49022779
tags question: http://stackoverflow.com/q/49043654
tags question: http://stackoverflow.com/q/48986723
type: Tag
tags question: http://stackoverflow.com/q/49007660
tags question: http://stackoverflow.com/q/48969355
tags question: http://stackoverflow.com/q/49058162
tags question: http://stackoverflow.com/q/48995284
tags question: http://stackoverflow.com/q/48997181
tags question: http://stackoverflow.com/q/49011251
tags question: http://stackoverflow.com/q/49047655
tags question: http://stackoverflow.com/q/49071739
tags question: http://stackoverflow.com/q/49083639
tags question: http://stackoverflow.com/q/49051262
tags question: http://stackoverflow.com/q/49108836
tags question: http://stackoverflow.com/q/49053729
tags question: http://stackoverflow.com/q/49101761
tags question: http://stackoverflow.com/q/48976480
tags question: http://stackoverflow.com/q/49067168
tags question: http://stackoverflow.com/q/49053059
tags question: http://stackoverflow.com/q/49073331
tags question: http://stackoverflow.com/q/49070345
tag name: kivy
tags question: http://stackoverflow.com/q/49094978
tags question: http://stackoverflow.com/q/49080919
tags question: http://stackoverflow.com/q/49084520
tags question: http://stackoverflow.com/q/49015057
tags question: http://stackoverflow.com/q/48976901
tags question: http://stackoverflow.com/q/48963808
tags question: http://stackoverflow.com/q/49039974
tags question: http://stackoverflow.com/q/48971498
tags question: http://stackoverflow.com/q/48970770
tags question: http://stackoverflow.com/q/49023750
tags question: http://stackoverflow.com/q/49059214
tags question: http://stackoverflow.com/q/48969324
tags question: http://stackoverflow.com/q/49061841

http://stackoverflow.com/comment/85122388
type: QuestionComment
comment on: http://stackoverflow.com/q/49058366
has text: @Bill Bell, edit my question with the pretended output. the header should be the date, dinner, and lunch. and the name of the table should be the name(i.e John).
score: 0
type: Comment

http://stackoverflow.com/comment/85022793
comment on: http://stackoverflow.com/a/49001389
type: Comment
has text: I did but nothing has changed. when I run it on the local server it works fine but when I go to production it doesn't show up
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85195454
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49095133
type: Comment
has text: This would be perfect but it keeps saying there is a syntax error on line 22.

http://stackoverflow.com/comment/85148330
comment on: http://stackoverflow.com/q/49071221
score: 0
has text: The problem is that you're creating multiple `Tk` instances. Each program should have exactly one of those.
type: QuestionComment
type: Comment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/49085797
tags question: http://stackoverflow.com/q/49110328
tags question: http://stackoverflow.com/q/49029226
tags question: http://stackoverflow.com/q/49027768
tags question: http://stackoverflow.com/q/49010606
type: Tag
tags question: http://stackoverflow.com/q/49070450
tags question: http://stackoverflow.com/q/49101560
tags question: http://stackoverflow.com/q/48971410
tags question: http://stackoverflow.com/q/49114202
tags question: http://stackoverflow.com/q/48972164
tags question: http://stackoverflow.com/q/49033806

http://stackoverflow.com/a/49074988
score: 0
has body: Figured it out. Hopefully this will help anyone who has a similar issue as I did. add_dev = device[device["device_type"]=="address"] add_dev["join_left"]=add_dev["upstream_device_id"] count = add_dev.shape[0] x=0 while count&gt;0: x+=1 add_dev = add_dev.merge( no_add"id","device_type","upstream_device_id".rename( index=str, columns={ "id":"id_"+str(x), "device_type":"device_type_"+str(x), "upstream_device_id":"upstream_device_id_"+str(x) }), how="left", left_on="join_left", right_on="id_"+str(x) ) add_dev["node_flag"]=np.where(add_dev["device_type_"+str(x)]=='node',1,0) add_dev["join_left"] = np.where(add_dev["node_flag"] == 1, -999, add_dev["upstream_device_id_"+str(x)]) count = add_dev.shape[0]-add_dev["node_flag"].sum()
type: Answer
answers question: http://stackoverflow.com/q/49072866

http://stackoverflow.com/q/48979223
has title: Numpy Array creation causing "ValueError: invalid literal for int() with base 10: 'n'"
score: 0
has answer: http://stackoverflow.com/a/48979560
tagged with: numpy
has body: I'm trying to run a predictive RNN from this repo https://github.com/jgpavez/LSTM---Stock-prediction. "python lstm_forex.py" It seems to be having trouble creating an empty Numpy array The function giving me problems, starting with the line 'days', fourth from the bottom. def read_data(path="full_USDJPY.csv", dir="/Users/Computer/stock/LSTM2/", max_len=30, valid_portion=0.1, columns=4, up=False, params_file='params.npz',min=False): ''' Reading forex data, daily or minute ''' path = os.path.join(dir, path) #data = read_csv(path,delimiter=delimiter) data = genfromtxt(path, delimiter=',',skip_header=1) # Adding data bu minute if min == False: date_index = 1 values_index = 3 hours = data[:,2] else: date_index = 0 values_index = 1 dates = data[:,date_index] print (dates) days = numpy.array([datetime.datetime(int(str(date)[0:-2][0:4]),int(str(date)[0:-2][4:6]), int(str(date)[0:-2][6:8])).weekday() for date in dates]) months = numpy.array([datetime.datetime(int(str(date)[0:-2][0:4]),int(str(date)[0:-2][4:6]), int(str(date)[0:-2][6:8])).month for date in dates]) Gives the error... Traceback (most recent call last): File "lstm_forex.py", line 778, in &lt;module&gt; tick=tick File "lstm_forex.py", line 560, in train_lstm train, valid, test, mean, std = read_data(max_len=n_iter, path=dataset, params_file=params_file,min=(tick=='minute')) File "/Users/Computer/stock/LSTM2/forex.py", line 85, in read_data int(str(date)[0:-2][6:8])).weekday() for date in dates]) ValueError: invalid literal for int() with base 10: 'n' I've seen a similar problem that involded putting '.strip' at the end of something. This code is so complicated I don't quite know where to put it. I tried everywhere and got usually the same error 'has no attribute' on others. Now I'm not sure what might fix it.
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48979560
tagged with: valueerror
has comment: http://stackoverflow.com/comment/84964084
linked to: http://stackoverflow.com/q/1841565
tagged with: python
answer count: 1

http://stackoverflow.com/a/48996736
has comment: http://stackoverflow.com/comment/84999538
has comment: http://stackoverflow.com/comment/84999797
type: Answer
has body: Update lines 43-45 to following: instance_name = "" if 'Tags' in instance: for tag in instance['Tags']: if tag['Key'] == 'Name': instance_name = tag['Value'] if not instance_name: instance_name = instance['InstanceId'] snap = ec.create_snapshot( VolumeId=vol_id, TagSpecifications=[{ 'ResourceType': 'snapshot', 'Tags': [{ 'Key': 'Name', 'Value': instance['InstanceId'] }] }] )
has comment: http://stackoverflow.com/comment/84999967
answers question: http://stackoverflow.com/q/48995632
score: 0

http://stackoverflow.com/a/49020142
answers question: http://stackoverflow.com/q/49019202
has body: i find it to make a make it we should create a dictionair of dictionaries like this : val = {} val[0]={ "cat": "cat4", "date": "02/11/2015", "notes": "this notes 4" }; val[1]={ "cat": "cat5", "date": "02/11/2015", "notes": "this notes 5" }; after we should insert it to jsonData with the params key jsonData : {"params":val} and we use it directly in the controller : i=0 while i &lt; len(args): http.request.env['sap.orders'].create({"cat": args[str(i)]['cat'], "order_date": args[str(i)]['date'],"notes": args[str(i)]['notes']}) i = i+1 i hope it help ,thanks any way :)
score: 0
type: Answer

http://stackoverflow.com/comment/85204898
score: 0
comment on: http://stackoverflow.com/q/49098595
type: Comment
has text: So what you are saying is I just need to add the` ,1`?
type: QuestionComment

http://stackoverflow.com/comment/85184080
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49087876
has text: @Fake: No, it's not incorrect. I can say with certainty. The way `pack` was used in this example, the frame is placed between the left and right side. Even though the frame in question was placed on the bottom, it's the bottom of the _available_ space, not the bottom of the window as a whole. As I suggested, remove the call to `geometry` and the frame will appear between the left and right sides. You didn't ask how to get it to appear at the bottom of the window, you simply asked why it wasn't appearing.

http://stackoverflow.com/comment/85124545
has text: I'm getting the same error on Python 3.5 and the latest update of the GoogleAds module. Strangely, this used to work! And switching over to Python 2.7 isn't really an option since the whole code base is Python 3 (and used to work fine)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49030383

http://stackoverflow.com/comment/85075482
type: QuestionComment
comment on: http://stackoverflow.com/q/49034403
score: 0
has text: If you are wanting the columns in the order that you would get from a `select *`, then you could do `c.execute('pragma table_info(your_table_name)')` to get the column names.
type: Comment

http://stackoverflow.com/q/48976662
accepted answer: http://stackoverflow.com/a/59039465
score: 0
type: Question
tagged with: sublimetext
has body: After install of Sublime Text 2 and running a few .py files with CTRL+B, I can find this file in the filesystem: C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\Python\Python.sublime-build However, after installing Sublime Text 3 (portable version from here) and running a few Python files, I still can't find Python.sublime-build related to Sublime Text 3 in the whole filesystem. Have .sublime-build config files been packed into another file/package, and why, since it makes the editing much less handy?
has title: .sublime-build files not present after Sublime Text 3 install
tagged with: sublime-build
answer count: 2
has answer: http://stackoverflow.com/a/59039465
has answer: http://stackoverflow.com/a/48976964
tagged with: sublimetext3
tagged with: windows
possible better answer: http://stackoverflow.com/a/48976964
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49050197
has answer: http://stackoverflow.com/a/49050951
has comment: http://stackoverflow.com/comment/85105205
has comment: http://stackoverflow.com/comment/85105496
favorite count: 0
tagged with: python-3.x
has title: How to get the first capital letter and then each that isn't followed by another capital letter in Python?
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49050827
accepted answer: http://stackoverflow.com/a/49050951
type: Question
has body: I am developing a script that creates abbrevations for a list of names that are too long for me to use. I need to split each name into parts divided by dots and then take each capital letter that is at a beginning of a word. Just like this: InternetGatewayDevice.DeviceInfo.Description -> IGD.DI.D However, if there are more consecutive capital letters (like in the following example), I only want to take the first one and then the one that is not followed by a capital letter. So, from "WANDevice" I want get "WD". Like this: InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANIPConnection.1.PortMapping.7.ExternalPort -> IGD.WD1.WCD1.WC1.PM7.EP So far I have written this script: data = json.load(open('./cwmp/tr069/test.json')) def shorten(i): x = i.split(".") abbreviations = [] for each in x: abbrev = '' for each_letter in each: if each_letter.isupper(): abbrev = abbrev + each_letter abbreviations.append(abbrev) short_string = ".".join(abbreviations) return short_string for i in data["mappings"]["cwmp_genieacs"]["properties"]: if "." in i: shorten(i) else: pass It works correctly "translates" the first example but I am not sure how to do the rest. I think if I had to, I would probably think of some way to do it (like maybe split the strings into single characters) but I am looking for an efficient &amp; smart way to do it. I will be grateful for any advice. I am using Python 3.6. EDIT: I decided to try a different approach and iterate over single characters and I pretty easily achieved what I wanted. Nevertheless, thank you for your answers and suggestions, I will most certainly go through them. def char_by_char(i): abbrev= "" for index, each_char in enumerate(i): # Define previous and next characters if index == 0: previous_char = None else: previous_char = i[index - 1] if index == len(i) - 1: next_char = None else: next_char = i[index + 1] # Character is uppercase if each_char.isupper(): if next_char is not None: if next_char.isupper(): if (previous_char is "."…
downvote count: 0
possible better answer: http://stackoverflow.com/a/49050612
answer count: 3
has answer: http://stackoverflow.com/a/49050612

http://stackoverflow.com/comment/85094610
comment on: http://stackoverflow.com/a/49044573
has text: Two files may help you maintain it.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49030383
score: 2
type: AnsweredQuestion
has body: I try to make connection with the Google Adwords API using Python 3.6. I managed to install the libraries, got a developer token, client_customer_id, user_agent, client_id, client_secret and requested succesfully a refresh_token. My googleads.yaml file looks like this: adwords: developer_token: hta... client_customer_id: 235-...-.... user_agent: mycompany client_id: 25785...apps.googleusercontent.com client_secret: J9Da... refresh_token: 1/ckhGH6... When running the first python script get_campaigns.py, I get the very generic response TypeError: cannot use a string pattern on a bytes-like object in ...\Anaconda3\lib\site-packages\googleads-10.0.0-py3.6.egg\googleads\util.py", line 302, in filter Other functions like traffic_estimator_service.get(selector) produce the same error. Furthermore, when starting the Python script get_campaigns.py, I get the following warning, which might explains something: WARNING:googleads.common:Your default encoding, cp1252, is not UTF-8. Please run this script with UTF-8 encoding to avoid errors. INFO:oauth2client.client:Refreshing access_token INFO:googleads.common:Request summary - {'methodName': get, 'clientCustomerId': xxx-xxx-xxxx} I tried many things, but still can't find what causes my error. My settings seem to be right, and I use the examples as provided here. Help is highly appreciated!
type: Question
downvote count: 0
answer count: 1
tagged with: google-ads-api
has comment: http://stackoverflow.com/comment/85212335
favorite count: 0
has title: Python 3.6 Googleads TypeError: cannot use a string pattern on a bytes-like object
accepted answer: http://stackoverflow.com/a/49048103
upvote count: 2
has comment: http://stackoverflow.com/comment/85129740
has answer: http://stackoverflow.com/a/49048103
has comment: http://stackoverflow.com/comment/85100330
tagged with: python
has comment: http://stackoverflow.com/comment/85124545

http://stackoverflow.com/comment/84957331
type: QuestionComment
type: Comment
has text: Is the path for your Python 2.7 installation set in your environment variables?
comment on: http://stackoverflow.com/q/48976184
score: 1

http://stackoverflow.com/a/49032170
has body: I recommend you use tags in your YAML file, and drop the use of keys with names like Item1, Item2 (replace with a list of tagged objects). It is difficult to see the exact structure your data has, but an initial step could be to make the YAML document (assumed to be in a file input.yaml: - ModuleName: myTestModule - Version: 1.0 - ModuleNumbers: [96,97,98,99] - !Message Name: AO3_ DLC: 8 Signal1: Name: Temperature Length: 16 Signal2: Name: AnalogOut3 Length: 16 SignalGroup1: #Comment Name: app_fcex Type: Bitfield Signal1: Name: drive_ready Length: 1 Signal2: Name: error_active Length: 1 Signal3: Name: warning_active Length: 1 Signal3: Name: Temperatur 2 Length: 8 ValueTable: Name: TempStates items: - !Item Name: INIT Value: 1 - !Item Name: RUN Value: 2 - !Item Name: DONE Value: 3 - !Item Name: ERROR Value: 4 - !Message name: AO2_ object: RX2 DLC: 8 and load that with: import sys import ruamel.yaml class Item: def __init__(self, name=None, value=None): self.name = name self.value = value @classmethod def from_yaml(cls, constructor, node): for m in constructor.construct_yaml_map(node): pass return cls(m['Name'], m['Value']) def __repr__(self): return 'Item(name={.name}, value={.value})'.format(self, self) class Message: def __init__(self, name=None, DLC=None, object=None, signals=None): self.name = name self.dlc = DLC self.object = object self.signals = [] if signals is None else signals @classmethod def from_yaml(cls, constructor, node): for m in constructor.construct_yaml_map(node): pass if 'Name' in m: name = m['Name'] elif 'name' in m: name = m['name'] else: name = None object = m['object'] if 'object' in m else None if 'DLC' in m: dlc = m['DLC'] else: dlc = None if 'signals' in m: signals = m['signals'] elif 'Signal1' in m: x = 1 signals = [] while True: name = "Signal{}".format(x) try: signals.append(m[name]) except KeyError: break x += 1 else: signals = None return cls(name, dlc, object, signals) def __repr__(self): return 'Message(name={}, DLC={}, object={}, s…
accepted answer of: http://stackoverflow.com/q/49029459
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85135050
type: Answer
answers question: http://stackoverflow.com/q/49029459
upvote count: 3
has comment: http://stackoverflow.com/comment/85092861
score: 3

http://stackoverflow.com/comment/85279795
score: 0
type: Comment
has text: Please do not leave code-only answers, add explanations to your answer.
comment on: http://stackoverflow.com/a/49130932
type: AnswerComment

http://stackoverflow.com/q/48976705
type: UnansweredQuestion
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/48977215
has title: django joins with many to many relationship
tagged with: join
has comment: http://stackoverflow.com/comment/84958458
score: 1
has comment: http://stackoverflow.com/comment/84958619
type: Question
has body: I've looked at multiple answers to similar questions on how to do a join over django models with a many to many relationship but none seem to work, could someone please help. User -> your normal django user model class Upload(models.Model): file = models.FileField(storage=FileSystemStorage(location='./xyz/xyz/')) timestamp = models.DateTimeField(auto_now_add=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class FollowerRelationship(models.Model): followed_content_creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followed_fk') following_content_creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following_fk') Now I'd like to select all Uploads from a given user's followers, how could I do that without hitting the storage system more than once? Many thanks
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84959879
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84958828

http://stackoverflow.com/q/48982187
type: Question
answer count: 2
has title: edit linux telegraf.conf with python
downvote count: 0
has body: I am using telegraf as a measuring/monitoring tool in my tests. I need to edit telegraf configurations automatically; since all tests are being executed automatically. Currently I am using re for configuring it; this is the process: Read the whole file content. Use regex to find and edit the required plugin/property. Write the whole changed content to the file. But I'm searching for a library, if exists, like ConfigParser or reconfigure to handle the configurations as an object not content. I tried ConfigParser.ConfigParser, ConfigParser.RawConfigParser and ConfigParser.SafeConfigParser; all return: ConfigParser.ParsingError: File contains parsing errors: /etc/telegraf/telegraf.conf reconfigure library has specific configuration classes, each belongs to a special type of linux configs (e.g. FSTabConfig, ResolvConfig and some other types), but it doesn't contain a class for telegraf configs. Does anyone have an option in mind? EDIT 1: I tried configobj library (as @KevinC suggested), but it loads nothing: &gt;&gt;&gt; import configobj &gt;&gt;&gt; c = configobj.ConfigObj('/home/zeinab/Desktop/config-modification/telegraf.conf', list_values=False) &gt;&gt;&gt; c ConfigObj({}) Using list_values=True returns the same results.
favorite count: 0
has comment: http://stackoverflow.com/comment/84970687
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84970108
has answer: http://stackoverflow.com/a/51857435
tagged with: automation
has answer: http://stackoverflow.com/a/63040474
tagged with: configuration
tagged with: telegraf

http://stackoverflow.com/a/49025798
answers question: http://stackoverflow.com/q/49000226
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49000226
has body: Order does not matter. Only the names matter. See the below example that demonstrates this (sorry it is R, but the behaviour will be identical in Python: the only R-specific thing here is: a) using built-in iris; b) using t(d), as otherwise I end up with a 4-row, 1-column, H2O frame.) BTW, if you specify column indices, instead of names, the first thing H2O does is convert them to column names. (See the m@parameters$x output in the below.) library(h2o) h2o.init() iris &lt;- as.h2o(iris) m &lt;- h2o.randomForest(1:4, 5, iris) m@parameters$x d &lt;- c(1.4,3.6,5.0,0.2) names(d) &lt;- c("Petal.Length", "Sepal.Width", "Sepal.Length", "Petal.Width") test &lt;- as.h2o(t(d)) test h2o.predict(m, test) P.S. regarding your example, you will need to rename (lowercase) the column names in your test data, so that they match the training data, and then it will work.
type: AcceptedAnswer

elasticsearch
tags question: http://stackoverflow.com/q/49108252
type: Tag
tags question: http://stackoverflow.com/q/49040720
tags question: http://stackoverflow.com/q/48965137
tags question: http://stackoverflow.com/q/48988359
tag name: elasticsearch
tags question: http://stackoverflow.com/q/49045181

http://stackoverflow.com/a/48972304
upvote count: 3
answers question: http://stackoverflow.com/q/48972160
has body: for a given url pattern such as url(r'^random/(?P&lt;arg1&gt;[0-9]+)/(?P&lt;arg2&gt;[0-9]+)/$', views.random, name="urlname") or url(r'^argfree/', views.random2, name="urlname2 from django.http import HttpResponseRedirect from django.urls import reverse def view(request): # do your thing if something: return HttpResponseRedirect(reverse("urlname", args=["this_is_arg1", "this_is_arg2"])) else: return HttpResponseRedirect(reverse("urlname"))
score: 3
downvote count: 0
type: Answer

http://stackoverflow.com/q/49116596
tagged with: python
tagged with: php
has body: I would like to run a script in python with a button on a web page. I already write my script in python and the design of the web page. My python last a few minutes and I have to print on the page the output of the script. But when I press the button, the script start and the page stay in loading and all the text appears at the end... So I would like to print the output in real time. By the way, I'm sorry for my English but I'm Belgian ^^ Thanks. Kevin.
answer count: 0
type: Question
has title: Printing output of a python script with html/css/php
score: 0
has comment: http://stackoverflow.com/comment/85241302
has comment: http://stackoverflow.com/comment/85239119
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/84975519
comment on: http://stackoverflow.com/q/48985455
score: 0
type: QuestionComment
type: Comment
has text: try https://stackoverflow.com/questions/29831052/error-importing-h5py

http://stackoverflow.com/a/49007337
has body: Use Python Counter (part of standard library): &gt;&gt;&gt; str = 'foo fighters' &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counter = Counter(str) Counter({'f': 2, 'o': 2, ' ': 1, 'e': 1, 'g': 1, 'i': 1, 'h': 1, 's': 1, 'r': 1, 't': 1}) &gt;&gt;&gt; counter['f'] 2 &gt;&gt;&gt;
type: Answer
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/49007215

http://stackoverflow.com/comment/85051080
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/49023123
has text: You can't. Use two slices

http://stackoverflow.com/a/49119215
accepted answer of: http://stackoverflow.com/q/49119011
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Your code here uses instance variable title: def __str__(self): return self.title When Python 'looks' through your vars it sees that self.title was never declared, hence you get an error. To fix it I would add title to your model: class update_grid(models.Model): title = models.CharField(max_length=30) data = JSONField() def __str__(self): return self.title I hope it helps
answers question: http://stackoverflow.com/q/49119011

http://stackoverflow.com/a/55368813
score: 4
has body: Here's a working version for bokeh 1.0.4 from random import random import bokeh.io from bokeh.io import output_notebook, show from bokeh.layouts import row from bokeh.models import CustomJS, ColumnDataSource from bokeh.plotting import figure from bokeh.models.widgets import DataTable, DateFormatter, TableColumn from bokeh.resources import INLINE bokeh.io.output_notebook(INLINE) x = [random() for x in range(500)] y = [random() for y in range(500)] s1 = ColumnDataSource(data=dict(x=x, y=y)) p1 = figure(plot_width=400, plot_height=400, tools="lasso_select", title="Select Here") p1.circle('x', 'y', source=s1, alpha=0.6) s2 = ColumnDataSource(data=dict(x=[], y=[])) p2 = figure(plot_width=400, plot_height=400, x_range=(0, 1), y_range=(0, 1), tools="", title="Watch Here") p2.circle('x', 'y', source=s2, alpha=0.6) columns = [TableColumn(field ="x", title = "X axis"), TableColumn(field ="y", title = "Y axis")] table = DataTable(source =s2, columns = columns, width =155, height = 380) s1.selected.js_on_change('indices', CustomJS(args=dict(s1=s1, s2=s2, table=table), code=""" var inds = cb_obj.indices; var d1 = s1.data; var d2 = s2.data; d2['x'] = [] d2['y'] = [] for (var i = 0; i &lt; inds.length; i++) { d2['x'].push(d1['x'][inds[i]]) d2['y'].push(d1['y'][inds[i]]) } s2.change.emit(); table.change.emit(); """) ) layout = row(p1, p2, table) show(layout) You can even select rows/values in the table and the points in the second plot will change opacity (and you can sort the table by clicking the headers)
answers question: http://stackoverflow.com/q/48982260
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/85221581
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49108256
has text: you should do `model.outputs = [model.layers[-1].output]` and `model.layers[-1].outbound_nodes = []`after popping the 3 layers. Here you have a related issue: `https://github.com/keras-team/keras/issues/2371`

http://stackoverflow.com/q/48972155
has body: A file has lines like: $ cat build-log.txt 2018-02-23T10:08:52.856946Z|cov-internal-capture|6812|info|&gt; EXECUTING: "C:\ghs\comp_201416\asarm.exe" -elf -b0 [ skip ] I spent an hour or more trying to find out how to set the Python re.search pattern. It all ended up with (the goal was just to extract the compiler name, 'asarm' in this instance) m = re.search('C:\\\\ghs\\\\comp_201416\\\\([a-z]*)\\.exe', line) in the Python code which works (at least m.group(1) gives 'asarm' ) Please explain why the four backslashes is needed to quote just one in the file? Using Python 2.7 Mac OS X High Sierra Elpy GNU Emacs 25.3.1 (x86_64-apple-darwin13.4.0, NS appkit-1265.21 Version 10.9.5 (Build 13F1911)) [ https://emacsformacosx.com ]
linked to: http://stackoverflow.com/q/33582162
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48972251
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84949565
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48972251
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84949515
has title: How to quote backslash in Python code (four \ to quote one)?

http://stackoverflow.com/comment/85002116
score: 0
comment on: http://stackoverflow.com/q/48981687
has text: Thanks @LazyElephant for giving it a try. Could you share the sample data that cause it to work? Granted I didn't divid the `dW`, `db` by `companies`, but I should have caused the numbers to blow up since `companies` is only about 200.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85084807
type: QuestionComment
type: Comment
has text: Okay, I misunderstood that. Nonetheless, thank you!
comment on: http://stackoverflow.com/q/49039491
score: 0

http://stackoverflow.com/a/49066562
has body: Boolean values are the two constant objects False and True. For Boolean Strings bool('') =&gt; False bool('false') =&gt; True The bool checks whether the list has an object or not. If it is empty it will return False, if anything but empty, it will return True. In your case, bOk = bool(input()), has a value, therefore bOk returns True, regardless of what object it has. And thus the output you have.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49066162
upvote count: 2
answers question: http://stackoverflow.com/q/49066162

http://stackoverflow.com/q/48995922
tagged with: tidyr
answer count: 1
linked to: http://stackoverflow.com/q/5963269
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84997545
tagged with: python
tagged with: dplyr
has comment: http://stackoverflow.com/comment/84997460
has comment: http://stackoverflow.com/comment/84997462
has comment: http://stackoverflow.com/comment/84997251
score: 0
has answer: http://stackoverflow.com/a/48996369
type: Question
has title: How to tweak in mail Body using MailR in R
has body: I am new to using Library mailR and search a lot on google but couldn't found anything useful. I have 2 html table in R, i want to sent them using MailR library in mail body but when i'm sending the mail both table looks like joined to each other. How to tweak mail body using MailR library. I want mail Looks like below mentioned format. Hi Team, "some sentence here" using t.start and nrows() in the sentence space "some sentence here: I am using the code to make table something like this: Table1&lt;-DF%&gt;% tableHTML(rownames = FALSE, widths = rep(100, 13), second_headers = list(c(1, 6, 6), c("", "ABC", "XYX")), caption = "ABC Stat") %&gt;% add_css_caption(css = list(c("font-weight", "border"), c("bold", "1px solid black")))%&gt;% add_css_row(css = list(c("background-color"), c("lightblue")), rows = 0:2)%&gt;%add_css_caption(css = list(c("background-color"), c("lightblue"))) and same code for table2 And to send e-mail the code looks like: library(mailR) sender&lt;-"a12db@gmail.com" recipients&lt;-c("xyc@gmail.com") sm&lt;-list(host.name = "smmm.gmail.com", port = 123, user.name="a12db@gmail.com", passwd="1#4$12#", ssl=TRUE) send.mail(from=sender, to=recipients, subject = paste0("Abc Repo"), body = paste("Some sentence",Table1,"\br",Table2), html = TRUE, inline = FALSE, smtp = sm, authenticate = TRUE, attach.files =("abc.csv") , send = TRUE )
tagged with: sendmailr
tagged with: http://stackoverflow.com/tag/r

http://stackoverflow.com/a/49018716
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/85058742
score: 4
accepted answer of: http://stackoverflow.com/q/49004671
answers question: http://stackoverflow.com/q/49004671
type: AcceptedAnswer
has body: There are a lot of ways to share state between tests. To name a few: Using a session-scoped fixture Define a fixture with a session scope where the value is calculated. It will executed before the first test that uses it runs and then will be cached for the whole test run: # conftest.py @pytest.fixture(scope='session') def grain(): host = ... return host.salt("grains.item", "client_NAME") Just use the fixture as the input argument in tests to access the value: def test_ACD_GRAIN(grain): assert grain['client_NAME'] == "test" Using pytest namespace Define an autouse fixture with a session scope, so it is autoapplied once per session and stores the value in the pytest namespace. # conftest.py import pytest def pytest_namespace(): return {'grain': None} @pytest.fixture(scope='session', autouse=True) def grain(): host = ... pytest.grain = host.salt("grains.item", "client_NAME") It will be executed before the first test runs. In tests, just call pytest.grain to get the value: import pytest def test_ACD_GRAIN(): grain = pytest.grain assert grain['client_NAME'] == "test" pytest cache: reuse values between test runs If the value does not change between test runs, you can even persist in on disk: @pytest.fixture def grain(request): grain = request.config.cache.get('grain', None) if not grain: host = ... grain = host.salt("grains.item", "client_NAME") request.config.cache.set('grain', grain) return grain Now the tests won't need to recalculate the value on different test runs unless you clear the cache on disk: $ pytest ... $ pytest --cache-show ... grain contains: 'spam' Rerun the tests with the --cache-clear flag to delete the cache and force the value to be recalculated.
type: Answer
has comment: http://stackoverflow.com/comment/85056620

http://stackoverflow.com/q/49101342
has answer: http://stackoverflow.com/a/49114348
has answer: http://stackoverflow.com/a/49115535
type: Question
has title: Implementing the Prolog Unification algorithm in Python? Backtracking
score: 14
has comment: http://stackoverflow.com/comment/112201459
possible better answer: http://stackoverflow.com/a/49115535
tagged with: algorithm
has comment: http://stackoverflow.com/comment/85331696
linked to: http://stackoverflow.com/q/1396558
has comment: http://stackoverflow.com/comment/85233973
upvote count: 14
tagged with: prolog
answer count: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/49114348
has answer: http://stackoverflow.com/a/49121029
tagged with: python
tagged with: backtracking
tagged with: unification
type: AnsweredQuestion
has body: I'm trying to implement Unification, but having problems.. already got dozen of examples,but all they do is to muddy the water. I get more confused than enlightened : http://www.cs.trincoll.edu/~ram/cpsc352/notes/unification.html https://www.doc.ic.ac.uk/~sgc/teaching/pre2012/v231/lecture8.html [code below is based on this intro] http://www.cs.bham.ac.uk/research/projects/poplog/paradigms_lectures/lecture20.html#representing https://norvig.com/unify-bug.pdf How can I implement the unification algorithm in a language like Java or C#? The art of Prolog one ...and several others. The biggest problem is that I could not figure clear statement of the problem. More mathy or lispy explanations are confusing me even more. As a good start it seems a good idea to follow the representation to be list based (like in the lispy cases) i.e. : pred(Var, val) =becomes=&gt; [pred, Var, val] p1(val1, p2(val2, Var1)) ==&gt; [p1, val1, [p2, val2, Var1]] except how do you represent lists themselves !? i.e. [H|T] I would love if you can show me a Python pseudo code and/or more detailed algorithm description or a pointer to one. Some points I grasp is the need to separate the code in general-unifier and var-unification, but then I cant see the mutual-recusive case ! ... and so on. As a side note : I would also love for you to mention how would you handle Unification on Backtracking. I think I have backtracking squared-away, but I know something has to happen to substitution-frame on backtracking. Added an answer with the current code. http://www.igrok.site/bi/Bi_language.html http://www.igrok.site/bi/TOC.html https://github.com/vsraptor/bi/blob/master/lib/bi_engine.py
downvote count: 0

http://stackoverflow.com/comment/85220968
type: QuestionComment
has text: Possible duplicate of [How to convert comma-delimited string to list in Python?](https://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python)
score: 1
comment on: http://stackoverflow.com/q/49107938
type: Comment

http://stackoverflow.com/comment/85075940
comment on: http://stackoverflow.com/q/49035445
score: 0
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga exactly.

http://stackoverflow.com/q/49106709
tagged with: pypi
type: Question
accepted answer: http://stackoverflow.com/a/49107899
downvote count: 0
has title: README.rst fails to render on PyPi when using `raw` directive
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/46682793
has body: I have a README.rst in my project hosted on GitHub. It renders fine on GitHub but fails to render on PyPi i.e. I see raw content on the PyPi project description page. I have looked through similar questions and checked the rst format using python setup.py -r and the packages rstcheck &amp; collective.checkdocs, all of which do not throw any errors. There are no relative links or internal links. I am not sure what the problem is here and how I can fix this. I know this question has been asked many times. I think I have tried all the solutions and they did not work for me and that is why I am asking again.
has answer: http://stackoverflow.com/a/49107899
score: 6
tagged with: python
tagged with: restructuredtext
upvote count: 6
duplicate of: http://stackoverflow.com/q/46682793
type: AnsweredQuestion

http://stackoverflow.com/comment/85239864
type: AnswerComment
has text: so this is faster than apply even though it uses a for loop? very interesting
type: Comment
comment on: http://stackoverflow.com/a/49117080
score: 0

http://stackoverflow.com/comment/85135738
type: Comment
comment on: http://stackoverflow.com/q/49064831
score: 0
type: QuestionComment
has text: Yes, because in my working environment, lot of people continuously change this library file to add their own utility functions. What if somebody defines some functions after sayhi() call. I cannot restrict others from adding code after the call, neither can i check that file everytime a commit is made

http://stackoverflow.com/a/48970525
has comment: http://stackoverflow.com/comment/84952481
answers question: http://stackoverflow.com/q/48970272
type: Answer
score: 0
has body: I would suggest you to do "Edge Analytics" at the Raspbery Pi side. Cause Your problem is occurred because both your Client(Raspberry Pi) and Server is having high performance but your network is too slow. Solution You can write a simple Python algorithm to send only the changed bits in a frame, instead of sending the whole data over the network. By the above mentioned method you can reduce your network usage, which helps you in sending more frame(30-60fps) information. Terms Edge Analytics : It refers to the analysis of data from some non-central point in a system, such as a network switch, peripheral node or connected device or sensor Reference url's http://pythonforengineers.com/image-and-video-processing-in-python/ https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/

http://stackoverflow.com/q/49061099
has comment: http://stackoverflow.com/comment/85127196
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49061337
type: Question
has comment: http://stackoverflow.com/comment/85127426
score: 1
has body: I have to write a regex condition in which A token only contains letters (i.e. a-z or A-Z), "-" (hyphen), or "(underscore) " . Moreover, a token cannot starts or ends with "-" or "_" . I tried but i am not able to get that text = "this is a breath-taking ambitious movie; test text: abc_dcd abc_ dvr89w, abc-dcd -abc" tokens=re.findall(r'[\-\_][a-zA-Z]+|[a-zA-Z]+-+_[a-zA-Z]', text)
has comment: http://stackoverflow.com/comment/85127264
answer count: 3
upvote count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49061197
has comment: http://stackoverflow.com/comment/85127308
tagged with: python
has title: Or condition not working in regex python
tagged with: regex
has answer: http://stackoverflow.com/a/49061211
has comment: http://stackoverflow.com/comment/85127352

http://stackoverflow.com/q/49071084
has body: I have a data frame for which I would like to add a column value using an if statement. I have been trying a lambda function but have not had luck. I want to add a column that says if threshold&lt; order, then set new column to threshold else set column to order. df_new Order Threshold 20,000 100,000 500,000 50,000 100,000 75,000 I tried: df_new['New Column'].apply(lambda x: df_new['Threshold'] if &lt; df_new['Order'] else df_new['Order Quantity'])
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49071241
type: Question
tagged with: if-statement
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49071241
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
has title: pandas new column if statement
tagged with: python

http://stackoverflow.com/q/48972634
accepted answer: http://stackoverflow.com/a/48991422
type: AnsweredQuestion
tagged with: brainfuck
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48991422
score: 0
has comment: http://stackoverflow.com/comment/84965358
tagged with: python-3.x
has title: brainfuck intepreter printing out wrong
has body: I recently decided to try to code "yet another" brainfuck interpreter, but I have a problem. It prints out the wrong numbers, when it should put our hello,world!. Does anyone know why this is happening? Thanks in advance! I cannot figure out why it's doing this. Please help! I am only a beginner. Sorry for the bad coding style, but please don't change the whole thing. I would rather recieve tips. from copy import copy import sys def brainfuckintepreter(program): # find pairs of brackets brackets = {} bbrackets = {} def findmatchingclosingbracket(ctr): level = 0 if program[ctr] == '[': while True: if program[ctr] == '[': level += 1 elif program[ctr] == ']': level -= 1 if level == 0: return ctr break ctr += 1 def findmatchingopeningbracket(ctr): level = 0 if program[ctr] == ']': while True: if program[ctr] == '[': level -= 1 elif program[ctr] == ']': level += 1 if level == 0: return ctr break ctr -= 1 """ ctr = 0 for a in program: if a == '[': f = copy(findmatchingclosingbracket(ctr)) brackets[ctr] = f bbrackets[f] = ctr ctr += 1 print(brackets) print(bbrackets) """ # running the program tape = [0] * 3000 pointer = 1500 counter = 0 results = "" valid = True while counter != len(program) and valid: a = program[counter] # move right if a == '&gt;': if pointer == len(tape) - 1: tape.append(0) pointer += 1 # move left elif a == '&lt;': if pointer == 0: raise ValueError("On index ", counter, ", the program tried to move to -1 on the tape") valid = False return valid else: pointer -= 1 # increment elif a == '+': if tape[pointer] == 255: tape[pointer] = 0 else: tape[pointer] += 1 # decrement elif a == '-': if tape[pointer] == 0: tape[pointer] = 255 else: tape[pointer] -= 1 # output character elif a == '.': t = chr(tape[pointer]) results += t print(t, end='') # input character elif a == ',': tape[pointer] = ord(sys.stdin.read(1)) # opening bracket elif a == '[': if tape[pointer] == 0: pointer = findmatchingclosingbracket(pointer) # closing bracket elif a == ']': if tape[point…
tagged with: python

http://stackoverflow.com/q/49040154
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85086380
tagged with: fabric
has comment: http://stackoverflow.com/comment/85086408
tagged with: python
has title: Fabric - Handle error when mirror not available
has body: My fabric script installs AWS Systems Manager from a mirror. Right now it fails if the mirror is not available. Is there a way to handle this situation? I would love to supply additional mirrors and have it try each until successful. How can I add that? def ssm_install(): try: is_running = sudo('status amazon-ssm-agent', warn_only=True) if "start/running" in is_running: sys.exit() else: run('mkdir -p /tmp/ssm') run('cd /tmp/ssm') sudo('yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm') sys.exit() except NetworkError: print "Can't connect to this host" sys.exit()
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85103265
type: Comment
type: QuestionComment
score: 1
has text: Using `otypes=[object]` might get `vectorize` to work. `vectorize` uses `frompyfunc`, but changes the returned dtype.
comment on: http://stackoverflow.com/q/49047468

http://stackoverflow.com/comment/85164237
type: QuestionComment
has text: "Arrays" are called *lists* in Python. That is probably why you were unable to find [the official documentation](https://docs.python.org/3/tutorial/datastructures.html).
score: 1
comment on: http://stackoverflow.com/q/49079102
type: Comment

http://stackoverflow.com/q/49026864
has body: I have created a tkinter application, wherein I do save the process done in UI using "Save" button. Below is the sample part of my code for better understanding: self.savebtn = Button(self.btm_frm,text="Save",width=10,command=self.savebutton) def savebutton(self): self.savelist=[] self.savetext = r" Item - " + str(self.a) + " is done " self.savelist.append(self.text) So every time I click on "Save" button, it would call self.savebutton command which actually saves some text. And I want to create a list that would record all the values of self.savetext But I am stuck at creating list of whole data, since I am not familiar with this case, and the above code could retain only the list of last call. Can anyone guide on achieving this.
score: 0
tagged with: python
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/49026981
has answer: http://stackoverflow.com/a/49027200
type: AnsweredQuestion
has title: Creating a list from a variable holding changing values
possible better answer: http://stackoverflow.com/a/49027200
type: Question
accepted answer: http://stackoverflow.com/a/49026981
answer count: 2

http://stackoverflow.com/comment/85207138
type: QuestionComment
has text: @Alex TypeError: unhashable type: 'slice' error
comment on: http://stackoverflow.com/q/49100943
score: 0
type: Comment

http://stackoverflow.com/comment/85200632
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49097658
has text: @PedroMaimere, no need for a global here.
score: 0

http://stackoverflow.com/q/49059042
has body: Hello I am trying to render this map with Folium inside a jupyter notebook. https://github.com/kthotav/TopoJSON-Maps/blob/master/usa/usa-states/colorado/colorado-counties.json As this is TopoJson, it should be pretty straightforward m = folium.Map([39, -105], zoom_start=7) folium.TopoJson( open('./data/colorado-counties.json'), object_path='objects.colorado-counties' ).add_to(m) m This renders the base layer, but does not draw the polygons for the counties. I found this other example on stackoverflow and it renders just fine with essentially the same code. m = folium.Map(location=[40.7,-74], zoom_start=10) folium.TopoJson( open('./data/nyc_census_tracts_2010.geojson'), object_path='objects.nyct2010', ).add_to(m) m I can't find any large scale differences between the two files. Is there some topojson version incompatibility?
upvote count: 1
tagged with: geojson
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49076485
score: 1
has title: Python Folium Topojson file not rendering
accepted answer: http://stackoverflow.com/a/49076485
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/42107268
answer count: 1
tagged with: python
tagged with: topojson
tagged with: folium
favorite count: 0

http://stackoverflow.com/a/48976706
has comment: http://stackoverflow.com/comment/84958941
answers question: http://stackoverflow.com/q/48976413
has comment: http://stackoverflow.com/comment/84958693
accepted answer of: http://stackoverflow.com/q/48976413
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84958818
has comment: http://stackoverflow.com/comment/84958482
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84958598
has comment: http://stackoverflow.com/comment/84958636
type: Answer
has body: Is bounding the output variable between 0 and 1 and then running the model an acceptable way of trying to predict an interval variable using a neural network? I suppose that can work if you know the range of values that your output can take in advance. It's certainly not common though. With the following code, you're essentially cheating a bit. You're using all data (training and validation) to compute your bounds for the scaler, whereas only training data should be used. dataset=np.loadtxt("cars.csv", delimiter=",") x=dataset[:,0:5] y=dataset[:,5] y=np.reshape(y, (-1,1)) scaler = MinMaxScaler() print(scaler.fit(x)) print(scaler.fit(y)) xscale=scaler.transform(x) yscale=scaler.transform(y) If you don't cheat like that though, you may get values in the validation data that exceed your bounds. If you then still use a sigmoid, you'll be unable to make correct predictions (which should lie outside [0, 1] if scaled according to bounds determined by training data only). It's much more common to simply end with a linear layer for regression tasks, like Hemen suggested. Your learning process may still benefit from scaling outputs in the training data to [0, 1], but then outputs outside training data could, for example, get mapped to 1.1 if they slightly exceed all values observed in training data.

http://stackoverflow.com/comment/84962526
has text: I found better solution :) now rows is users
type: AnswerComment
comment on: http://stackoverflow.com/a/48978617
type: Comment
score: 0

missing-data
tags question: http://stackoverflow.com/q/48980261
type: Tag
tag name: missing-data
tags question: http://stackoverflow.com/q/49029952

http://stackoverflow.com/a/49086116
has comment: http://stackoverflow.com/comment/85181074
type: Answer
has body: You can use itertools.combinations to make doing it very easy. What you're calling an "array" is referred to as a "list" in Python, by-the-way. from itertools import combinations def maximum_product(nums): return max(trio[0] * trio[1] * trio[2] for trio in combinations(nums, 3)) nums = [-1, -2, -3, 9] print(maximum_product(nums)) # -&gt; 54 This could be generalized to determine the maximum product of N integers by (also) using functools.reduce() to compute the product of N items: from functools import reduce from itertools import combinations def maximum_product(nums, group_size): return max(reduce(lambda a, b: a*b, nums, 1) for group in combinations(nums, group_size)) nums = [-1, -2, -3, 9] print(maximum_product(nums, 3)) # -&gt; 54 Of course, this generality will slow execution down a bit...
answers question: http://stackoverflow.com/q/49084955
has comment: http://stackoverflow.com/comment/85179013
has comment: http://stackoverflow.com/comment/85179096
upvote count: 1
has comment: http://stackoverflow.com/comment/85178883
has comment: http://stackoverflow.com/comment/85178826
has comment: http://stackoverflow.com/comment/85185144
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85178807
has comment: http://stackoverflow.com/comment/85178577

http://stackoverflow.com/q/48971232
upvote count: 3
tagged with: python
has title: Unable to resolve "SyntaxError: invalid syntax"
has answer: http://stackoverflow.com/a/48971248
has answer: http://stackoverflow.com/a/48971313
type: UnansweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84948412
has body: I'm very new to Python and I was attempting to make a silly little pointless piece of code. However, when I try to run the code I get an "invalid syntax" error. This is the code: import time name=input("What would your name happen to be?") print("Hello there,", name,"!") time.sleep(3) ohno=input("Would you like your PC to crash? (Yes or No)") if ohno.lower() == "yes": print("* crashes", name,"'s PC *") else: print("Invalid answer, reload script") if ohno.lower() == "no": print("Okay. Have a nice day,", name) else: print("Invalid answer, reload script") When the error appears, it doesn't even show where the error is. The syntax seems just fine to me.. or I could just be a complete idiot. Well, if anybody can help me, that would be helpful. Thank you in advance!
answer count: 2
downvote count: 2
favorite count: 0

http://stackoverflow.com/comment/85037513
has text: Yah so it would be better to incorporate your function in the TK class like I said and it will work (sit there doing nothing)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49015176

http://stackoverflow.com/q/49026356
tagged with: workflow
score: 0
has answer: http://stackoverflow.com/a/49124280
tagged with: python
type: UnansweredQuestion
tagged with: django
has body: I've a workflow. class WorkFlow1(Flow): start = flow.StartFunction(function1) \ .Next(this.task2) task2 = flow.StartFunction(function2) \ .Next(this.end) end = flow.End() @flow_start_func def function1(activation, **kwargs): print('Func1 Called.') activation.prepare() activation.done() return activation @flow_start_func def function2(activation, **kwargs): print('Func2 Called.') activation.prepare() activation.done() return activation I am able to run the workflow programmatically using `WorkFlowClass.start.run()`. It starts the workflow perfectly, but, does not the completes it. The output of the above snippet is Func1 Called Upon completing Node1(start) of workflow, task2 is not called. Meaning, only first task of the workflow is called, not the subsequent tasks. Why? And how can I execute the complete workflow?
type: Question
tagged with: django-viewflow
has title: Django Viewflow - Run the complete worflow
answer count: 1

http://stackoverflow.com/comment/85084428
score: 0
type: QuestionComment
has text: Don't name variables the same as functions.
type: Comment
comment on: http://stackoverflow.com/q/49039491

http://stackoverflow.com/a/49078315
has body: bigL = [] diminish = 24 i = 10056 while i &gt;= 0: ## Just abstracting the code to easily modify it ... this will run while i is positive bigL.append(range(0, i, diminish)) ## Supply i and diminish and then append the list to bigL i -= diminish ## Reduce i by diminish (by 24 in this case)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49078285
downvote count: 0
score: 1

http://stackoverflow.com/comment/85182062
comment on: http://stackoverflow.com/q/49088214
type: Comment
type: QuestionComment
has text: Please explain further what do you mean when you say that you want to save the value of the `post` field in different variables.
score: 1

http://stackoverflow.com/q/49104411
tagged with: python
has body: I want to plot factor plots for my data. I tried doing it the below way but the chart values didn't turn out as expected. df = pd.DataFrame({'subset_product':['A','A','A','B','B','C','C'], 'subset_close':[1,1,0,1,1,1,0]}) prod_counts = df.groupby('subset_product').size().rename('prod_counts') df['prod_count'] = df['subset_product'].map(prod_counts) g = sns.factorplot(y='prod_count',x='subset_product',hue='subset_close',data=df,kind='bar',palette='muted',legend=False,ci=None) plt.legend(loc='best') However, my plots all have the same height, meaning it didn't separate the data into '1' and '0'. Example: For A, the blue bar should have height = 1, and the green bar should have height = 2.
has title: python seaborn shows bar plots as same height for different class
has answer: http://stackoverflow.com/a/49104671
has comment: http://stackoverflow.com/comment/85213956
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49104671
type: Question
has comment: http://stackoverflow.com/comment/85213935
has comment: http://stackoverflow.com/comment/85214047
score: 0
has comment: http://stackoverflow.com/comment/85214077
tagged with: pandas
answer count: 1
tagged with: seaborn

http://stackoverflow.com/q/49029780
has comment: http://stackoverflow.com/comment/85065804
favorite count: 0
tagged with: qt3d
tagged with: python
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/49031103
has title: Overlapping widgets in QLayout
score: 1
tagged with: pyside2
type: Question
has comment: http://stackoverflow.com/comment/85066318
has comment: http://stackoverflow.com/comment/85065611
tagged with: qt5
has comment: http://stackoverflow.com/comment/85064239
answer count: 2
has answer: http://stackoverflow.com/a/49031103
has answer: http://stackoverflow.com/a/49947929
upvote count: 1
accepted answer: http://stackoverflow.com/a/49947929
tagged with: user-interface
has body: I want to create a window where is Qt3DWindow in the back and some QPushButtons above it. However only Qt3DWindow animation is shown and QPushButtons are not seen. I would also like to have Qt3DWindow functional and QPushButtons as well (So I can click on the buttons or 3D animation behind). Buttons are only seen when I set Qt3DWindow transparency to lower value. Of course in that case buttons are only seen but not functional. class MainWindow(QMainWindow): def __init__(self, *args): QMainWindow.__init__(self, *args) self.window = Window() # Qt3DExtras.Qt3DWindow self.container = self.createWindowContainer(self.window) self.buttons = Buttons() self.layout().addWidget(self.buttons.view) # QtWidgets.QGraphicsView self.layout().addWidget(self.container)

http://stackoverflow.com/a/49031573
has body: pyspark.rdd.RDD.mapPartition method is lazily evaluated. Usually to force an evaluation, you can a method that returns a value on the lazy RDD instance that is returned. There are higher-level functions that take care of forcing an evaluation of the RDD values. e.g. pyspark.rdd.RDD.foreach Since you don't really care about the results of the operation you can use pyspark.rdd.RDD.foreach instead of pyspark.rdd.RDD.mapPartition. def first_of(it): for first in it: return first return [] def insert_first(it): first = first_of(it) item_count = len(first) newObject.full_item(sc, dataBase, item_count, end_date) if len(size_DF) == 0: print('No record present in the truncated list') else: size_DF.forEach(insert_first)
upvote count: 2
answers question: http://stackoverflow.com/q/49023893
has comment: http://stackoverflow.com/comment/85068608
has comment: http://stackoverflow.com/comment/85106468
has comment: http://stackoverflow.com/comment/85070184
score: 2
accepted answer of: http://stackoverflow.com/q/49023893
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85124183
has comment: http://stackoverflow.com/comment/85069377
type: Answer
has comment: http://stackoverflow.com/comment/85068147

http://stackoverflow.com/q/48970632
downvote count: 1
type: AnsweredQuestion
tagged with: heroku
has answer: http://stackoverflow.com/a/48972027
has title: Why can't I keep my articles published recently when I redeploy my flask app on heroku?
type: Question
answer count: 2
tagged with: flask
tagged with: flask-sqlalchemy
score: 0
tagged with: heroku-toolbelt
accepted answer: http://stackoverflow.com/a/48972027
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/48972274
has body: I write a simple script publish.py for publishing articles written in markdown. so i can use: python3 publish.py -a https://MYNAME.herokuapp.com/publish -p article.md -t MYTOKEN to upload my article and save it in my sqlite database test.db my route function: @main.route('/publish', methods=['GET', 'POST']) def publish(): if request.method == 'GET': abort(404) # authorization token = request.form.get('token', '') if token != current_app.config['TOKEN']: return 'invalid access token', 500 title = request.form.get('title', None) if not title: return 'no title found', 500 summary = request.form.get('summary', None) if not summary: return 'no summary found', 500 content = request.form.get('content', None) if not content: return 'no content found', 500 content = markdown2html(content) pub_time = request.form.get('pub_time', None) if pub_time: pub_time = datetime.strptime(pub_time, app.config['TIME_FORMAT']) tags = request.form.getlist('tags') create_article(title, summary, content, pub_time, tags) return '', 200 when I publish an artilce by the script it sames normal, my website can show this article. but when i push new changes on Heroku and restart it, my article published just now disppeared! heroku maintenance:on git push heroku master heroku run python3 manage.py db upgrade heroku restart heroku maintenance:off How can i keep my old articles when i have to push new changes on Heroku. (and it's quite normal if i run my server on my localhost)
has answer: http://stackoverflow.com/a/48972274
upvote count: 1

http://stackoverflow.com/comment/96627075
score: 1
has text: Shouldn't I also uncomment the `SSL=/usr/local/ssl` line in the Setup file?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50888765

http://stackoverflow.com/comment/85002075
type: Comment
comment on: http://stackoverflow.com/a/48998049
has text: @mxbi did you try this version: `idx+np.arange(0, X.shape[0]*X.shape[1], X.shape[1])[:,None]`, I don't think it will be fast enough, but I'm curious if it is faster than the other...
score: 0
type: AnswerComment

http://stackoverflow.com/q/49057495
tagged with: combinatorics
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49057719
linked to: http://stackoverflow.com/q/1482308
score: 0
answer count: 1
has title: Print all combinations of a set with n elements split between subsets with j elements while retaining alphabetical order
tagged with: arrays
has comment: http://stackoverflow.com/comment/85180193
tagged with: sorting
has answer: http://stackoverflow.com/a/49057719
has body: Let's say I have a set with n=3 elements: [a,b,c] Using combinatorics we know that this set has 8 subsets with j elements: [∅], [a], [b], [c], [a,b], [a,c], [b,c], [a,b,c] Now what I want to do using Python is print all of the permutations of these 8 subsets with the constraints being that there must be exactly 3 subsets for each permutation (empty subsets are fine), all elements must be used, and alphabetical order must be maintained within each subset (alphabetical order does not need to be maintained outside of the subset--e.g. [c],[a],[b] is fine). I have attempted something like this: x=1 y=3 for i in set(permutations(chain.from_iterable(set_n))): while x&lt;=3: permuted = sorted([i[:y], i[x:]]) x = x+1 y = y-1 print permuted Where set_n is my set of n elements, but this of course only gives permutations of two subsets and only a single permutation of those two subsets. It's also not maintaining alphabetical order within the subsets.
type: AnsweredQuestion
tagged with: permutation

http://stackoverflow.com/comment/84938092
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48964455
type: AnswerComment
has text: ah okay. one moment i will write an example

http://stackoverflow.com/q/49018263
has comment: http://stackoverflow.com/comment/85042129
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85041995
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85042055
tagged with: pandas
has answer: http://stackoverflow.com/a/49018382
has comment: http://stackoverflow.com/comment/85041832
has body: I am trying to apply a simple function to extract the month from a string column in a pandas dataframe, where the string is of the form m/d/yyyy. The dataframe is called data, the date column is called transaction date, and my new proposed month column I wish to call transaction month. The below works just fine: data['transaction month']=data['transaction date'].map(lambda x: x[0:x.index('/')]) However, if I try to do the same thing with a named function, it just returns a column where every value is None def extract_month_from_date(date): return date[0:date.index('/')] data['transaction month 2']=data['transaction date'].map(extract_month_from_date) I've stared at the code for long enough that I think I'm going crazy, what's wrong with the
answer count: 1
has title: map with named function vs identical lambda function providing different responses, pandas

http://stackoverflow.com/a/49112062
downvote count: 0
answers question: http://stackoverflow.com/q/49112001
score: 1
has body: Instead of [a-z|A-Z]{2} you could use [A-Z]{2} and [a-z]{2} to match SOit. To match the dot before .csv you could escape it \. Try it like this: [0-9]{4}[A-Z]{2}[a-z]{2}_filename_\d{8}_[0-9]{6}\.csv
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49112001

http://stackoverflow.com/comment/85213978
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49101595
has text: Please read why a [screenshot of HTML or code or error is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Consider updating the Question with formatted text based relevant HTML, code trials and error stack trace.
score: 0

http://stackoverflow.com/q/49035988
has comment: http://stackoverflow.com/comment/85079496
tagged with: version
tagged with: python
tagged with: pycharm
answer count: 0
upvote count: 3
tagged with: sys
downvote count: 1
tagged with: platform
has comment: http://stackoverflow.com/comment/85077425
has body: When I use Pycharm, whose default python interpreter is set to be python 2.7.14. When I run the integrated console in Pycharm several line of code bellow, the python versions are confusing. Could someone explain what's the difference between these two commands?
type: UnansweredQuestion
score: 2
has title: Python console: difference between sys.version() and os.system("python -V")
has comment: http://stackoverflow.com/comment/85076915
favorite count: 0
has comment: http://stackoverflow.com/comment/85079309
type: Question

http://stackoverflow.com/comment/85171329
has text: Your view seems OK. You are saving a form, I think the problem come from StudentFileForm
score: 0
comment on: http://stackoverflow.com/q/49082214
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85281691
type: Comment
comment on: http://stackoverflow.com/a/49118621
score: 1
has text: unstack is some kind of pivoting operation. It creates as many columns as you have unique items in your status column, i.e. each possible status gets its own column. Pandas will plots different columns in the grouped fashion as seen in the graph.
type: AnswerComment

http://stackoverflow.com/q/49088524
tagged with: web-scraping
upvote count: 1
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
has title: Search button is not working when search box is filled in
type: Question
downvote count: 0
has body: I've written a scraper in python with selenium to input an address in a searchbox and press the search button. When I run the scraper, it looks like that it fills in the address but when it press the search button to populate results then the site shows please enter Address first. Where I'm going wrong? The search address is embedded within .send_keys() to be tested. Thanks in advance for any help. Site address: website This is my attempt: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) driver.get("replace with above address") wait.until(EC.presence_of_element_located((By.ID, "autocomplete"))).send_keys("5068 SW 141st Ave, Miramar, FL 33027") wait.until(EC.presence_of_element_located((By.ID, "map-search"))).click() driver.quit() Btw, no iframe is there, so I thought it would be as simple as that but turn out the opposite.
accepted answer: http://stackoverflow.com/a/49088642
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49088642
tagged with: python-3.x
tagged with: selenium

http://stackoverflow.com/q/48981282
type: Question
tagged with: numpy
has title: How to make IDLE python display directly results from a function defined and ran from a .py file
tagged with: function
has body: I have tried many set and search quite some time. I'll try to summarize to my problem. I a have a file I name script.py. Inside this script.py I have something like this: import math import numpy as np from numpy import matrix #Inserting variables: A=float(input("insert position 1: ")) K=float(input("insert position 2: ")) #Doing some math: a1=A*K a2=A/K #Defining a funtion: def solve(var1,var2) #This function uses numpy and math and handles matrices. #I am not putting it to save space and make my problem clear #Calling the funtion: solve(a1,a2) print (solve) #The values of a1 and a2 are the once I calculated previously Then I press "run module" to run script.py, it shows: &gt;&gt; insert position 1: &gt;&gt; insert position 2: I insert the values and then it shows: &lt;function solve at 0x000000000A0C1378&gt; What can I do to make the python shell display the result directly? Currently in order to get the results I need to type in the python shell &gt;&gt; solve(a1,a2) to have my result. I hope I was able to make my problem clear and simple. Thanks.
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48981317
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48981317
score: 1

http://stackoverflow.com/comment/85041570
has text: Sorry I've just realized that while that helps with matching it does not exactly match the words. It will still pick up similar words containing the original such as when searching for QD it will flag as a positive if SYQD is in the list that it is search from. How can I go about fixing this?
type: Comment
comment on: http://stackoverflow.com/a/49017138
type: AnswerComment
score: 0

http://stackoverflow.com/comment/120961666
type: QuestionComment
has text: did you try: did you try `conda install -y networkx">=2.5"`?
type: Comment
comment on: http://stackoverflow.com/q/49105282
score: 0

http://stackoverflow.com/comment/85062752
score: 0
type: Comment
type: QuestionComment
has text: `assert all(len(i) > 3 for i in lst), "not all sublists are long enough"`
comment on: http://stackoverflow.com/q/49029226

http://stackoverflow.com/comment/85153293
score: 0
has text: Also, try traveling to the `BASE_URL` first, then going to `&page=x` to see if you have to load the domain before traveling to those pages. Can you share the **site** with us?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49073298

http://stackoverflow.com/q/49023337
has comment: http://stackoverflow.com/comment/85051501
has answer: http://stackoverflow.com/a/49023961
type: Question
tagged with: python
answer count: 1
tagged with: svd
score: 0
has body: svd formular： A ≈ UΣV* I use numpy.linalg.svd to run svd algorithm. And I want to set dimension of matrix. For example: A=3*5 dimension, after running numpy.linalg.svd, U=3*3 dimension, Σ=3*1 dimension, V*=5*5 dimension. I need to set specific dimension like U=3*64 dimension, V*=64*5 dimension. But it seems there is no optional dimension parameter can be set in numpy.linalg.svd.
accepted answer: http://stackoverflow.com/a/49023961
tagged with: scipy
tagged with: numpy
has title: set dimension of svd algorithm in python
type: AnsweredQuestion

http://stackoverflow.com/a/49113159
has body: You can use unstack to reshape the data frame. Also,based on your given output, I assume you want to to drop inspector_name where one of the compliance (positive or negative) is not available. ## sample data df = pd.DataFrame({'inspector_name':['Addison, Michael','Addison, Michael','Ahmad, Muna I','Ahmad, Muna I','Anderson, Trevis'], 'compliance': [0.0,1.0,0.0,1.0,0.0], 'compliance_detail':[0.4312, 0.0340, 0.7314,0.052,0.1666]}) df = df.set_index(['inspector_name','compliance']) ## solution df = df.unstack().dropna().reset_index() df.columns = ['inspector_name','negative_complaince','positive_complaince'] df inspector_name negative_complaince positive_complaince 0 Addison, Michael 0.4312 0.034 1 Ahmad, Muna I 0.7314 0.052
type: Answer
has comment: http://stackoverflow.com/comment/85231575
score: 0
answers question: http://stackoverflow.com/q/49112472

http://stackoverflow.com/q/48968251
has comment: http://stackoverflow.com/comment/84942174
type: AnsweredQuestion
has body: In previous versions of numpy, I was able to do something like this: data = np.array([(0,1,2),(3,4,5),(6,7,8)], dtype=np.dtype([('a','&lt;f8'), ('b','&lt;f8'),('c','&lt;f8')])) data_nd = data'a','b'.view(('&lt;f8',2)) and this would give me a view of the original recarray data as a 2 dimensional ndarray of type np.float32. In numpy version 1.14 when I try the second line above I get the error: ValueError: Changing the dtype to a subarray type is only supported if the total itemsize is unchanged This is because the itemsize of data'a','b' is still 24. Okay, that's fine, but is there some way to get a copy of those columns of data that updates the itemsize so that I can make the view that I want? For instance, even making a copy (or deep copy) of data'a','b' still results in an itemsize of 24, which I don't understand.
has title: View of recarray as ndarray
type: Question
tagged with: numpy
tagged with: numpy-ndarray
score: 0
has answer: http://stackoverflow.com/a/48968365
accepted answer: http://stackoverflow.com/a/48968365
answer count: 1
tagged with: python-2.7
tagged with: python

http://stackoverflow.com/comment/85042014
type: QuestionComment
score: 0
has text: once it's hashable, I get another error saying that I can't compare types. But this error goes away if I comment out the tuple. Any idea why that might be?
comment on: http://stackoverflow.com/q/49018295
type: Comment

http://stackoverflow.com/comment/85235898
type: Comment
has text: it is very helpful but how can I scale this for suppose 2 entities i.e. college1 Ownership: Private Institute Type: Affiliated College college2 Ownership: Private Institute Type: Affiliated College
comment on: http://stackoverflow.com/a/49104002
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85137265
type: AnswerComment
comment on: http://stackoverflow.com/a/49065643
type: Comment
has text: Nope, I just wanted to remove all directories above and including `package1`. Thanks for the help!
score: 0

http://stackoverflow.com/comment/85176741
type: AnswerComment
score: 0
type: Comment
has text: @Bugs_Bunny - Glad can help!
comment on: http://stackoverflow.com/a/49082111

semaphore
type: Tag
tag name: semaphore
tags question: http://stackoverflow.com/q/48971121

http://stackoverflow.com/q/49090488
has body: I am not sure if it is the right expression, but searching merge or change index didn't get me anywhere. Basically I have two dataframes: df_A = pd.DataFrame(1, index=[1,2,3], columns = [1,2,3]) df_B = pd.DataFrame(0, index=[1,2,4], columns = [1,2,5]) I want to transform df_A and df_B such that both share the same index and columns, which are the unions of the two. The missing values will be filled with NaN: df_A_new: 1 2 3 5 index 1 1 1 1 NaN 2 1 1 1 NaN 3 1 1 1 NaN 4 NaN NaN NaN NaN df_B_new: 1 2 3 5 index 1 0 0 NaN 0 2 0 0 NaN 0 3 NaN NaN NaN NaN 4 0 0 NaN 0
has answer: http://stackoverflow.com/a/49090519
tagged with: indexing
type: AnsweredQuestion
downvote count: 0
type: Question
tagged with: union
has title: union of two dataframes' index and columns
score: 4
tagged with: pandas
answer count: 1
tagged with: python
upvote count: 4
accepted answer: http://stackoverflow.com/a/49090519
favorite count: 0

http://stackoverflow.com/a/49012383
upvote count: 2
score: 2
has body: What happens is that the text widget still gets the return you entered. Binding the Enter does not inhibits the propagation of the event after your function ends, unless you alter it to cancel event propagation by returning the break string, like this: def hi(event): print(txt.get('1.0',END)) txt.delete('1.0',END) return 'break'
downvote count: 0
answers question: http://stackoverflow.com/q/49011948
type: Answer

http://stackoverflow.com/comment/85011937
comment on: http://stackoverflow.com/q/49003742
score: 0
has text: Did you try using regular expressions ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49035943
has comment: http://stackoverflow.com/comment/85078265
type: Question
has body: Unless I'm mistaken, this isn't a SO duplicate. I'm not using Tornado, I just want to send a ping frame every 30s to keep the connection alive using the websockets library. Being a risk taker, I had a guess but I don't know what to make of the server reply: import websockets import asyncio async def test_ping(): websocket = await websockets.connect('wss://api.example.com') reply = await websocket.ping() print(reply) loop = asyncio.new_event_loop() loop.create_task(test_ping()) loop.run_forever() &gt;&gt; &lt;Future pending&gt; (I already have an established connection to produce the 'Future pending' response.)
has comment: http://stackoverflow.com/comment/85077163
has comment: http://stackoverflow.com/comment/85076975
has title: Python websockets send ping frame
has comment: http://stackoverflow.com/comment/85078587
has answer: http://stackoverflow.com/a/52633401
answer count: 1
downvote count: 0
tagged with: websocket
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: ping
score: 2
has comment: http://stackoverflow.com/comment/85077601
upvote count: 2

http://stackoverflow.com/comment/85184460
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49089398
has text: @MartijnPieters and what I must to do?
score: 0

http://stackoverflow.com/q/48979835
downvote count: 5
tagged with: google-colaboratory
has title: Accelerating python processing.. [Google Colab]
answer count: 1
has answer: http://stackoverflow.com/a/49004881
favorite count: 0
has body: I have a python program which I want to accelerate using GPU on Google colaboratory. The program have basic for looping, reading and writing to file operations. I ran the file on google colab. and found no change in execution time. How could I accelerate python's for loops, reading and writing to files? Can I accelerate these operations on a GPU? Thank You.
tagged with: python
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/49004881
type: Question
score: -2

tkinter
tags question: http://stackoverflow.com/q/49021710
tags question: http://stackoverflow.com/q/49028505
tags question: http://stackoverflow.com/q/49061798
tags question: http://stackoverflow.com/q/49035753
tags question: http://stackoverflow.com/q/49020380
tags question: http://stackoverflow.com/q/49094361
tags question: http://stackoverflow.com/q/49049616
tags question: http://stackoverflow.com/q/49013196
tags question: http://stackoverflow.com/q/49028756
tags question: http://stackoverflow.com/q/48970091
tags question: http://stackoverflow.com/q/49086833
tags question: http://stackoverflow.com/q/48996961
tags question: http://stackoverflow.com/q/49027916
tags question: http://stackoverflow.com/q/49026353
tags question: http://stackoverflow.com/q/49064856
tags question: http://stackoverflow.com/q/48972683
tags question: http://stackoverflow.com/q/49110675
tags question: http://stackoverflow.com/q/49084946
tag name: tkinter
tags question: http://stackoverflow.com/q/49085244
tags question: http://stackoverflow.com/q/49067147
tags question: http://stackoverflow.com/q/49075036
tags question: http://stackoverflow.com/q/49082572
tags question: http://stackoverflow.com/q/49083816
tags question: http://stackoverflow.com/q/48983443
tags question: http://stackoverflow.com/q/49036021
tags question: http://stackoverflow.com/q/49091718
tags question: http://stackoverflow.com/q/49095720
tags question: http://stackoverflow.com/q/48977312
tags question: http://stackoverflow.com/q/49081910
tags question: http://stackoverflow.com/q/48974730
tags question: http://stackoverflow.com/q/48983657
tags question: http://stackoverflow.com/q/48993468
tags question: http://stackoverflow.com/q/49035368
tags question: http://stackoverflow.com/q/48991022
tags question: http://stackoverflow.com/q/49035768
tags question: http://stackoverflow.com/q/48983638
tags question: http://stackoverflow.com/q/49017146
tags question: http://stackoverflow.com/q/49020819
tags question: http://stackoverflow.com/q/48991884
tags question: http://stackoverflow.com/q/49018192
tags question: http://stackoverflow.com/q/49061602
tags question: http://stackoverflow.com/q/49096649
tags question: http://stackoverflow.com/q/49052789
tags question: http://stackoverflow.com/q/49032951
tags question: http://stackoverflow.com/q/49006896
tags question: http://stackoverflow.com/q/49061458
tags question: http://stackoverflow.com/q/48964879
tags question: http://stackoverflow.com/q/49072942
tags question: http://stackoverflow.com/q/48987503
tags question: http://stackoverflow.com/q/48972560
tags question: http://stackoverflow.com/q/48992757
tags question: http://stackoverflow.com/q/48964977
tags question: http://stackoverflow.com/q/49059108
tags question: http://stackoverflow.com/q/49038809
tags question: http://stackoverflow.com/q/49001710
tags question: http://stackoverflow.com/q/49070420
tags question: http://stackoverflow.com/q/49041512
tags question: http://stackoverflow.com/q/49098565
tags question: http://stackoverflow.com/q/49101325
tags question: http://stackoverflow.com/q/49087598
tags question: http://stackoverflow.com/q/48982496
tags question: http://stackoverflow.com/q/49098600
tags question: http://stackoverflow.com/q/49020287
tags question: http://stackoverflow.com/q/49048124
tags question: http://stackoverflow.com/q/49010193
tags question: http://stackoverflow.com/q/49082862
tags question: http://stackoverflow.com/q/49070292
tags question: http://stackoverflow.com/q/49037051
tags question: http://stackoverflow.com/q/49020555
tags question: http://stackoverflow.com/q/49041160
tags question: http://stackoverflow.com/q/49032298
tags question: http://stackoverflow.com/q/49067547
tags question: http://stackoverflow.com/q/49094318
tags question: http://stackoverflow.com/q/49035257
tags question: http://stackoverflow.com/q/48966649
tags question: http://stackoverflow.com/q/49067263
tags question: http://stackoverflow.com/q/48977473
tags question: http://stackoverflow.com/q/49013237
tags question: http://stackoverflow.com/q/49058775

http://stackoverflow.com/a/49086708
answers question: http://stackoverflow.com/q/49086551
type: Answer
downvote count: 0
score: 2
upvote count: 2
has body: You're using command wrong. Replace: Button(..., command=ListPopulate(listlist)) with: Button(..., command=lambda l=ListUpdate(): ListPopulate(l))

http://stackoverflow.com/comment/84963347
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48979104
has text: Or he could just use `print` by itself @jonrsharpe: `print('Good job, ' + myName + '! You guessed my number in ', guessesTaken, ' guesses!')`. Or he could just use `str` without using a variable - albeit it would be a bit ugly. There are many options, OP, do a bit of research and choose one.
type: QuestionComment

http://stackoverflow.com/comment/85116660
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49021760
type: Comment
has text: May I ask you to mark my answer as the right answer?

http://stackoverflow.com/comment/85107181
comment on: http://stackoverflow.com/q/49049940
type: QuestionComment
type: Comment
score: 1
has text: Besides the answers, avoid `os.system('cls')` like the plague. It is the code equivalent of having your frontdoor lock broken and calling a locksmith each time you are leaving or arriving home (instead of asking him to fix it) . (You create an external process just to erase the screen, and it is a system dependent command).

http://stackoverflow.com/a/49033388
score: 0
answers question: http://stackoverflow.com/q/49032242
type: Answer
has body: It works perfectly for me. On MacOS, you should perhaps remove or comment the second line (os.system("clear all")) that supposed to clear the terminal screen but doen't change the result. The output is: Retrieving http://py4e-data.dr-chuck.net/comments_55310.json User count: 2 total sum is 2351 If it still doen't work, I suspect it hangs fetching http://py4e-data.dr-chuck.net/comments_55310.json with your internet connection that seems unstable.
has comment: http://stackoverflow.com/comment/85078292
has comment: http://stackoverflow.com/comment/85138493

http://stackoverflow.com/q/48991760
has comment: http://stackoverflow.com/comment/84989329
has title: Unexpected behavior with Tkinter and two Listboxes bound to ListboxSelect event
has comment: http://stackoverflow.com/comment/84988647
type: Question
has answer: http://stackoverflow.com/a/61364019
tagged with: python
tagged with: tkinter
upvote count: 2
has body: I’ve encountered an unusual problem in a script that I’m working on. The program is written in Python3/Tkinter. It initializes two Listboxes, wrapped in two separate Frames, and according to the user’s commands displays either one or the other. An exception arises when the user selects on one of the items in the first Listbox, then decides to change screen and selects an item in the second frame. I’ve created a sample code (below), to replicate the problem. With this code, during runtime, clicking on one item in the first Listbox (white background) makes the second Listbox appear (orange background). Also, the first object is “unpacked” and thus the user should no longer be able to interact with it. Finally, clicking on an item in the second Listbox, raises an IndexError in the “on_select_1” method from the first object. Why would that method execute after that event?? I’m well aware of my limits as a programmer, but I’m pretty sure this is not what is supposed to happen. import tkinter as tk class Listbox1(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.lb1 = tk.Listbox(self) for i in ["item 1.1", "item 1.2", "item 1.3", "item 1.4"]: self.lb1.insert(tk.END, i) self.lb1.bind("&lt;&lt;ListboxSelect&gt;&gt;", self.on_select_1) self.lb1.pack() def on_select_1(self, *args): try: print("item {} selected in listbox 1".format(self.lb1.curselection()[0])) except IndexError: print("IndexError raised in method 'on_select_1'") self.master.switch() class Listbox2(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.lb2 = tk.Listbox(self, bg='orange') for i in ["item 2.1", "item 2.2", "item 2.3", "item 2.4"]: self.lb2.insert(tk.END, i) self.lb2.bind("&lt;&lt;ListboxSelect&gt;&gt;", self.on_select_2) self.lb2.pack() def on_select_2(self, *args): print("item {} selected in listbox 2".format(self.lb2.curselection()[0])) class App(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.pack() self.lb1_frame = Lis…
accepted answer: http://stackoverflow.com/a/48992537
answer count: 3
has answer: http://stackoverflow.com/a/48992537
possible better answer: http://stackoverflow.com/a/48991937
linked to: http://stackoverflow.com/q/14467604
has answer: http://stackoverflow.com/a/48991937
score: 2
type: AnsweredQuestion
tagged with: listbox
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/85113520
comment on: http://stackoverflow.com/a/49021760
type: AnswerComment
score: 0
type: Comment
has text: Thank you very much, sorry I am not expert in python, and did not know why the positions are shown in float. I have mostly worked with Matlab and I was thinking if I convert the coordinates to int, I may be wrong. Thanks once again

http://stackoverflow.com/q/49112683
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
has title: AttributeError when using theano backend with CPU
type: Question
accepted answer: http://stackoverflow.com/a/49113307
tagged with: theano
has body: I am trying to run this python notebook where a well known convolutional neural network is implemented using Keras. The author uses theano as a backend and uses his cpu device. Because my CPU is not supported by CUDA (which is needed to use it) i will try to use my gpu (to begin with). I installed keras and theano plus the needed requirements following this link. I skipped the gpu configuration since I want to use my GPU. To use my GPU I changed the device flag in one of the first lines resulting in this: #%matplotlib inline import numpy as np import pandas as pd import sys from skimage.io import imread from matplotlib import pyplot as plt import os os.environ['KERAS_BACKEND'] = 'theano' os.environ['THEANO_FLAGS'] = 'mode=FAST_RUN, device=cpu, floatX=float32, optimizer=fast_compile' from keras import models from keras.optimizers import SGD This gives me an error: AttributeError: ('This name is already taken', 'floatX') I found solutions but primarily for GPU users. I also read somewhere that I have to delete a $HOME/.theanorc file, however I cannot find this file. Can anyone shed some light on what causes this error and how to solve this?
has answer: http://stackoverflow.com/a/49113307
score: 0
answer count: 1
tagged with: keras

http://stackoverflow.com/q/49040796
has answer: http://stackoverflow.com/a/49040834
accepted answer: http://stackoverflow.com/a/49040834
has answer: http://stackoverflow.com/a/49040832
has answer: http://stackoverflow.com/a/53905938
upvote count: 2
downvote count: 2
tagged with: for-loop
has title: For Loop in a Function for Counting Vowels in a User Inputted String
has comment: http://stackoverflow.com/comment/85086910
tagged with: function
has answer: http://stackoverflow.com/a/49040856
answer count: 7
has answer: http://stackoverflow.com/a/49040887
favorite count: 0
score: 0
possible better answer: http://stackoverflow.com/a/49040832
tagged with: python
has body: I am attempting to run a for loop in a function that is designed to count the vowels in a user inputted string. However, the error "builtins: TypeError" keeps appearing. I have tried simply using the length of the string, using the len function, but the error simply won't go away, and the code is ultimately broken because of this. Is there a solution to this? Screenshot of the code with the error message showing For instance, I first ask the user to input a string. It is then supposed to use the function, called in the print statement, to count the vowels in the user inputted string. Currently, when typing a string, such as Kay, it produces an error code on line 6 that states "for char in (string):" which is the beginning of the for loop. The purpose of this loop is to ensure all letters are being checked for vowels before the code quits. There is a proper indentation, indicated by the lack of error and the principles of computer science and programming. The user inputted portion, which states "string= input("Please enter a phrase. ")" defines the variable string, and is placed at the top of the code.
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53444206
has answer: http://stackoverflow.com/a/49041154
type: Question

http://stackoverflow.com/comment/84960851
score: 0
has text: The queue has an ID is 00, and that persom has duration of 350-200=150 minutes
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48977743

http://stackoverflow.com/comment/137179932
type: Comment
comment on: http://stackoverflow.com/q/49119633
score: 0
type: QuestionComment
has text: The error message does not seem to match the code. The error message suggests the "`else`" has actually been indented seven more spaces than the "`if`", thus causing "`IndentationError: unexpected indent`". The indentation levels are not required to be consistent.

http://stackoverflow.com/comment/120749064
type: AnswerComment
comment on: http://stackoverflow.com/a/51116910
score: 0
type: Comment
has text: Indeed, there is no need for mutex in most cases. The only place a mutex is used is for logical reasons (for example shared data structure that should be locked from connection start to finish)

http://stackoverflow.com/a/49084644
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49084393
has body: I believe your code does not meet your requirements: You want to find which elements in list1 are also in list2. The result should be [48, 33, 46], but your result is [48, 46]. This is because after it finds 48 as a duplicate, 48 is deleted from list1. During this process, the index of 33 changes from 1 to 0. This means that the for can not iterate over this element, as now it wants to iterate from index 1. So 33 is missed. The correct code is: list1 = [48, 33, 46, 46, 87, 11, 50, 99, 65, 87] list2 = [48, 33, 46] # duplicates = [list1.pop(list1.index(i)) for i in list1 if i in list2] duplicates = list(set([i for i in list1 if i in list2])) print duplicates And the main thing here is a python list comprehension. Explain new code logic: 1. iterate 1st element of `list1` and find it in `list2`, so pick it. 2. repeat step 1 3. finally you get [48, 33, 46, 46], use `set` to change to [48, 33, 46], and use `list` to chanage back to list Your old code logic: 1. iterate 1st element of `list1` and find it in `list2`, so pick it. 2. after pick it, you get the index of 1st element, then pop it (delete it from `list1` and return the element) so for this iterate, you get `48` 3. then you want to iterate 2rd element of `list1`, that supposed to be `33`; however, during the process of step2, you delete the `48`, so `33` becomes the 1st element, nolonger the 2rd element, so when you iterate, you missed the `33` & directly iterate to the `46` 4. for these not in `list2`, will not be handled.
type: Answer
score: 4

http://stackoverflow.com/q/48980029
has comment: http://stackoverflow.com/comment/84965191
accepted answer: http://stackoverflow.com/a/48981104
has answer: http://stackoverflow.com/a/57486033
has title: Catch proxy errors on requests python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/66155548
answer count: 3
possible better answer: http://stackoverflow.com/a/57486033
linked to: http://stackoverflow.com/q/16511337
downvote count: 0
favorite count: 0
tagged with: proxy
has answer: http://stackoverflow.com/a/48981104
tagged with: python
has body: I'm new on python so I'm having some trouble. I'm trying to build a tool that posts data to an external server with proxy. I have it working, but the problem is I don't know how to catch the proxy connection error and print something else. The code I wrote is: import requests from bs4 import BeautifulSoup headers = { "User-Agent": "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11", "Content-Type": "application/json" } proxies = { "https": "https://244.324.324.32:8081", } data = {"test": "test"} r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers) print(r.text) How can I print, for example "Proxy Connection Error", when the proxy is dead (not connecting/working) or something like this. This is my first time using python so I'm having trouble. Thank You
type: AnsweredQuestion
tagged with: python-requests
type: Question

http://stackoverflow.com/comment/90025221
score: 0
type: QuestionComment
type: Comment
has text: A solution: https://stackoverflow.com/a/50827230/1198074
comment on: http://stackoverflow.com/q/49028254

http://stackoverflow.com/comment/94054637
score: 3
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49059414
has text: found it - extra_compile_args=['-fopenmp', '-march=native'], extra_link_args=['-fopenmp', '-march=native'], https://stackoverflow.com/questions/30631091/optimizing-simple-cpu-bound-loops-using-cython-and-replacing-a-list

http://stackoverflow.com/comment/84989322
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48992036
score: 0
has text: @jackotonye I've update my post

http://stackoverflow.com/comment/85246091
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by the Nth number? What is your expected output?
comment on: http://stackoverflow.com/q/49120260

http://stackoverflow.com/q/48996872
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48997012
has title: Get Element from XML
has comment: http://stackoverflow.com/comment/84999156
tagged with: web-scraping
type: Question
accepted answer: http://stackoverflow.com/a/48997012
score: 0
answer count: 1
has body: I want to get the elements from a XML that can be fetched from a URL. I have written the following code import xml.etree.ElementTree as ET url = 'https://www.sec.gov/Archives/edgar/data/1568219/000156821918000001/primary_doc.xml' req = ulib.Request(url) primaryXML = ulib.urlopen(req) xmlData = primaryXML.read() content = ET.fromstring(xmlData) The XML that is available is 13F-HR LIVE false false false 0001568219 XXXXXXXX 12-31-2017 <reportCalendarOrQuarter>12-31-2017</reportCalendarOrQuarter> TD Ameritrade Trust Co <com:street1>PO BOX 17748</com:street1> <com:city>DENVER</com:city> <com:stateOrCountry>CO</com:stateOrCountry> <com:zipCode>80217-0748</com:zipCode> 13F HOLDINGS REPORT 028-15163 <provideInfoForInstruction5>N</provideInfoForInstruction5> Erik Hunt Senior Analyst 303-294-5311 Erik Hunt Denver CO 02-26-2018 <otherIncludedManagersCount>0</otherIncludedManagersCount> 20 268468 false I want to get the value of submissionType When I try content.find("edgarSubmission/headerData/submissionType") I dont get any result. I want to get 13F-HR Can someone please explain what I am doing wrong ?

http://stackoverflow.com/q/48971438
favorite count: 0
tagged with: binary
has answer: http://stackoverflow.com/a/48971638
tagged with: python
tagged with: signed
tagged with: hex
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/48971735
has body: I was wondering if theres any easy and fast way to obtain the decimal value of a signed hex in python. What I do to check the value of a hex code is just open up python in terminal and type in the hex, it returns the decimal like this: &gt;&gt;&gt;0x0024 36 &gt;&gt;&gt;0xcafe 51966 So I was wondering, is there any way that I could do that for signed short hex? for example 0xfffc should return -4
type: Question
has title: Signed decimal from a signed hex short in python
answer count: 3
has answer: http://stackoverflow.com/a/48971735
upvote count: 1
has answer: http://stackoverflow.com/a/48971481
accepted answer: http://stackoverflow.com/a/48971481

http://stackoverflow.com/q/49014214
has comment: http://stackoverflow.com/comment/85034875
answer count: 1
tagged with: email
has comment: http://stackoverflow.com/comment/85035799
has comment: http://stackoverflow.com/comment/85037476
tagged with: python
has comment: http://stackoverflow.com/comment/85034291
has body: I'm trying to send emails and attach a VCF file, but I'm running into some trouble. I've managed to send emails with plain text without any issues, but here's the error I'm getting when I run my code now: AttributeError: 'file' object has no attribute 'rfind' And my code: import vobject import requests import smtplib from os.path import basename from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication j = vobject.vCard() j.add('n') j.n.value = vobject.vcard.Name(family='Harris', given='Jeffrey') j.add('fn') j.fn.value = 'Jeffrey Harris' j.add('email') j.email.value = 'jeffrey@osafoundation.org' j.email.type_param = 'Internet' k = j.serialize() with open ('new.vcf', 'w') as file: file.write(k) with open('new.vcf', 'rb') as fil: part = MIMEApplication( fil.read(), Name=basename(fil) ) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(fil) msg = MIMEMultipart() msg['From'] = 'me@myemail.com' msg['To'] = 'me@myemail.com' msg['Subject'] = 'test' message = 'test' msg.attach(part) mailserver = smtplib.SMTP('secure.emailsrvr.com',587) mailserver.ehlo() mailserver.starttls() mailserver.ehlo() mailserver.login('me@myemail.com', 'mypassword') mailserver.sendmail('me@myemail.com','me@myemail.com',msg.as_string()) mailserver.quit() Any ideas on what I'm doing wrong?
type: AnsweredQuestion
has title: Adding email attachments using smtplib
type: Question
has comment: http://stackoverflow.com/comment/85034556
tagged with: smtplib
has answer: http://stackoverflow.com/a/49017370
accepted answer: http://stackoverflow.com/a/49017370
tagged with: smtp
has comment: http://stackoverflow.com/comment/85034784
score: 0

http://stackoverflow.com/q/49103913
has body: I have a graph where each node have three attributes: 'name', 'type', 'tag'. I want to create a function to check whether a node exists for a given attribute and value. For example: check if a node with attribute 'tag' = '1' exists. I wrote the following code: def find_node(gr, att, val): nodesAt5 = filter(lambda (n, d): d[att] == val, gr.nodes(data=True)) return nodesAt5 And I call the function as: if not find_node(G, 'tag', w): # do something It gives this error: KeyError: 'tag' Any suggestions?
accepted answer: http://stackoverflow.com/a/49110331
has title: Check whether a node exists in networkx
possible better answer: http://stackoverflow.com/a/49103937
has comment: http://stackoverflow.com/comment/85215702
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49103937
score: 1
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: python
tagged with: networkx
has comment: http://stackoverflow.com/comment/85212997
has answer: http://stackoverflow.com/a/49110331
has comment: http://stackoverflow.com/comment/85212970
has comment: http://stackoverflow.com/comment/85213020
downvote count: 1
has comment: http://stackoverflow.com/comment/85213033

http://stackoverflow.com/comment/85014004
comment on: http://stackoverflow.com/q/49004682
type: Comment
type: QuestionComment
has text: In *Pythonland*, juggling with index positions that much can get you arrested.
score: 1

http://stackoverflow.com/comment/123798250
type: AnswerComment
has text: Do note that the min_count argument is only valid for certain pandas resampler method (like sum, min, max). Using the min_count argument in other methods (like mean, std) will raise an UnSupportedFunctionCall.
comment on: http://stackoverflow.com/a/60821359
type: Comment
score: 2

http://stackoverflow.com/q/49085756
has answer: http://stackoverflow.com/a/49085781
has title: how to remove first and last character of a string if it is special character using regex in python
type: Question
has comment: http://stackoverflow.com/comment/85176972
downvote count: 4
has answer: http://stackoverflow.com/a/49086179
has answer: http://stackoverflow.com/a/49085963
upvote count: 0
has comment: http://stackoverflow.com/comment/85176884
tagged with: string
has answer: http://stackoverflow.com/a/49085822
accepted answer: http://stackoverflow.com/a/49085781
tagged with: regex
possible better answer: http://stackoverflow.com/a/49085822
answer count: 4
favorite count: 0
score: -4
tagged with: python
has body: I have a list like, mylist=["'one'","{two}","'three'","four","{{{five}}}","s*ix"] For each element, I want to remove the first and last character if it is a special character (other than a-z). My desired output is, out_list=["one","two","three","four","{{five}}","s*ix"]
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/85040318
comment on: http://stackoverflow.com/q/49017577
has text: _"it turns out it exists"_. Are you sure about that? Try `b[a==3] = 9` and see if it has the effect you expect.
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/49018227
has title: Python issue with pycurl and openssl
favorite count: 0
downvote count: 0
has answer: http://stackoverflow.com/a/52976331
type: UnansweredQuestion
upvote count: 4
tagged with: pycurl
has comment: http://stackoverflow.com/comment/85041841
has comment: http://stackoverflow.com/comment/85041804
type: Question
tagged with: openssl
answer count: 1
score: 4
has body: I am trying to run code that uses pycurl but when I do i get the following error: uilleann-pipes-160:data_collection Jim$ python xlsxDownloader.py Traceback (most recent call last): File "xlsxDownloader.py", line 21, in &lt;module&gt; from import_hedgehogs import Link File "/Users/Jim/Documents/Hedgehogs/hedgehogs/data_collection/import_hedgehogs.py", line 8, in &lt;module&gt; import pycurl ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other) When I do "which pycurl" in terminal it gives no output so I then tried installing pycurl using "pip install pycurl". However, When I do that I get the following error: uilleann-pipes-160:data_collection Jim$ pip install pycurl Collecting pycurl Using cached pycurl-7.43.0.1.tar.gz Installing collected packages: pycurl Running setup.py install for pycurl ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/zw/hmv25ltn4hxcr3t9lrx7fc9r0000gn/T/pip-build-gqCefl/pycurl/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/zw/hmv25ltn4hxcr3t9lrx7fc9r0000gn/T/pip-Vbtxf4-record/install-record.txt --single-version-externally-managed --compile: Using curl-config (libcurl 7.54.0) running install running build running build_py creating build creating build/lib.macosx-10.13-intel-2.7 creating build/lib.macosx-10.13-intel-2.7/curl copying python/curl/__init__.py -&gt; build/lib.macosx-10.13-intel-2.7/curl running build_ext building 'pycurl' extension creating build/temp.macosx-10.13-intel-2.7 creating build/temp.macosx-10.13-intel-2.7/src cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRA…
has comment: http://stackoverflow.com/comment/85042442
has comment: http://stackoverflow.com/comment/85041603
has comment: http://stackoverflow.com/comment/88801303
tagged with: python

http://stackoverflow.com/q/48997764
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48997863
upvote count: 3
has body: The following PyQt4 example demonstrates my problem. The text in the QTableWidget cells is centered nicely, until you edit the cells. When you edit a cell the text is left justified. I would like to maintain center alignment during edit of each cell. import sys from PyQt4 import QtGui from PyQt4 import QtCore from PyQt4 import Qt from PyQt4.QtCore import * from PyQt4.QtGui import * class MainWindow(QtGui.QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.table = QtGui.QTableWidget(parent=self) self.table.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers) self.table.setColumnCount(2) self.table.setRowCount(2) self.table.setHorizontalHeaderLabels(['col1','col2']) self.table.setVerticalHeaderLabels(['row1','row2']) item = QtGui.QTableWidgetItem('x') item.setFlags(Qt.NoItemFlags | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setTextAlignment(Qt.AlignHCenter|Qt.AlignVCenter|Qt.AlignCenter) self.table.setItem(0, 0, item) item = QtGui.QTableWidgetItem('x') item.setFlags(Qt.NoItemFlags | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setTextAlignment(Qt.AlignHCenter|Qt.AlignVCenter|Qt.AlignCenter) self.table.setItem(0, 1, item) item = QtGui.QTableWidgetItem('x') item.setFlags(Qt.NoItemFlags | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setTextAlignment(Qt.AlignHCenter|Qt.AlignVCenter|Qt.AlignCenter) self.table.setItem(1, 0, item) item = QtGui.QTableWidgetItem('x') item.setFlags(Qt.NoItemFlags | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setTextAlignment(Qt.AlignHCenter|Qt.AlignVCenter|Qt.AlignCenter) self.table.setItem(1, 1, item) layout = QtGui.QGridLayout() layout.addWidget(self.table, 1, 0) self.setLayout(layout) ################################################################ if __name__ == "__main__": app = QtGui.QApplication(sys.argv) app.setStyle("Plastique") # set style myapp = MainWindow() # instantiate the main window myapp.show() # show the…
has title: Centering Text in QTableWidgetItem during cell Edit
type: Question
tagged with: qtablewidget
tagged with: pyqt4
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48997863

django-templates
tags question: http://stackoverflow.com/q/49084214
tags question: http://stackoverflow.com/q/49093652
tags question: http://stackoverflow.com/q/49009527
tags question: http://stackoverflow.com/q/49009169
tag name: django-templates
tags question: http://stackoverflow.com/q/49099308
type: Tag
tags question: http://stackoverflow.com/q/49055570
tags question: http://stackoverflow.com/q/49108090
tags question: http://stackoverflow.com/q/48992253
tags question: http://stackoverflow.com/q/49017014
tags question: http://stackoverflow.com/q/48982838
tags question: http://stackoverflow.com/q/48969292
tags question: http://stackoverflow.com/q/49031201
tags question: http://stackoverflow.com/q/49077361
tags question: http://stackoverflow.com/q/49048536
tags question: http://stackoverflow.com/q/49023207
tags question: http://stackoverflow.com/q/49085748
tags question: http://stackoverflow.com/q/49090272
tags question: http://stackoverflow.com/q/49003113
tags question: http://stackoverflow.com/q/49072454

http://stackoverflow.com/comment/85214844
comment on: http://stackoverflow.com/q/49104927
score: 0
type: QuestionComment
type: Comment
has text: How will you encode categorical data? Are you planning to use dummy columns?

cntk
tags question: http://stackoverflow.com/q/49088392
tags question: http://stackoverflow.com/q/49038692
tag name: cntk
tags question: http://stackoverflow.com/q/48994155
type: Tag

http://stackoverflow.com/q/49066006
downvote count: 0
score: 1
tagged with: keras
has body: I am following this code from Keras: from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input import numpy as np model = VGG16(weights='imagenet', include_top=False) img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) features = model.predict(x) That is an example for a single image. How can I make it for a bunch of images? Let say I have 2000 images and I am expecting to have features shape as (2000, 7, 7, 512)
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has title: How to iterate through images for extracting features with VGG16?
upvote count: 1
has comment: http://stackoverflow.com/comment/85138654
has comment: http://stackoverflow.com/comment/85137387
tagged with: for-loop
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85013027
type: QuestionComment
type: Comment
has text: BTW, here's some more info that might help solving the issue: If I use the `tkMessageBox` in a function that is called when a button is clicked, the display of the message block does not affect the binding. (See my edited question.)
comment on: http://stackoverflow.com/q/48983443
score: 0

http://stackoverflow.com/comment/85101206
type: Comment
type: QuestionComment
has text: you reopen the file you write to for every line... open it once only (in the original `with` statement and you should be fine.
comment on: http://stackoverflow.com/q/49048508
score: 0

http://stackoverflow.com/a/49077918
upvote count: 1
answers question: http://stackoverflow.com/q/49077866
has comment: http://stackoverflow.com/comment/85163437
has comment: http://stackoverflow.com/comment/85164274
has comment: http://stackoverflow.com/comment/85163525
has comment: http://stackoverflow.com/comment/85163399
downvote count: 0
type: Answer
has body: The return value of an input is a string, just add weapons[int(option)] to change to a integer. EDIT: undo the above. All you did was define weapons as a tuple instead of a dictionary. Just change the definition to weapons = {'Greatsword', 40}
score: 1

http://stackoverflow.com/comment/85187331
type: Comment
type: QuestionComment
has text: You need to construct **dummy codes** for `ses==1` and `ses==2` if you want to mimic the Stata output. See, e.g., https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html
comment on: http://stackoverflow.com/q/49086721
score: 0

http://stackoverflow.com/comment/85311466
comment on: http://stackoverflow.com/a/49112304
has text: @Dhanvanth and I am not going to give out my contact details on Stack Overflow
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48977541
downvote count: 0
possible better answer: http://stackoverflow.com/a/48977933
has title: Python - formatting one big string
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48978425
accepted answer: http://stackoverflow.com/a/48978425
has answer: http://stackoverflow.com/a/48977933
tagged with: formatting
has body: I have a long string of farmAnimals that looks like this: it has \n\n\n and a \t in front of the Farm Animals Farm Animals F M Total Cow 11 10 21 Horse 3 6 9 Sheep 4 8 12 Goat 3 4 7 Chicken 1 1 2 Hen 5 7 12 Pig 3 7 10 Turkey 0 5 5 Cattle 1 1 2 Llama 3 5 8 Donkey 5 9 14 Duck 1 1 2 Total 40 64 104 I want to make the output look like this: Farm Animals F M Total Cow 11 12 23 Horse 5 5 10 Sheep 4 12 16 ....... Total 108 134 242 what I did so far is print(farmAnimalsString.strip().replace('\n\n','').replace('\t',' ').replace('\n\n\n','').replace('\n\n\n\n','')) My current solution doesn't necessarily produce the correct output but its close. There are different amounts of \n between each field, which makes it tricky for me. So, I am wondering if there is a better way to do this because all I can think about is this brute force way, and I think by doing this I won't be able to get the output that I want.. Thanks in advance! Edit: I just realized that one of the animal names are two words such as "Jack Rabbit" So when it printed, it looks like Farm Animals F M Total Jack Rabbit 1 2 3 Snow Bunny 0 1 1 Cow 0 1 1 Total 1 4 5
type: Question
upvote count: 2
answer count: 2
tagged with: string
favorite count: 0

http://stackoverflow.com/comment/85055034
has text: Yes but I dont get the last point, the dropout will not be active when i make predictions only in training so the dropout will not affect how Grad-CAM works?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49016530

http://stackoverflow.com/a/48972274
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48970632
has body: SQLite database needs files to keep data. create_article updates the database, whose files are stored in some dyno. This means that you can post new articles as long as you do not perform dyno-related operations like deploying (pushing to the remote branch) or restarting. To avoid this situation you might want to store the database files somewhere else, but running other databases is a better approach. More info about dynos: https://devcenter.heroku.com/articles/dynos

http://stackoverflow.com/comment/85539017
comment on: http://stackoverflow.com/a/49117047
type: AnswerComment
score: 0
type: Comment
has text: Sorry, I actually got my `[]` mixed up in that last comment, I meant to say `[[[1 1 1]][[2 2 2]][[3 3 3]]]`, in which case your R would be [1 1 1], your G would be [2 2 2] and your B would be [3 3 3]. Does that make more sense? (note that in this example, this would be a 1x3 pixel image)

http://stackoverflow.com/a/49112055
downvote count: 0
score: 5
type: AcceptedAnswer
has body: Use extract by keywords separated by | with fillna: pat = r"(Mental|Community)" df['Hospital Type'] = df['Hospital'].str.extract(pat, expand=False).fillna('Other') print (df) Hospital 2009-10 2010-11 Hospital Type 0 Aberystwyth Mental Health Unit 19 19 Mental 1 Bro Ddyfi Community Hospital 16 10 Community 2 Bronglais General Hospital 160 148 Other 3 Caebryn Mental Health Unit 37 39 Mental 4 Carmarthen Mental Health Unit 38 31 Mental
has comment: http://stackoverflow.com/comment/85229389
type: Answer
accepted answer of: http://stackoverflow.com/q/49112008
upvote count: 5
answers question: http://stackoverflow.com/q/49112008

http://stackoverflow.com/comment/84988677
comment on: http://stackoverflow.com/q/48991665
score: 0
type: Comment
type: QuestionComment
has text: What is i_iter doing? Aren't you repeating max_iter times the loop on j (with no difference between the repetitions since V_old is created only after the loop)?

http://stackoverflow.com/a/50650817
has comment: http://stackoverflow.com/comment/88498507
has comment: http://stackoverflow.com/comment/88497651
score: 12
upvote count: 12
accepted answer of: http://stackoverflow.com/q/49072942
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88376472
has body: I would use a Toplevel() window to build my own customer error box. I think using ttk buttons here would be a good idea and with a combination of frames and weights we can get the window to look decent enough. Keeping the window from being resized by the user I also had to set up a way to toggle the details textbox. With a tracking variable and the use of a if/else statement that was easy enough to set up. Finally, we can disable the textbox with .config(state="disabled") import tkinter as tk import tkinter.ttk as ttk import traceback class MyApp(tk.Tk): def __init__(self): super().__init__() tk.Button(self, text='test error', command=self.run_bad_math).pack() @staticmethod def run_bad_math(): try: 1/0 except Exception as error: title = 'Traceback Error' message = "An error has occurred: '{}'.".format(error) detail = traceback.format_exc() TopErrorWindow(title, message, detail) class TopErrorWindow(tk.Toplevel): def __init__(self, title, message, detail): tk.Toplevel.__init__(self) self.details_expanded = False self.title(title) self.geometry('350x75') self.minsize(350, 75) self.maxsize(425, 250) self.rowconfigure(0, weight=0) self.rowconfigure(1, weight=1) self.columnconfigure(0, weight=1) button_frame = tk.Frame(self) button_frame.grid(row=0, column=0, sticky='nsew') button_frame.columnconfigure(0, weight=1) button_frame.columnconfigure(1, weight=1) text_frame = tk.Frame(self) text_frame.grid(row=1, column=0, padx=(7, 7), pady=(7, 7), sticky='nsew') text_frame.rowconfigure(0, weight=1) text_frame.columnconfigure(0, weight=1) ttk.Label(button_frame, text=message).grid(row=0, column=0, columnspan=2, pady=(7, 7)) ttk.Button(button_frame, text='OK', command=self.destroy).grid(row=1, column=0, sticky='e') ttk.Button(button_frame, text='Details', command=self.toggle_details).grid(row=1, column=1, sticky='w') self.textbox = tk.Text(text_frame, height=6) self.textbox.insert('1.0', detail) self.textbox.config(state='disabled') self.scrollb = tk.Scrollbar(text_frame, comman…
answers question: http://stackoverflow.com/q/49072942
has comment: http://stackoverflow.com/comment/88498917
type: Answer
has comment: http://stackoverflow.com/comment/88497983
has comment: http://stackoverflow.com/comment/88497785

http://stackoverflow.com/q/48966117
has body: I have a short script called 'split-jpeg-to-fits.py' (from http://docs.astropy.org/en/stable/generated/examples/io/split-jpeg-to-fits.html) it converts a jpg into 3 ('red', 'blue' and 'green') greyscale FITS files. In Python 3.6 it worked, it was working fine just a few days ago, but not now for some reason, it doesn't even recognize PIL, I get the error 'No module named 'PIL'', so I tried it with Python 2.7.. seems to be OK with PIL/pillow but still doesn't produce results. Could it be related to me installing Intel Distribution for Python and Miniconda today(?) All it does (in 2.7) is display the image dimensions and then I get the following error messages, which is indicating a problem with matplotlib: Traceback (most recent call last): File "C:\Users\marti\Downloads\split-jpeg-to-fits.py", line 40, in &lt;module&gt; plt.imshow(image) File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 3101, in imshow **kwargs) File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 1717, in inner return func(ax, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axes\_axes.py", line 5127, in imshow im.set_data(X) File "C:\Python27\lib\site-packages\matplotlib\image.py", line 607, in set_data raise TypeError("Image data cannot be converted to float") TypeError: Image data cannot be converted to float and when I close the Python shell I get a Microsoft Visual C++ Runtime Library error - Any help'd be very much appreciated. Thanks.
upvote count: 0
answer count: 1
score: -1
has title: Python code for splitting JPEG's to three separate (R,G,B) FITS images not working anymore
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: python-imaging-library
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48976250
downvote count: 1
type: Question

http://stackoverflow.com/comment/84998778
type: QuestionComment
comment on: http://stackoverflow.com/q/48996679
has text: You need another ' after string65. And why is your result missing a few numbers?
score: 0
type: Comment

http://stackoverflow.com/a/48999321
downvote count: 0
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48999177
answers question: http://stackoverflow.com/q/48999177
has body: The great thing about anaconda is the easy way of managing multiple different environments. And that is what you are looking for. All you have to do is creat an environment with python version 2.7. Right now you only have the default(root) environment. A really good video on how to actually use anaconda is here (11mins and only the last 5-6 mins are what you're actually looking for) Basically you type the following in your terminal: to see all the environments you have right now: conda env list to create a new env called py27env: conda create --name py27env python=2.7 (+ other modules you want...) to activate the environment: source activate py27env to see which python version you are using: which python to exit an environment: source deactivate
type: AcceptedAnswer

http://stackoverflow.com/a/49091188
type: Answer
has body: You can use in operator: &gt;&gt;&gt; b in (7, 8) True
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/49091163
answers question: http://stackoverflow.com/q/49091163
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49052756
has comment: http://stackoverflow.com/comment/85111801
tagged with: matlab-engine
has body: I have a matlab function file called 'calculate_K_matrix.m ' which contains the following code: function K = calculate_K_matrix(A, B, n) K = place(A, B, eigs(A)*n) end I can call this from matlab like so: addpath('/home/ash/Dropbox/SimulationNotebooks/Control') A = [0 1 ;-100 -5] B = [0 ; 7] n = 1.1 % how aggressive feedback is K = calculate_K_matrix(A, B, n) but when I try to call this from python using the matlab engine API like so: import matlab import matlab.engine eng = matlab.engine.start_matlab() A = matlab.double([[0, 1],[-100, -5]]) B = matlab.double([[0],[7]]) n = 1.1 double(param initializer=None, param size=None, param is_complex=False) n_matlab = matlab.double([n]) eng.addpath(r'/home/ash/Dropbox/SimulationNotebooks/Control') K = eng.calculate_K_matrix(A, B, n_matlab) Then I get the following error: In [17]: run test.py Attempt to execute SCRIPT calculate_K_matrix as a function: /home/ash/Dropbox/SimulationNotebooks/Control/calculate_K_matrix.m --------------------------------------------------------------------------- MatlabExecutionError Traceback (most recent call last) /home/ash/Dropbox/SimulationNotebooks/Control/test.py in &lt;module&gt;() 10 11 eng.addpath(r'/home/ash/Dropbox/SimulationNotebooks/Control') ---&gt; 12 K = eng.calculate_K_matrix(A, B, n_matlab) /home/ash/anaconda2/envs/python3/lib/python3.5/site-packages/matlab/engine/matlabengine.py in __call__(self, *args, **kwargs) 76 else: 77 return FutureResult(self._engine(), future, nargs, _stdout, ---&gt; 78 _stderr, feval=True).result() 79 80 def __validate_engine(self): /home/ash/anaconda2/envs/python3/lib/python3.5/site-packages/matlab/engine/futureresult.py in result(self, timeout) 66 raise TypeError(pythonengine.getMessage('TimeoutCannotBeNegative')) 67 ---&gt; 68 return self.__future.result(timeout) 69 70 def cancel(self): /home/ash/anaconda2/envs/python3/lib/python3.5/site-packages/matlab/engine/fevalfuture.py in result(self, timeout) 80 raise TimeoutError(pythonengine.getMessage('Mat…
tagged with: matlab
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/55046476
has title: How to call a matlab function file from python using the matlab engine API?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85110637
has comment: http://stackoverflow.com/comment/85110226
answer count: 1
has answer: http://stackoverflow.com/a/55046476
has comment: http://stackoverflow.com/comment/85110094
favorite count: 0
has comment: http://stackoverflow.com/comment/85111340
tagged with: python
has comment: http://stackoverflow.com/comment/85110135
has comment: http://stackoverflow.com/comment/85110145
downvote count: 0

http://stackoverflow.com/a/49083601
has comment: http://stackoverflow.com/comment/85173245
has comment: http://stackoverflow.com/comment/85173353
upvote count: 3
has comment: http://stackoverflow.com/comment/85178350
has comment: http://stackoverflow.com/comment/85173275
type: Answer
has comment: http://stackoverflow.com/comment/85173017
answers question: http://stackoverflow.com/q/49083499
downvote count: 0
has body: You don't need to use switch_to_alert() as well as get() to close modal window. Just try to close it with below code: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[aria-label="Close"]'))).click() This allows you to wait for button appearance and click the button
score: 3

http://stackoverflow.com/q/49042957
answer count: 1
has answer: http://stackoverflow.com/a/49044162
accepted answer: http://stackoverflow.com/a/49044162
tagged with: python
has title: Trying to insert a previous answer as an x value
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85091239
has body: def Use_Last_Answer(): choose_opt = input('''Do you want to use the previous answer? (Y/N)''' ) if choose_opt.upper() == 'Y': #Function for ANS x = ANS find_fractions_2 elif choose_opt.upper() == 'N': find_fractions() else: Use_Last_Answer() def find_fractions(): x = 0 # makes x reset but not necessary x = Fraction(input('''Enter (1st) fraction:''')) find_fractions_2() def find_fractions_2(): operation = input(''' What do you want to do? Add (1) (e.g) 1/5 + 1/10 = 3/10 Enter Function number:''') if(operation != '1'): print("You must enter a valid operation") else: y = Fraction(input('''Enter (2nd) fraction:''')) if operation == '1': print('''Adding Fractions...''') print('{} + {} = '.format(x, y)) ANS = print(x + y) Use_Last_Answer() find_fractions() (This isn't the whole code, but just cut down to fit). I'm trying to make an ANS function which is usually available on calculators by making ANS = (x+y) &lt;- from the previous equation and making a def to see whether ANS is able to become x variable. I separated def find_functions() into two parts to bypass x = Fraction(input('''Enter (1st) fraction:''')) and go to which operation (e.g) add, subtract etc. making the previous answer the new equations x variable. But it's not working and when I separate def find_fractions() into the two parts and start a new equation the x variable doesn't carry through to the second part and the x+y doesn't compute. I'm in high school and this is my 5th week of computer science, so I won't know too much jargon.
has comment: http://stackoverflow.com/comment/85091417
type: Question
score: 0

http://stackoverflow.com/comment/85208913
type: QuestionComment
has text: @FlorentB. this is a good idea I'll try it out
comment on: http://stackoverflow.com/q/49018497
score: 0
type: Comment

http://stackoverflow.com/q/49102606
tagged with: facebook-like
favorite count: 0
tagged with: google-app-engine
has title: How to generate User specific feeds?
tagged with: python
downvote count: 0
answer count: 0
type: UnansweredQuestion
score: 2
has body: I have 2 tables - Pages and Feeds. Each feed belong to a specific page. The user follows the interested page. My requirement is to provide feeds for the user from the pages he has followed in a random way. That is, if page1 has 5 feeds &amp; page2 has 5 feeds, I would like display these 10 feeds in a random way so that user doesn't get bored with feed from single page. PS: Pages will contain feeds more than 5. If user likes, 3 or more pages, The feeds has to be fetched accordingly. Each time max 10 feeds are fetched(for optimization) so I need to know how to iterate from the previous point. Backend: Google App Engine Python Environment Google Data store Is there any way to achieve this?
type: Question
upvote count: 2
tagged with: google-cloud-datastore

http://stackoverflow.com/comment/84946150
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/q/22657548/8079103
score: 0
comment on: http://stackoverflow.com/q/48970217

http://stackoverflow.com/comment/85109039
comment on: http://stackoverflow.com/q/49050556
score: 0
type: Comment
type: QuestionComment
has text: Error says that there is no key `title` in the data dictionary (or associative array if you a PHP programmer) sent to pipelines, you need to send this from the spider code you posted in your question.

http://stackoverflow.com/comment/85078386
type: AnswerComment
comment on: http://stackoverflow.com/a/49036725
type: Comment
has text: In python 3.x, I believe you need `list(map(...))`. But I don't think creating a list is necessary (see my solution).
score: 1

http://stackoverflow.com/comment/84947864
comment on: http://stackoverflow.com/q/48971247
has text: Ok, try shifting i = i + 1 out of the second loop, into the first after the second loop.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49058313
has comment: http://stackoverflow.com/comment/85122252
linked to: http://stackoverflow.com/q/30947682
type: Question
upvote count: 4
has body: So right now I am combining many json files, transforming the data then writing out as rows to a CSV file. The problem is that this data will grow exponentially, and I may run into memory errors in the future. How would I go about writing to CSV, but once the file size is greater than 1GB start writing to a new file? This is my code for writing to one file: with open('foo.csv', 'w', encoding='utf-8', newline='') as f: for response_row in load_json(): try: writer = csv.writer(f, delimiter="|") writer.writerow(row) except Exception as e: logging.critical(str(e))
has comment: http://stackoverflow.com/comment/85122149
has comment: http://stackoverflow.com/comment/85122232
answer count: 1
score: 4
has comment: http://stackoverflow.com/comment/85122085
has comment: http://stackoverflow.com/comment/85121887
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/77999270
has comment: http://stackoverflow.com/comment/85121761
downvote count: 0
has comment: http://stackoverflow.com/comment/85127098
has comment: http://stackoverflow.com/comment/85122205
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85122129
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85122385
has comment: http://stackoverflow.com/comment/85805484
tagged with: python
has comment: http://stackoverflow.com/comment/85121511
has comment: http://stackoverflow.com/comment/85122191
has comment: http://stackoverflow.com/comment/85121438
has comment: http://stackoverflow.com/comment/85121845
has comment: http://stackoverflow.com/comment/85122309
has comment: http://stackoverflow.com/comment/85824680
has comment: http://stackoverflow.com/comment/85122185
linked to: http://stackoverflow.com/q/27430555
has comment: http://stackoverflow.com/comment/85123200
has comment: http://stackoverflow.com/comment/85121466
has title: How to write to multiple CSV files with a max size
has comment: http://stackoverflow.com/comment/85122083

http://stackoverflow.com/q/49034826
has comment: http://stackoverflow.com/comment/85080137
upvote count: 1
downvote count: 1
type: Question
tagged with: python-2.7
score: 0
has body: file1 = open('manu.txt', 'r') charlist = [] lines=file1.readlines() for i in range(0,len(str(lines))-1): prevline=lines[i] nextline=lines[i+1] if 'a' in nextline: charlist.append(nextline) print charlist I am trying to find a word and trying to keep that in a list by reading each line a file. But it is giving list out range error.
has title: list out of range: when a line is appended to a list by searching a word in a file
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49034899

http://stackoverflow.com/comment/84964790
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48979771
has text: If you only have two values to check, what you have above is is much better than trying to do some sort of list comprehension. Its much more readable.
type: Comment

http://stackoverflow.com/a/49089369
has comment: http://stackoverflow.com/comment/85385126
accepted answer of: http://stackoverflow.com/q/49032661
has comment: http://stackoverflow.com/comment/85395227
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: PHP's passthru function does not have the elegant method for which you may be searching of passing environment variables. If you must use passthru, then export your variables directly in the command: passthru("SOMEVAR=$yourVar PATH=$newPATH ... /path/to/executable $arg1 $arg2 ...") If you are inclined toward shell_exec, you may appreciate putenv for the slightly cleaner interface: putenv("SOMEVAR=$yourVar"); putenv("PATH=$newPATH"); echo shell_exec("/path/to/executable $arg1 $arg2 ..."); If you are open to a more robust (if tedious) approach, consider proc_open: $cmd = "/path/to/executable arg1 arg2 ..." # Files 0, 1, 2 are the standard "stdin", "stdout", and "stderr"; For details # read the PHP docs on proc_open. The key here is to give the child process a # pipe to write to, and from which we will read and handle the "passthru" # ourselves $fileDescriptors = array( 0 =&gt; ["pipe", "r"], 1 =&gt; ["pipe", "w"], 2 =&gt; ["pipe", "w"] ); $cwd = '/tmp'; $env = [ 'PATH' =&gt; $newPATH, 'SOMEVAR' =&gt; $someVar, ... ]; # "pHandle" = "Process handle". Note that $pipes is new here, and will be # given back to us $pHandle = proc_open($cmd, $fileDescriptors, $pipes, $cwd, $env); # crucial: did proc_open work? if ( is_resource( $pHandle ) ) { # $pipes is now valid $pstdout = $pipes[ 1 ]; # Hey, whaddya know? PHP has just what we need... fpassthru( $pstdout ); # Whenever you proc_open, you must also proc_close. Just don't # forget to close any open file handles fclose( $pipes[0] ); fclose( $pipes[1] ); fclose( $pipes[2] ); proc_close( $pHandle ); }
type: Answer
answers question: http://stackoverflow.com/q/49032661

http://stackoverflow.com/comment/85074849
type: QuestionComment
type: Comment
has text: @lurker because this requires to hardcode the columnnames list somewhere ;)
comment on: http://stackoverflow.com/q/49034403
score: 0

http://stackoverflow.com/comment/85103066
comment on: http://stackoverflow.com/q/49049431
type: Comment
type: QuestionComment
score: 0
has text: @Ev.Kounis its for checking the amount is less than 500 and the percentage difference is on the flag for the lower amount. Think that needs to be in a separate if rather than elif actually thanks.

http://stackoverflow.com/comment/85076181
has text: What you have currently looks right. However a couple of question are in order. Is your base dir called `app`? If so you need to remove the `app/static` and just use `userimages` as the value of `upload_to`. Also check your Django settings that the right MEDIA_ROOT is set. I'm not sure that you want to upload user photos to static directory because security. If so, you may need to subclass FileSystemStorage to do this. [Read more about what upload_to does](https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.FileField.upload_to)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49035290

http://stackoverflow.com/comment/85219941
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49107491
has text: Please keep it short and minimal, this is rather verbose

http://stackoverflow.com/comment/84953959
type: QuestionComment
score: 0
has text: I need to cast to int to get quantized values. Is there a better way to do that?
comment on: http://stackoverflow.com/q/48964861
type: Comment

http://stackoverflow.com/comment/85126471
type: QuestionComment
has text: you can find all the legit attributes [here](https://docs.python.org/3.6/tutorial/datastructures.html#more-on-lists)
score: 1
comment on: http://stackoverflow.com/q/49060560
type: Comment

http://stackoverflow.com/comment/85161004
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49077480
has text: can you post the df code, please? and also what is the year growth representing? the height difference between years of same person by person code?
score: 0

http://stackoverflow.com/comment/85199447
type: QuestionComment
comment on: http://stackoverflow.com/q/49096837
score: 1
has text: Possible duplicate of [Efficiently delete arrays that are close from each other given a threshold in python](https://stackoverflow.com/questions/43035503/efficiently-delete-arrays-that-are-close-from-each-other-given-a-threshold-in-py)
type: Comment

http://stackoverflow.com/comment/85014539
score: 0
comment on: http://stackoverflow.com/a/49004537
type: Comment
type: AnswerComment
has text: Still no output with glob.glob(os.path.expanduser(os.path.join('~', 'Downloads/NewFolder', " ** / *.jpg")))

http://stackoverflow.com/q/49052688
tagged with: python-3.x
has title: How to keep selected points on a ColumnDataSource object and deselect them with ResetTool?
accepted answer: http://stackoverflow.com/a/49107765
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: plot
type: Question
tagged with: bokeh
has answer: http://stackoverflow.com/a/49107765
has body: I have plotted a circle glyph. When I select some points they are marked as selected. But I lose the selection when I change the tool I am using or when I click on some other place of the figure. Which is the best way to keep the selection on the circle glyph?. I want to deselect all the points when the ResetTool is pressed. I am working with the master (0.12.14+25.g675aacf72) branch of bokeh where the Selection class already exists. def update_selection(self, attr, old, new): ''' I do this to avoid deselection ''' if new.indices == []: self.source.selected.indices = self.old_selection else: self.old_selection = list(new.indices) source.on_change( 'selected', update_selection ) I use this to call a callback when the Reset tool is pressed: def deselect_points(self, event): ''' I do this to deselect point on Reset event But when the indices are updated the update_selection method is called ''' self.source.selected.indices = [] plot.on_event(Reset, deselect_points) So is there a way to keep the selection and only deselect point on Reset event? Update 03/14/2018 This is happening only when the Tap Tool is enabled. So I have written an issue on GitHub to check if this is the expected behaviour
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/109730833
type: Comment
comment on: http://stackoverflow.com/a/49115339
score: 0
type: AnswerComment
has text: pd.pivot_table(df, index=['user_id', 'total_spent', 'purchase_date', 'purchase_id', 'aisle'], columns=['department'], values='item_cost', aggfunc=np.sum, fill_value=0).reset_index()

http://stackoverflow.com/comment/85234588
type: QuestionComment
has text: Depending on which shell you use this may be impossible; a lot of shells take Ctrl-Z as the "send to background" command, so your script would be sent to the background before it could see those keypresses.
score: 1
comment on: http://stackoverflow.com/q/49114749
type: Comment

http://stackoverflow.com/q/49028978
has body: On running command python -m pip install python-emnist , Getting error as follows: Could not find a version that satisfies the requirement python-emnist (from versions: ) No matching distribution found for python-emnist Please help and provide solution.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49029069
upvote count: 0
favorite count: 0
type: Question
tagged with: python
has title: Could not find a version that satisfies the requirement python-emnist (from versions: ) No matching distribution found for python-emnist
score: -1
downvote count: 1
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/q/49116900
has comment: http://stackoverflow.com/comment/85239851
answer count: 0
type: UnansweredQuestion
score: 0
has body: I'm trying to get the device address from Alexa. I've followed this tutorial but I'm having some problems. The code I'm using is this one: def test_intent(event, context): from botocore.vendored import requests device_id = event["context"]["System"]["device"]["deviceId"] api_access_token = event["context"]["System"]["apiAccessToken"] api_uri = "https://api.amazonalexa.com/v1/devices/{}/settings/address".format(device_id) api_headers = {"Accept": "application/json", "Authorization": "Bearer {}".format(api_access_token)} api_response = requests.get(api_uri, headers=api_headers) data = api_response.json() I put some location (US location) in my alexa app and I allowed the permission the skill ask me (Full Address in this case). The api_response.status_code is 204, so it should be ok. But when I run the last line "api_response.json()" it crashes (alexa replays that there is a problem with the skill). I think the problem is the api_response is None and the json is not working, but I don't know why this could happend. Any guess about this? Edit: After some test, I realised that I've set the phone's location, not the echo dot location in the Alexa app, so that's the reason the app responded with 204 (no data)
tagged with: alexa-skills-kit
type: Question
has title: Alexa and Python Lambda Function to retrieve Device Address
has comment: http://stackoverflow.com/comment/85239110
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/85240037
tagged with: python
has comment: http://stackoverflow.com/comment/85239537

http://stackoverflow.com/a/49107957
answers question: http://stackoverflow.com/q/49107640
score: 0
upvote count: 1
downvote count: 1
has body: Just in case, a solution with pandas import pandas as pd df = pd.DataFrame(dict(key=list(d.keys()),val=list(d.values()))) print(df) key val 0 1 a 1 2 b 2 3 c 3 4 c 4 5 c 5 6 c df = df.drop_duplicates(subset=['val']) df.index=df.key df.val.to_dict() {1: 'a', 2: 'b', 3: 'c'} Don't know performances issues on biggest dataset or if it is more pythonic. Nevertheless, no loops.
type: Answer

http://stackoverflow.com/q/49095323
has answer: http://stackoverflow.com/a/49096337
has title: Trouble in plotting dates in PyPlot
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49136312
possible better answer: http://stackoverflow.com/a/49096337
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
upvote count: 1
has answer: http://stackoverflow.com/a/49136312
has body: I am trying to plot a simple time-series. Here's my code: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from datetime import datetime %matplotlib inline df = pd.read_csv("sample.csv", parse_dates=['t']) df'sq', 'iq', 'rq' = df'sq', 'iq', 'rq'.apply(pd.to_numeric, errors='coerce') df = df.fillna(0) df.set_index('t') This is part of the output: df't','sq'.plot() plt.show() As you can see, the x-axis in the plot above is not the dates I intended it to show. When I change the plotting call as below, I get the following gibberish plot, although the x-axis is now correct. df't','sq'.plot(x = 't') plt.show() Any tips on what I am doing wrong? Please comment and let me know if you need more information about the problem. Thanks in advance.
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/48990825
has body: Code works fine but seems this line is ugly. self.data["data"]["someComponent"]["items"][1]["content"]["items"].append(json.load(someVariable)) So my question is: Is that suitable for code by python conventions? flake8, pylint, etc.. does not showing problems. Maybe you have some fresh ideas for refactoring?
tagged with: python
has answer: http://stackoverflow.com/a/48992041
type: AnsweredQuestion
upvote count: 2
tagged with: refactoring
has title: Refactoring of long dict attributes line
accepted answer: http://stackoverflow.com/a/48992041
type: Question
score: 2
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49096679
answer count: 3
accepted answer: http://stackoverflow.com/a/49101085
tagged with: pandas
has answer: http://stackoverflow.com/a/49097465
favorite count: 0
has answer: http://stackoverflow.com/a/49101085
has comment: http://stackoverflow.com/comment/85204552
tagged with: python
has comment: http://stackoverflow.com/comment/85206433
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85198710
has body: A B C 0 blue 14.5 14.0 1 blue 14.0 14.0 2 blue 13.5 14.0 3 blue 12.0 14.0 4 blue 10.5 14.0 5 green 20.0 19.0 6 green 19.0 19.0 7 green 18.5 19.0 8 green 18.0 19.0 9 green 17.5 19.0 10 green 16.0 19.0 I want to create a new df1 with next conditions, per each A group ("blue" and "green"): Select the rows where B = C and rows where B = C-1 If it doesn´t exist any B value in the group that satisfy the condition (B = C-1), select the next row further down that would correspond. For instance, in "blue group" B = C - 1 would be 14.0 - 1 = 13.0 . As it doesn´t exist any 13.0 "blue group", select the next row further down that exists in df, that is: 3 blue 12.0 14.0 df1 should be: A B C 1 blue 14.0 14.0 3 blue 12.0 14.0 6 green 19.0 19.0 8 green 18.0 19.0 I´ve tried: df1 = df[(df["B"] == df["C"]) | (df["B"] == df["C"]-1)]
type: Question
score: 3
has answer: http://stackoverflow.com/a/49099640
has title: Selecting rows in groups with conditions
possible better answer: http://stackoverflow.com/a/49099640
upvote count: 3

http://stackoverflow.com/a/48971621
has body: According to the docs: Widget names should start with upper case letters while property names should start with lower case ones. Following the PEP8 Naming Conventions is encouraged. So in your case the solution is to change the first letter of the properties to lowercase: .py synonym_box = ObjectProperty() ant_box = ObjectProperty() .kv meaning_box: meaning_input synonym_box: Synonym_input
accepted answer of: http://stackoverflow.com/q/48971498
type: Answer
answers question: http://stackoverflow.com/q/48971498
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84948314
comment on: http://stackoverflow.com/a/48971532
has text: @VivekKalyanarangan - thank you, good idea. I add it to answer.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48977538
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84960481
has comment: http://stackoverflow.com/comment/84960297
upvote count: 1
tagged with: mixed
tagged with: attachment
tagged with: content-type
type: Question
downvote count: 0
score: 1
favorite count: 0
has title: How can I read the body and download the attached file/s from Gmail with Python2.7?
tagged with: python
tagged with: gmail
has body: I'm trying to read the body of my inbox folder on my Email and, if there is an attachment, download it. I've reached to read the body of the received mails, but only if there isn't any attachment on it. Now I've reached to read all body messages of the received mails, but I can't download the attached files inside the mail yet. Next, You'll see my code, if it can help someone, you're free to use it. import imaplib import email import myEmails from myEmails import dicCorreos,dicContras class Attachement(object): def __init__(self): self.data = None; self.content_type = None; self.size = None; self.name = None; def parse_attachment(message_part): content_disposition = message_part.get("Content-Disposition", None) if content_disposition: dispositions = content_disposition.strip().split(";") if content_disposition and dispositions[0].lower() == "attachment": attachment = Attachement() attachment.data = message_part.get_payload(decode=True) attachment.content_type = message_part.get_content_type() attachment.size = len(attachment.data) attachment.name = message_part.get_filename() return attachment return None def get_text(self, email_message_instance): maintype = email_message_instance.get_content_maintype() if maintype == 'multipart': for part in email_message_instance.get_payload(): if part.get_content_maintype() == 'text': return part.get_payload() if part.get_content_maintype() == 'multipart': for part2 in part.get_payload(): return part2.get_payload() elif maintype == 'text': return email_message_instance.get_payload() mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login(dicCorreos['correo3'],dicContras['contra3']) mail.list() mail.select("inbox") result,data = mail.search(None,"ALL") # result=OK,data=['1 2 3 4 5 6 7 8 9 10 11 ...'] if result=='OK': latest_id = data[0].split()[-6:] list_data=[] for i in range(len(latest_id)): list_data.append(email.message_from_string(mail.fetch(latest_id[int(i)],"(RFC822)")[1][0][1])) print len(list_data) print range(len(list_dat…

http://stackoverflow.com/comment/85207142
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49053059
has text: Ok, I made an attempt to apply your suggestion. I defined `config_file` in the build function of `MainApp`. I then declared `app = App.get_running_app()` in each function that makes use of `config_file`. I then replaced all other `config_file` references with `app.config_file`. The error I get now is **AttributeError: 'NoneType' object has no attribute 'config_file'**.
score: 0

http://stackoverflow.com/a/49078755
type: AcceptedAnswer
has body: According to the docs: The selection is automatically updated when the cursor position changes. You can get the currently selected text from the TextInput.selection_text property. and in your case when you click on the Label and appear in TextInput the cursor changes position so a text is selected. And when a text is selected and you write something it is replaced, that's why the text disappears. The solution is to clean the selection: from kivy.clock import Clock class EditableLabel(Label): [...] def on_edit(self, instance, value): if not value: if self.textinput: self.remove_widget(self.textinput) return self.textinput = t = TextInput( text=self.text, size_hint=(None, None), font_size=self.font_size, font_name=self.font_name, pos=self.pos, size=self.size, multiline=False) self.bind(pos=t.setter('pos'), size=t.setter('size')) self.add_widget(self.textinput) t.bind(on_text_validate=self.on_text_validate, focus=self.on_text_focus) Clock.schedule_once(lambda dt: self.textinput.cancel_selection())
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49070345
answers question: http://stackoverflow.com/q/49070345
upvote count: 1
score: 1

http://stackoverflow.com/q/49007149
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85019405
favorite count: 0
type: UnansweredQuestion
has title: Got an error when trying to import Tensorflow in Anaconda
has answer: http://stackoverflow.com/a/49095509
has answer: http://stackoverflow.com/a/49008218
tagged with: python
tagged with: tensorflow
type: Question
has body: I installed tensorflow with pip3, then validated it with # Python import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) And all works fine in terminal. However, when i try to import tensorflow in Anaconda it throws up an error: import tensorflow as tf Traceback (most recent call last): File "&lt;ipython-input-4-64156d691fe5&gt;", line 1, in &lt;module&gt; import tensorflow as tf File "/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 51, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/Users/Ivan/anaconda3/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/Users/Ivan/anaconda3/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: dlopen(/Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib Referenced from: /Users/Ivan/anaconda3/lib/python3.6/site-packages/tensorflow/python/_pywrap_t…
tagged with: anaconda
has comment: http://stackoverflow.com/comment/85019288
score: 4
upvote count: 4

http://stackoverflow.com/a/49102917
score: 14
downvote count: 0
answers question: http://stackoverflow.com/q/49099293
type: Answer
has body: In newer versions, the grid_scores_ is renamed as cv_results_. Following the documentation, you need this: best_index_ : int The index (of the cv_results_ arrays) which corresponds to the best &gt; candidate parameter setting. The dict at search.cv_results_['params'][search.best_index_] gives the &gt; parameter setting for the best model, that gives the highest mean score (search.best_score_). So in your case, you need Best params :- result.cv_results_['params'][result.best_index_] OR result.best_params_ Best mean score :- result.cv_results_['mean_test_score'][result.best_index_] OR result.best_score_ Best std :- result.cv_results_['std_test_score'][result.best_index_]
upvote count: 14

http://stackoverflow.com/comment/84989910
comment on: http://stackoverflow.com/q/48992179
has text: I am not setting the locale. Is that a problem? I am trying to find out, why with the default locale (de_DE in my example) strftime produces a wrong output,
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49063586
has comment: http://stackoverflow.com/comment/85133063
has comment: http://stackoverflow.com/comment/85132722
tagged with: django
type: Question
has title: Need to go one level deeper into json but am not able, upon ajax server response
has answer: http://stackoverflow.com/a/49063795
accepted answer: http://stackoverflow.com/a/49063795
linked to: http://stackoverflow.com/q/17722433
has body: I am able to have the browser send the server the initial http post, and from the server I am able to send the browser the json which contains the json represented objects. But from here I am not able to populate the select options. We'll actually I am but it is only one level deep, and also for some season add it all into one option (least of my worries atm). It places this within the select option, if the data variable contains objects "[object, Object], [object, Object], [object, Object]" View Code if request.is_ajax(): selected_date = request.POST['selected_date'] slots_on_day = Calendar.objects.filter(date=selected_date) data = [] for cal in slots_on_day: data.append(model_to_dict(cal)) return JsonResponse(status=200, data={'slots_on_day': data}) json structure (data variable) [{'id': 47, 'date': datetime.date(2018, 3, 12), 'timeslot_A': datetime.time(10, 0), 'timeslot_B': datetime.time(12, 0), 'booked': True}, {'id': 45, 'date': datetime.date(2018, 3, 12), 'timeslot_A': datetime.time(8, 0), 'timeslot_B': datetime.time(10, 0), 'booked': False}] The Ajax Success success: function(data){ $.each(data, function(key, value){ $('select[name=slot]').append(' ' + value2 +' '); }); } Here is something else I tried success: function(data){ $.each(data, function(key, value){ for (var key in data) { $('select[name=slot]').append(' ' + value +' '); } EDITED - Heres Templates Date: Time: --------- UPDATE Now for the ajax success I have this: success: function(data){ $.each(data['slots_on_day'], function(key, value){ $('select[name=slot]').append(' ' + value +' '); }); } now what this does is it adds a value to each of the appended objects starting at 0 and incriminating by 1. So the first option will have a value of 0. The second a value of 1 etc. The text for each of these is always '[object Object]' The console.log(data) output is: { "slots_on_day": [ { "id": 41, "date": "2018-03-05", "timeslot_A": "08:00:00", "timeslot_B": "10:00:00", "booked": false }, { "id": 42, "date"…
has comment: http://stackoverflow.com/comment/85132409
has comment: http://stackoverflow.com/comment/85132292
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/3552461
tagged with: arrays
has comment: http://stackoverflow.com/comment/85132767
tagged with: javascript
has comment: http://stackoverflow.com/comment/85132329
tagged with: ajax
possible better answer: http://stackoverflow.com/a/49063948
has comment: http://stackoverflow.com/comment/85132680
tagged with: python
has answer: http://stackoverflow.com/a/49063948
has comment: http://stackoverflow.com/comment/85132574
type: AnsweredQuestion

lstm
tags question: http://stackoverflow.com/q/49089775
tags question: http://stackoverflow.com/q/49093292
tags question: http://stackoverflow.com/q/49103531
tags question: http://stackoverflow.com/q/49097124
tags question: http://stackoverflow.com/q/49114306
tags question: http://stackoverflow.com/q/49078266
tags question: http://stackoverflow.com/q/49099700
tags question: http://stackoverflow.com/q/48969273
tag name: lstm
tags question: http://stackoverflow.com/q/49005616
tags question: http://stackoverflow.com/q/49082088
tags question: http://stackoverflow.com/q/49107489
tags question: http://stackoverflow.com/q/48992033
tags question: http://stackoverflow.com/q/48966371
tags question: http://stackoverflow.com/q/49062287
tags question: http://stackoverflow.com/q/49012907
tags question: http://stackoverflow.com/q/49058777
type: Tag
tags question: http://stackoverflow.com/q/49100161
tags question: http://stackoverflow.com/q/49056451

http://stackoverflow.com/q/49109365
accepted answer: http://stackoverflow.com/a/49109422
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49109422
tagged with: python
has comment: http://stackoverflow.com/comment/85224279
linked to: http://stackoverflow.com/q/5419389
type: AnsweredQuestion
has body: How can I delete a complete line in the output screen of python? Can I use the escape sequence '\b' for this?
tagged with: line
has title: Delete a complete line in python 3 output
type: Question

http://stackoverflow.com/comment/85043628
has text: Possible duplicate: https://stackoverflow.com/questions/46386759/animation-funcanimation-valueerror-i-o-operation-on-closed-file . Also see this issue: https://github.com/matplotlib/matplotlib/issues/8053/
score: 1
comment on: http://stackoverflow.com/q/49019073
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49044131
upvote count: 12
has answer: http://stackoverflow.com/a/49052124
tagged with: bar-chart
downvote count: 0
answer count: 3
tagged with: python
has body: I use python3, seaborn countplot, my question : how to add the count values for every bar? Show the label at the top of each bar? how to have these bars in descending order? I wrote this: fig = plt.figure(figsize=(10,6)) sns.countplot(data_new['district'],data=data_new) plt.show() Thanks a lot !
has comment: http://stackoverflow.com/comment/85108704
favorite count: 0
type: UnansweredQuestion
tagged with: seaborn
linked to: http://stackoverflow.com/q/28931224
tagged with: plot-annotations
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/28931224
has title: how to add data Labels to seaborn countplot / factorplot
has answer: http://stackoverflow.com/a/71023764
has answer: http://stackoverflow.com/a/69813924
type: Question
score: 12

http://stackoverflow.com/comment/85245917
comment on: http://stackoverflow.com/a/49117847
has text: If you really want to use mode='1', why do you convert to RGB in the question? Anyway, added example for mode='1'.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84938816
type: Comment
has text: @DeliriousLettuce That's indeed a little faster, but consider the whole expensive is `O(n!)` and make the code loosely coupled, get the original permutations first seems better.
comment on: http://stackoverflow.com/a/48966181
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85048963
score: 0
type: QuestionComment
has text: here type is compared, not the value
type: Comment
comment on: http://stackoverflow.com/q/49021823

http://stackoverflow.com/comment/85189936
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48997476
has text: I'm not a Python expert, but I did come up with some simplified examples to verify `Cont` behaves correctly. Here, `flatten` is different than the one asked about in the question, but the example is still helpful to see how the Cont sequencing works. I thought you might enjoy them https://eval.in/966384

http://stackoverflow.com/comment/85040247
type: QuestionComment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Give us the JSON object as well.
score: 0
comment on: http://stackoverflow.com/q/49017580
type: Comment

http://stackoverflow.com/q/49027003
possible better answer: http://stackoverflow.com/a/49032160
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49030369
has answer: http://stackoverflow.com/a/49027741
score: 1
linked to: http://stackoverflow.com/q/12426363
upvote count: 1
type: Question
has body: I am writing python scripts to sychronize tables from a MSSQL database to a Postgresql DB. The original author tends to use super wide tables with a lot of regional consecutive NULL holes in them. For insertion speed, I serialized the records in bulk to string in the following form before execute() INSERT INTO A( {col_list} ) SELECT * FROM ( VALUES (row_1), (row_2),...) B( {col_list} ) During the row serialization, its not possbile to determin the data type of NULL or None in python. This makes the job complicated. All NULL values in timestamp columns, integer columns etc need explicit type cast into proper types, or Pg complains about it. Currently I am checking the DB API connection.description property and compare column type_code, for every column and add type casting like ::timestamp as needed. But this feels cumbersome, with the extra work: the driver already converted the data from text to proper python data type, now I have to redo it for column with those many Nones. Is there any better way to work around this with elegancy &amp; simplicity ?
has answer: http://stackoverflow.com/a/49030369
has title: How to avoid explicit casting NULL during INSERT in Postgresql
has answer: http://stackoverflow.com/a/49032160
answer count: 3
downvote count: 0
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/85063689
tagged with: python
tagged with: psycopg2

http://stackoverflow.com/comment/85025210
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49010166
has text: Entering `psql -U name -d dbase` ind cmd promt changes the beinning of the line to dbase=#. Guess this means its running?

http://stackoverflow.com/a/49078451
has body: You can try combining urllib.parse with pathlib. from urllib.parse import urlparse, urlunparse from pathlib import PosixPath s3_url = urlparse('s3://bucket/key') s3_path = PosixPath(s3_url.path) s3_path /= 'hello' s3_new_url = urlunparse((s3_url.scheme, s3_url.netloc, s3_path.as_posix(), s3_url.params, s3_url.query, s3_url.fragment)) # or # s3_new_url = s3_url._replace(path=s3_path.as_posix()).geturl() print(s3_new_url) It's quite cumbersome, but it's what you asked for.
type: Answer
upvote count: 15
downvote count: 0
answers question: http://stackoverflow.com/q/49078156
score: 15
accepted answer of: http://stackoverflow.com/q/49078156
has comment: http://stackoverflow.com/comment/113973636
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/134638250

http://stackoverflow.com/comment/85185513
score: 0
has text: What operating system
comment on: http://stackoverflow.com/q/49089984
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84964229
score: 1
type: AnswerComment
has text: Why do optimize so small timing? Maybe we should optimaze bigger scope to have valuable improvement?
type: Comment
comment on: http://stackoverflow.com/a/48968910

http://stackoverflow.com/q/49031060
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49031218
type: UnansweredQuestion
has title: How to slice a findall result from Pandas, Python
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49031249
type: Question
has body: I would like to extract using a specific pattern from a column of worksheet names which were extracted from excel spreadsheets, and only retrieve the last result from the list of results. For example: "&lt;Worksheet ""2012""&gt;" "&lt;Worksheet ""2012""&gt;" "&lt;Worksheet ""2012""&gt;" "&lt;Worksheet ""2012 - 2013""&gt;" "&lt;Worksheet ""2012 - 13""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" "&lt;Worksheet ""2011-2012""&gt;" I want to extract the twelve from 2011-2012 for example, from the worksheet column. I would like to use the following code in order to extract the last two digits that match the pattern, however I get an error: Can only tuple-index with a MultiIndex df['worksheet'].str.findall('\d{2}')[:,-1] How can I correctly extract using the pattern from the worksheet column and only retrieve the last instance? The result should look like: 12 12 12 13 13 12 12 12 12 12 12 12 12 12 12
score: 0
has answer: http://stackoverflow.com/a/49031254
answer count: 3
tagged with: pandas
upvote count: 1

http://stackoverflow.com/comment/85021089
type: Comment
has text: Nvm. Solved it. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/49004239
score: 0

http://stackoverflow.com/comment/85174934
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49084821
type: Comment
has text: have you tried adding the ":" like that re.findall(":\d+", x)

http://stackoverflow.com/comment/85073410
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49034016
has text: I don't know why you think that makes a difference. The point is, you need to patch where it is *called* - ie within your views - not where it is imported from.

authentication
tags question: http://stackoverflow.com/q/49084619
tags question: http://stackoverflow.com/q/49115909
tag name: authentication
type: Tag
tags question: http://stackoverflow.com/q/49004046
tags question: http://stackoverflow.com/q/48972677
tags question: http://stackoverflow.com/q/49004536
tags question: http://stackoverflow.com/q/49117411
tags question: http://stackoverflow.com/q/49004504
tags question: http://stackoverflow.com/q/49089744

http://stackoverflow.com/comment/85046118
score: 0
has text: if you normalize your data you will also be normalizing your MSE. You are saying that normalizing improved your error beyond what you would expect?
type: Comment
comment on: http://stackoverflow.com/a/49013012
type: AnswerComment

http://stackoverflow.com/q/48976901
answer count: 1
tagged with: kivy
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48977084
upvote count: 1
tagged with: python
has body: I want to print out the position of the pointer (mouse) everytime it passes over a widget. Actually to be more specific I'd like to print the current position of the mouse everytime it moves. Is that at all possible? Right now all I've managed to do is: Print the position of the mouse whenever the mouse is clicked (in two different ways) Print the position of the widget when it's clicked I'm sure it's easier than I think, thanks in advance. from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.app import App from kivy.uix.button import Button from kivy.lang import Builder from kivy.base import runTouchApp from kivy.uix.screenmanager import ScreenManager, Screen from kivy.input.motionevent import MotionEvent class MainScreen(Screen): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) def on_mouse_pos(self, pos): if Window.mouse_pos == self.ids.example_button: print("You've made it") # With out this if statement it does print the position every time # That the mouse is moved. But can I print "You've made it" every time # that the mouse is moved over the position of a widget? print(pos) def test_print(self): print(str(self.ids.example_button.pos)) Window.bind(mouse_pos = on_mouse_pos) class MyScreenManager(Screen): pass root_widget = Builder.load_string(''' MyScreenManager: MainScreen: &lt;MainScreen&gt;: name: 'Example' Button: id: example_button text: 'Print position of widget when mouse touches it' size_hint: 1, .05 pos_hint: {'x': 0, 'y': .5} on_release: root.test_print() ''') class TestApp(App): def build(self): self.title = 'Example Application' return root_widget if __name__ == '__main__': TestApp().run()
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/48977084
downvote count: 0
has title: How can I print the position of the pointer every time the mouse is moved over a widget in kivy?

http://stackoverflow.com/comment/85153384
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49063689
has text: Please do not add the solution to your question. If you found a solution that worked best for you, then you can accept it below or answer your own question. This site encourages multiple solutions from other users, as the one that worked best for you may not work the best for someone else. Your question has been rolled back to its previous state. For more information, please visit the [help].
score: 0

http://stackoverflow.com/q/48994440
has answer: http://stackoverflow.com/a/51013358
has answer: http://stackoverflow.com/a/63080968
upvote count: 116
has body: I have some code that needs to execute after Flask returns a response. I don't think it's complex enough to set up a task queue like Celery for it. The key requirement is that Flask must return the response to the client before running this function. It can't wait for the function to execute. There are some existing questions about this, but none of the answers seem to address running a task after the response is sent to the client, they still execute synchronously and then the response is returned. Python Flask sending response immediately Need to execute a function after returning the response in Flask Flask end response and continue processing
has answer: http://stackoverflow.com/a/56345908
has answer: http://stackoverflow.com/a/68462833
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51673851
linked to: http://stackoverflow.com/q/31063904
has answer: http://stackoverflow.com/a/66674957
has answer: http://stackoverflow.com/a/67846012
tagged with: flask
linked to: http://stackoverflow.com/q/18082683
favorite count: 0
score: 114
has answer: http://stackoverflow.com/a/48994441
type: Question
has answer: http://stackoverflow.com/a/60663373
tagged with: python
answer count: 10
has answer: http://stackoverflow.com/a/60849977
linked to: http://stackoverflow.com/q/17293311
has title: Execute a function after Flask returns response
downvote count: 2
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/48994441
possible better answer: http://stackoverflow.com/a/51013358

http://stackoverflow.com/comment/85070284
has text: If you separate it, e.g. `..., "-e", "ssh", "-i", "/path/to/public.key", ..."` then `/path/to/public.key` is treated a separate argument to rsync, rather than part of the value for the `-e` option.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49032494

http://stackoverflow.com/a/49086832
has comment: http://stackoverflow.com/comment/85182219
has comment: http://stackoverflow.com/comment/85182095
has comment: http://stackoverflow.com/comment/85182245
score: 1
has comment: http://stackoverflow.com/comment/125562290
downvote count: 1
has body: I sometimes need a similar method to debug recursive code. A very simple method is to declare a variable in a scope outside the recursive function. iterations_f1 = 10 iterations_f2 = 10 Then add some logic temporarily inside the recursive function to return before another recursive call if the iterations have been met. def f1(t): global iterations_f1 iterations_f1 = iterations_f1 - 1 if iterations_f1 == 0: return # rest of funtion ...
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85182174
answers question: http://stackoverflow.com/q/49086677
has comment: http://stackoverflow.com/comment/124401850
accepted answer of: http://stackoverflow.com/q/49086677
has comment: http://stackoverflow.com/comment/85179085
type: Answer
has comment: http://stackoverflow.com/comment/125560510
upvote count: 2
has comment: http://stackoverflow.com/comment/124418423

http://stackoverflow.com/comment/85240719
type: AnswerComment
score: 0
type: Comment
has text: what did you use to find spokes? You literally found all this in 5 minutes, but I've been trying to do it for 2 days. How can I check continuity of the spokes and more important, how to find it? I used Canny, HoughCircles, but I didn't get picture as you.
comment on: http://stackoverflow.com/a/49107076

http://stackoverflow.com/q/49089744
has answer: http://stackoverflow.com/a/49098982
tagged with: webdriver
has body: I have a question. I have 10 classes in 10 files and one main class and class with user log. I run all tests in the main class. I would like to run 10 at once. At present, the browser opens up to 10 times with each class. I would like 10 tests to take place in 1 browser session. It is possible? Because I can not do this. Please, help me, thank you! Me login class: class Login(unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = webdriver.Chrome() def setUp(self): self.browser.get("www") username = self.browser.find_element_by_id("username") password = self.browser.find_element_by_id("password") username.send_keys("aaaa") password.send_keys("ssswww") self.browser.find_element_by_id("button").click() def tearDown(self): self.browser.get("about:blank") @classmethod def tearDownClass(cls): cls.browser.quit()
answer count: 3
has answer: http://stackoverflow.com/a/57610103
has comment: http://stackoverflow.com/comment/85185120
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85186838
has answer: http://stackoverflow.com/a/49090806
has title: python selenium all test in one session browser
score: 0
tagged with: selenium
tagged with: authentication
type: Question
linked to: http://stackoverflow.com/q/6563725

http://stackoverflow.com/comment/85347243
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49103460
type: AnswerComment
has text: hmm i see but it seems to change it immediately after i press enter, does he delay need to be in miliseconds?

http://stackoverflow.com/q/49044011
has comment: http://stackoverflow.com/comment/85092977
has title: How to include modules and submodules in the application directory?
answer count: 0
has comment: http://stackoverflow.com/comment/85095120
type: Question
tagged with: paramiko
tagged with: python-2.7
score: 0
type: UnansweredQuestion
has body: I am trying to deploy a small application on a server, which has some dependencies (specifically - paramiko). I do not have root access to the server, and creating a virtual environment is not possible. How can I somehow package the said dependencies along with my code? I looked through StackOverflow quite a bit getting answers using a single package, but paramiko has further dependencies like cryptography, which is where any given solution fails. Of note is the fact that cryptography has nested modules. How do I include everything?
tagged with: python

pca
tag name: pca
tags question: http://stackoverflow.com/q/49067522
type: Tag

http://stackoverflow.com/q/49115877
tagged with: python
has comment: http://stackoverflow.com/comment/85237262
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49116097
type: Question
has title: Is there a pandas way of getting the averages between consecutive rows?
possible better answer: http://stackoverflow.com/a/49116097
downvote count: 0
has answer: http://stackoverflow.com/a/49116088
answer count: 2
tagged with: pandas
favorite count: 0
has body: import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(30,3)) df.head() which gives: 0 1 2 0 0.741955 0.913681 0.110109 1 0.079039 0.662438 0.510414 2 0.469055 0.201658 0.259958 3 0.371357 0.018394 0.485339 4 0.850254 0.808264 0.469885 Say I want to add another column that will build the averages in column 2: between index (0,1) (1,2)... (28,29). I imagine this is a common task as column 2 are the x axis positions and I want the categorical labels on a plot to appear in the middle between the 2 points on the x axis. So I was wondering if there is a pandas way for this: averages = [] for index, item in enumerate(df[2]): if index &lt; df[2].shape[0] -1: averages.append((item + df[2].iloc[index + 1]) / 2) df["averages"] = pd.Series(averages) df.head() which gives: 0 1 2 averages 0 0.997044 0.965708 0.211980 0.318781 1 0.716349 0.724811 0.425583 0.378653 2 0.729991 0.985072 0.331723 0.333138 3 0.996487 0.272300 0.334554 0.586686 as you can see 0.31 is an average of 0.21 and 0.42. Thanks!
linked to: http://stackoverflow.com/q/43437657
upvote count: 2
accepted answer: http://stackoverflow.com/a/49116088

http://stackoverflow.com/q/49010166
has comment: http://stackoverflow.com/comment/85028254
has comment: http://stackoverflow.com/comment/85027248
type: Question
has comment: http://stackoverflow.com/comment/85026490
has comment: http://stackoverflow.com/comment/85026290
tagged with: database
has comment: http://stackoverflow.com/comment/85024904
has comment: http://stackoverflow.com/comment/85028368
has title: OperationalError when converting from sqlite3 to postgresql
score: 0
has comment: http://stackoverflow.com/comment/85026049
has comment: http://stackoverflow.com/comment/85025596
has comment: http://stackoverflow.com/comment/85027557
has body: I tried changing my db from sqlite3 to postgresql using this tutorial: https://tutorial-extensions.djangogirls.org/en/optional_postgresql_installation/ but when i try to migrate i get the following error Traceback (most recent call last): File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\managemen…
has comment: http://stackoverflow.com/comment/85025210
tagged with: postgresql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85026701
tagged with: django
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/85025342
answer count: 0

http://stackoverflow.com/comment/85180855
comment on: http://stackoverflow.com/q/49080398
score: 0
type: QuestionComment
has text: `new_pos = (new_pos % 25) - 1`. Hmm, that's an interesting alphabet, with just 25 characters starting at -1.
type: Comment

http://stackoverflow.com/comment/99165417
type: Comment
comment on: http://stackoverflow.com/a/56270757
score: 2
has text: Please don't use batches to inserting data into different partitions - you're adding more load to the nodes, and really decreasing throughput. Better option is to issue async requests... Here is more on "bad use" of batches: https://docs.datastax.com/en/cql/3.3/cql/cql_using/useBatchBadExample.html
type: AnswerComment

http://stackoverflow.com/q/49058790
type: Question
has body: I'm trying to make a form in which a certain field, title, is pre-populated when another field, checkin_type, is selected from a drop-down menu. I'm trying to follow the approach outlined in Django: How to pre-populate FormView with dynamic (non-model) data? and have put a 'proof-of-concept' project here: https://github.com/khpeek/django-dynamic-form. In the view's template, I've made it such that when the checkin_type field has a .change(), an AJAX POST request is sent with the id of the selected check-in type: {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} In views.py, I've tried the following: import logging import sys from django.views import generic from .models import CheckIn, CheckInType from django.http import HttpResponse def get_stdout_logger(name, level): logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler(sys.stdout) handler.setLevel(level) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return logger logger = get_stdout_logger(__name__, level=logging.DEBUG) class CheckInCreate(generic.CreateView): model = CheckIn fields = '__all__' def post(self, request, *args, **kwargs): if request.is_ajax(): logger.debug(f"Received AJAX POST request with the following request.POST data: {request.POST}") self.checkin_type = CheckInType.objects.get(pk=request.POST['id']) return super().post(request, *args, **kwargs) def get_initial(self): initial = super().get_initial() if hasattr(self, 'checkin_type'): initial.update(title=self.checkin_type.title) logger.debug(f"Getting initial: {initial}") return initial def form_valid(self, *args, **kwargs): logger.debug("The form is valid!") return super().form_valid(*args, **kwargs) def form_invalid(self, form): logger.debug("The form is invalid!") if hasattr(self, 'checkin_type'): form['title'].initial = self.checkin_type.title logger.debug…
score: 0
has comment: http://stackoverflow.com/comment/85122755
has title: Django CreateView's form not re-rendering as expected
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85122775
tagged with: django
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/22083218

http://stackoverflow.com/comment/84975685
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [how can i delete whole day rows on condition column values.. pandas](https://stackoverflow.com/questions/48556510/how-can-i-delete-whole-day-rows-on-condition-column-values-pandas)
comment on: http://stackoverflow.com/q/48985027

http://stackoverflow.com/q/49052751
type: Question
has title: Create a Qgis Icon based on an existing Icon
tagged with: open-source
tagged with: gdal
upvote count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: qgis
has body: I am in need to create a Qgis icon similar to the existing Selection Qgis icon Select features by are or single click. I will create a new Icon to do exactly what the existing Qgis icon does and add some more script to it. 1 - I need to get the code for this existing Icon Select features by are or single click. 2 - Add the following code to it: layer = iface.activeLayer() selection = layer.selectedFeatures() print len(selection) for f in layer.selectedFeatures(): layer_xml = iface.addRasterLayer(f['tms'], f['name']) Any help on that will be very appreciated.
tagged with: python
answer count: 0
score: 1
tagged with: gis

http://stackoverflow.com/comment/85103890
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49026563
type: Comment
has text: Thanks a lot. Let me try, will comment here if Im unable to resolve the conflict regarding the Named entites. Just one last doubt, For the names, whose embedding is not present in word2vec vocabulary, should I remove them or replace them with words like "he/she"

http://stackoverflow.com/q/49091931
has body: An update to my previous post, with some changes: Say that I have 100 tweets. In those tweets, I need to extract: 1) food names, and 2) beverage names. I also need to attach type (drink or food) and an id-number (each item has a unique id) for each extraction. I already have a lexicon with names, type and id-number: lexicon = { 'dr pepper': {'type': 'drink', 'id': 'd_123'}, 'coca cola': {'type': 'drink', 'id': 'd_234'}, 'cola': {'type': 'drink', 'id': 'd_345'}, 'banana': {'type': 'food', 'id': 'f_456'}, 'banana split': {'type': 'food', 'id': 'f_567'}, 'cream': {'type': 'food', 'id': 'f_678'}, 'ice cream': {'type': 'food', 'id': 'f_789'}} Tweet example: After various processing of "tweet_1" I have this sentences: sentences = [ 'dr pepper is better than coca cola and suits banana split with ice cream', 'coca cola and banana is not a good combo'] My requested output (can be other type than list): ["tweet_id_1", [[["dr pepper"], ["drink", "d_124"]], [["coca cola"], ["drink", "d_234"]], [["banana split"], ["food", "f_567"]], [["ice cream"], ["food", "f_789"]]], "tweet_id_1",, [[["coca cola"], ["drink", "d_234"]], [["banana"], ["food", "f_456"]]]] It's important that the output should NOT extract unigrams within ngrams (n>1): ["tweet_id_1", [[["dr pepper"], ["drink", "d_124"]], [["coca cola"], ["drink", "d_234"]], [["cola"], ["drink", "d_345"]], [["banana split"], ["food", "f_567"]], [["banana"], ["food", "f_456"]], [["ice cream"], ["food", "f_789"]], [["cream"], ["food", "f_678"]]], "tweet_id_1", [[["coca cola"], ["drink", "d_234"]], [["cola"], ["drink", "d_345"]], [["banana"], ["food", "f_456"]]]] Ideally, I would like to be able to run my sentences in various nltk filters like lemmatize() and pos_tag() BEFORE the extraction to get an output like the following. But with this regexp solution, if I do that, then all the words are split into unigrams, or they will generate 1 unigram and 1 bigram from the string "coca cola", which would generate the output that I did not wa…
favorite count: 0
linked to: http://stackoverflow.com/q/49064114
upvote count: 2
type: UnansweredQuestion
has title: n-grams from text in python
has comment: http://stackoverflow.com/comment/85192865
tagged with: python
has answer: http://stackoverflow.com/a/49094843
tagged with: regex
tagged with: nlp
has comment: http://stackoverflow.com/comment/85196749
type: Question
has answer: http://stackoverflow.com/a/49092089
has answer: http://stackoverflow.com/a/49092451
tagged with: nltk
downvote count: 0
tagged with: n-gram
answer count: 3
score: 2

gnuradio
tags question: http://stackoverflow.com/q/49095278
tag name: gnuradio
type: Tag
tags question: http://stackoverflow.com/q/49031690

http://stackoverflow.com/q/49029324
possible better answer: http://stackoverflow.com/a/49029389
favorite count: 0
has answer: http://stackoverflow.com/a/49029389
has title: Accessing objects from list in other file
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85063316
type: Question
tagged with: object
accepted answer: http://stackoverflow.com/a/49029839
has body: So i have two files User.py that contains User class and UserInformation.py that handles list of all Users created. Why cant i access User data from my UserInformation.py list. User.py: class User(object): name = "" age = 0 def __init__(self, name, age): self.name = name self.age = age def toString(self): print("Name: " + self.name + ", Age: " + str(self.age)) And UserInformation.py import User listOfUsers = [] def addUser(User): listOfUsers.append(User) def listUsers(User): x = 0 while x &lt; len(listOfUsers): listOfUsers[x].toString() x= x+1 What is wrong why cant i print User objects?
answer count: 2
has answer: http://stackoverflow.com/a/49029839
upvote count: 1

http://stackoverflow.com/q/49034403
has answer: http://stackoverflow.com/a/49034883
has comment: http://stackoverflow.com/comment/85073885
has comment: http://stackoverflow.com/comment/85074303
has comment: http://stackoverflow.com/comment/85074685
has comment: http://stackoverflow.com/comment/85074849
type: Question
has comment: http://stackoverflow.com/comment/85075122
linked to: http://stackoverflow.com/q/13482091
has comment: http://stackoverflow.com/comment/85074959
has comment: http://stackoverflow.com/comment/85074809
score: 0
has title: UPDATE query without hardcoding column names
tagged with: sql
has comment: http://stackoverflow.com/comment/85075482
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/85074363
has comment: http://stackoverflow.com/comment/85074739
has comment: http://stackoverflow.com/comment/85074089
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85075200
has comment: http://stackoverflow.com/comment/85073834
has body: Let's say mytable has 5 columns, id being the first one. Is it possible to do an UPDATE without hardcoding the column names? UPDATE mytable VALUES(4, "hello", 31.12, 4141.12, "gjhg") WHERE id = 4 I haven't found it in most tutorials. Desired use case with sqlite3: row = (4, "hello", 31.12, 4141.12, "gjhg") c.execute('UPDATE mytable VALUES(?) WHERE id = ?', row, row[0])
tagged with: python
has comment: http://stackoverflow.com/comment/85074906

http://stackoverflow.com/comment/85044151
type: QuestionComment
comment on: http://stackoverflow.com/q/49016723
has text: I have added the relevant code to the question. The rest of the code is in the github repository linked above. I will add a bounty to this question if you help me solve the problem.
score: 0
type: Comment

http://stackoverflow.com/q/49035311
has title: change shader on all assigned meshes, without using hyperShade()
has comment: http://stackoverflow.com/comment/85098839
upvote count: 1
has body: I get all shapes assigned to baseMaterial, select the shapes and then assign the occlusionShader. for materialClass in materialClassList: select(materialClass.baseMaterial) hyperShade(objects="") hyperShade(a=materialClass.occlusionShader) works just fine, but if I use it as a pre render script: Error: line 0: hyperShade command not supported in batch mode What can I change the two last lines of my function to to make this work?
tagged with: maya
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49046788
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49049131
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/49049131
score: 1
has answer: http://stackoverflow.com/a/49046788
answer count: 2

http://stackoverflow.com/comment/85221298
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49108148
has text: I have a working code, something like this: ``` from PyQt4.QtGui import QMessageBox QMessageBox.information(parent, title, message) ``` can you try to do import like mine? Also, you have a different indentation. Perhaps you can fix that also.

http://stackoverflow.com/q/49073295
has answer: http://stackoverflow.com/a/49073452
upvote count: 5
has answer: http://stackoverflow.com/a/61449934
type: Question
answer count: 2
has title: Possible to decompress bz2 in python to a file instead of memory
downvote count: 0
has body: I've worked with decompressing and reading files on the fly in memory with the bz2 library. However, i've read through the documentation and can't seem to just simply decompress the file to create a brand new file on the file system with the decompressed data without memory storage. Sure, you could read line by line using BZ2Decompressor then write that to a file, but that would be insanely slow. (Decompressing massive files, 50GB+). Is there some method or library I have overlooked to achieve the same functionality as the terminal command bz2 -d myfile.ext.bz2 in python without using a hacky solution involving a subprocess to call that terminal command? Example why bz2 is so slow: Decompressing that file via bz2 -d: 104seconds Analytics on a decompressed file(just involves reading line by line): 183seconds with open(file_src) as x: for l in x: Decompressing on the file and using analytics: Over 600 seconds (This time should be max 104+183) if file_src.endswith(".bz2"): bz_file = bz2.BZ2File(file_src) for l in bz_file:
favorite count: 0
tagged with: python
type: UnansweredQuestion
tagged with: compression
score: 5

jquery
tags question: http://stackoverflow.com/q/49015016
tags question: http://stackoverflow.com/q/48994091
type: Tag
tags question: http://stackoverflow.com/q/49109399
tags question: http://stackoverflow.com/q/49036297
tags question: http://stackoverflow.com/q/48981746
tags question: http://stackoverflow.com/q/49069683
tag name: jquery
tags question: http://stackoverflow.com/q/49035043
tags question: http://stackoverflow.com/q/49030104
tags question: http://stackoverflow.com/q/49065891
tags question: http://stackoverflow.com/q/49036162
tags question: http://stackoverflow.com/q/48996797
tags question: http://stackoverflow.com/q/49037998

http://stackoverflow.com/comment/85149817
score: 1
has text: @rdv Take a look at [this](https://stackoverflow.com/a/45380994/5116726)
type: AnswerComment
comment on: http://stackoverflow.com/a/49060411
type: Comment

http://stackoverflow.com/comment/84992049
comment on: http://stackoverflow.com/a/48979312
score: 0
type: AnswerComment
has text: Correctly. Therefore deep recursion is dangerous. Each time you go to a deeper level, the size of the memory occupied by the call stack increases and you can get an exception. In Python you can set limit of recursion levels: `sys.setrecursionlimit(10000)`
type: Comment

http://stackoverflow.com/q/49075214
tagged with: docker
has comment: http://stackoverflow.com/comment/93347120
tagged with: nvidia-docker
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I followed this article to setup my GPU server, install CUDA and pull the nvidia-docker image that runs a gpu-enabled tensorflow instance with a jupyter notebook installed. however, I noticed I do not have anaconda3 inside that in order to update to python 3.6 and update all the packages. I wasnt able to attach the nividia-docker image and install anaconda3, since all the commands like wget to download are missing. How would I do it or is there an alternative way?
tagged with: anaconda
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has title: tensorflow nvidia gpu docker image - how to combine with anaconda3

http://stackoverflow.com/a/49021876
accepted answer of: http://stackoverflow.com/q/49021811
type: Answer
has body: You need to add languages into template context inside your view. Something like this: context = {'languages': Languages.objects.all()} return render(request, 'index.html', context)
answers question: http://stackoverflow.com/q/49021811
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85166205
type: QuestionComment
has text: seems to work for me
comment on: http://stackoverflow.com/q/49080143
score: 0
type: Comment

http://stackoverflow.com/comment/84947547
score: 0
has text: I've tried to explain further, thank you for clarifying.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48971104

http://stackoverflow.com/q/49100309
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85205865
has comment: http://stackoverflow.com/comment/85206667
type: Question
tagged with: instantiation
tagged with: object
has comment: http://stackoverflow.com/comment/85205943
has answer: http://stackoverflow.com/a/49100397
accepted answer: http://stackoverflow.com/a/49100397
tagged with: class
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49100372
has comment: http://stackoverflow.com/comment/85206724
has body: I wondered if its better to: Pass Object1 into Object2 for use or Instantiate Object1 from Object2 I could do either, but I am wondering what is better practice, or where i could get caught up. These are rather rudimentary examples, and of course in the second example, i could just use the list. The actual code I am using, i need to use a lot of Object1 values to do things in Object2. Example 1: class Object1: def __init__(self, person): self.id = person[0] self.name = person[1] self.age = person[2] class Object2: def __init__(self, object1): self.object1 = object1 retirement_age = self.object1.age + 25 print(self.object1.id) print(self.object1.name) print(retirement_age) person = [1, 'Ryan', 30] o = Object1(person) r = Object2(o) Example 2: class Object1: def __init__(self, person): self.id = person[0] self.name = person[1] self.age = person[2] class Object2: def __init__(self, person): self.o = Object1(person) retirement_age = self.o.age + 25 print(self.o.id) print(self.o.name) print(retirement_age) person = [1, 'Ryan', 30] r = Object2(person)
has title: python pass object or instantiate from within second object
possible better answer: http://stackoverflow.com/a/49100372

http://stackoverflow.com/q/49051409
has comment: http://stackoverflow.com/comment/85107479
score: 0
tagged with: pandas
has body: EDIT: I had made a mistake and my index was starting at 00:00:00, not at 06:00:00 (see below). So this question is spurious, but of course Wen's solution is correct. I have a dataframe whose index goes like this: 2017-11-01 06:00:00 2017-11-02 06:00:00 2017-11-03 06:00:00 ... and so on. But I have the suspicion there're missing entries, for instance, index for 2017-11-04 06:00:00 could be missing. I have used df = df.asfreq(freq="1D") to fill with NaN the missing values, but it creates a new index that doesn't take into consideration the hours, it goes 2017-11-01, 2017-11-02 and so on, so the values in the adjacent column are all NaN! How can I fix this? I don't see any option in asfreq that can solve it. Perhaps other tool? Thanks in advance.
tagged with: python
accepted answer: http://stackoverflow.com/a/49051613
type: AnsweredQuestion
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/19324453
has comment: http://stackoverflow.com/comment/85107552
has title: Using asfreq to resample a pandas dataframe
has answer: http://stackoverflow.com/a/49051613

http://stackoverflow.com/a/49018709
answers question: http://stackoverflow.com/q/49018644
has body: You could do this: df.assign(sum=df.groupby('id')['price'].transform('sum').drop_duplicates(keep='last')).fillna(0) OR df['sum'] = (df.groupby('id')['price'] .transform('sum') .mask(df.id.duplicated(keep='last'), 0)) Output: id price sum 0 1 2 0.0 1 1 6 0.0 2 1 4 12.0 3 2 2 0.0 4 2 10 0.0 5 2 1 0.0 6 2 5 18.0 7 3 1 0.0 8 3 5 6.0
score: 6
type: Answer
downvote count: 0
upvote count: 6

http://stackoverflow.com/comment/85165232
type: QuestionComment
has text: I actually did my work before posting. It may be environment issue but I actually install lmdb globally `condo install lmdb` I also run python NOT in any environment. If I install use `pip install lmdb` It allows me to access lmdb from any environment. There are some differences between pip and condo for lmdb library.
comment on: http://stackoverflow.com/q/49074022
score: 0
type: Comment

http://stackoverflow.com/comment/85109030
type: QuestionComment
comment on: http://stackoverflow.com/q/49052163
score: 0
has text: Sorry for the confusion. Each sequence for its respective read is required. I will update to reflect this.
type: Comment

http://stackoverflow.com/comment/85041067
has text: if OP's goal is to slice, I'd agree with @wim (same as in duplicate question https://stackoverflow.com/questions/18272160/access-multiple-elements-of-list-knowing-their-index)
type: Comment
comment on: http://stackoverflow.com/q/49017818
score: 0
type: QuestionComment

http://stackoverflow.com/q/49111590
score: 0
tagged with: deep-learning
answer count: 1
tagged with: keras
has title: keras activation function layer: model.add Activation('relu') gives invalid syntax
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49111766
has body: model = sequential () model.add(convolutional2D(32,3,3 , input_shape = (img_width, img_height,3)) model.add(Maxpooling2D(pool_size=(2,2))) model.add(Activation('relu')) model.add(convolutional2D(32,3,3)) model.add(Activation('relu')) model.add(MaxpoolingD2(pooling_size=(2,2))) model.add(convolutional2D(32,3,3,)) model.add(Activation('relu')) model.add(Maxpooling2D(pooling_size=(2,2))) model.add(Flatten()) model.add(dense(64)) model.add(Activation('relu')) model.add(dropout(0.5)) model.add(dense(1)) model.add(activation(sigmoid)) please someone should help out. I use jupyter notebook in python 2.7 environment and the above code returns: File "&lt;ipython-input-11-fab080993955&gt;", line 4 model.add(Activation('relu')) ^ SyntaxError: invalid syntax what could be the problem?

http://stackoverflow.com/comment/85015570
has text: Updated the question apologies, hadn't realised some descriptions have spaces in the string
comment on: http://stackoverflow.com/a/49005227
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84998560
has text: The error message suggests that `turtle1.width` is an integer, therefore cannot be called. Please cut the code down to a [mcve] (see e.g. https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for guidance).
comment on: http://stackoverflow.com/q/48996361
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/49059341
score: 0
answer count: 1
tagged with: pandas
tagged with: python
has body: Lets say I have 3 variables A, B and C for a long period of time. I can get a correlation matrix in pandas for a window of first 3 days simply by using .corr() A B C 23/2/2017 21.93 4.48 13.27 24/2/2017 2.65 10.18 11.95 25/2/2017 8.74 10.67 6.30 26/2/2017 6.88 10.26 8.40 27/2/2017 12.20 9.56 12.82 28/2/2017 8.12 9.54 2.67 A B C A 1 B -0.93 1 C 0.38 -0.70 1 This matrix can also be presented in table form: (A,B) (B,C) (C,A) 23/2/2017 NaN NaN NaN 24/2/2017 NaN NaN NaN 25/2/2017 -0.93 -0.70 0.38 What i need is a rolling window of 3 days with pairwise correlations populated like the table form above. I understand there's the pd.corring_corr(pairwise=True) function, just haven't got a clue how to obtain in a table format, with all possible combinations as columns. Appreciate if anyone can help. Thanks!
tagged with: correlation
type: UnansweredQuestion
has title: Multivariate rolling correlation in pandas
has answer: http://stackoverflow.com/a/49067186
type: Question
tagged with: time-series

http://stackoverflow.com/a/49109519
type: Answer
answers question: http://stackoverflow.com/q/49109400
upvote count: 3
score: 3
has body: There is a built-in library for that: import re result = re.split('from|join|where', yourStr) PS: @anubhava solution is better, which includes whitespaces to the determinators during the split.
downvote count: 0

http://stackoverflow.com/q/49093981
has title: Matplotlib - computing screen coordinates for function calls
downvote count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49095489
score: 1
favorite count: 0
type: Question
has body: I just started to explore matplotlib and related documentation. There is one thing which I am still not clear about even after going through the documentation. Below are some statements I copied from random examples. Most of the functions take arguments related to screen positions, for example: margin, padding, text placement/position etc. Most of the arguments are not the x,y arguments (numpy array) of the plot/bar etc, but screen positions. For instance when I see an example program on the documentation using margin = 0.2, how was this value arrived at? Was it based on trial and error? Same goes for padding, figtext,etc. I do not want to do this trial and error approach for each of these kind of functions and see how my figure looks. Is there any way to compute these values? Or is there any recommended standard which I can use to form my imagination when I call such functions. plt.margins(0.2) fig.subplots_adjust(top=0.85) plt.figtext(0.9, 0.05, '$x$') ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) ax.annotate('annotate', xy=(2, 1), xytext=(3, 4), arrowprops=dict(facecolor='black', shrink=0.05))
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/49095489
tagged with: matplotlib
upvote count: 1

http://stackoverflow.com/comment/85210593
comment on: http://stackoverflow.com/a/49102680
has text: why do you say `In your particular case, you don't actually seem to need a regex, though.,`, `I am trying to match line #define EPI_VERSION_STR "9.130.27 (TOB) (r749679 ASSRT)"` ,the `9.130.27` and `749679` can change
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49105344
tagged with: openpyxl
possible better answer: http://stackoverflow.com/a/70029024
type: Question
has answer: http://stackoverflow.com/a/70029024
has answer: http://stackoverflow.com/a/49105761
has body: I am trying to install a python library, openpyxl. I just installed python 3.6 on my windows 10 work computer. The result of my installation attempt is below. I found a related question: pip install and custom index url If my problem is use of a proxy, is there something I can do to install openpyxl anyway? C:\Users\00168070>pip install openpyxl Collecting openpyxl Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError>(': Failed to establish a new connection: [Errno 11002] getaddrinfo failed',)': /simple/openpyxl/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno 11002] getaddrinfo failed',)': /simple/openpyxl/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno 11002] getaddrinfo failed',)': /simple/openpyxl/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno 11002] getaddrinfo failed',)': /simple/openpyxl/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno 11002] getaddrinfo failed',)': /simple/openpyxl/ Could not find a version that satisfies the requirement openpyxl (from versions: ) No matching distribution found for openpyxl
has comment: http://stackoverflow.com/comment/85216355
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49105761
tagged with: proxy
linked to: http://stackoverflow.com/q/31559638
has title: failure to install openpyxl with pip--how to overcome proxy
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/29267024
upvote count: 2

http://stackoverflow.com/comment/85064163
score: 0
type: Comment
type: QuestionComment
has text: what is the value of nose_rect when it doesn't detect the nose?
comment on: http://stackoverflow.com/q/49029751

http://stackoverflow.com/a/49033389
score: 1
has body: List comprehensions. alphabets = {'it': {'a', 'b', 'c', 'd', 'e', 'à', 'ì'}, 'en': {'a', 'b', 'c', 'd', 'e'}, 'pl': {'a', 'b', 'c', 'd', 'e', 'ę', 'ś'}} def f(k, d): #return [x for x in d[k] if any(x not in v for k,v in d.items())] return {x for x in d[k] if any(x not in v for k,v in d.items())} print(f('pl', alphabets)) print(f('en', alphabets)) print(f('it', alphabets))
downvote count: 0
answers question: http://stackoverflow.com/q/49033130
type: Answer
has comment: http://stackoverflow.com/comment/85072241
upvote count: 1

database
tags question: http://stackoverflow.com/q/49010166
tags question: http://stackoverflow.com/q/49048533
tags question: http://stackoverflow.com/q/49021344
tags question: http://stackoverflow.com/q/49051507
tags question: http://stackoverflow.com/q/49012507
tags question: http://stackoverflow.com/q/49019088
tags question: http://stackoverflow.com/q/48997492
tags question: http://stackoverflow.com/q/48973532
type: Tag
tags question: http://stackoverflow.com/q/49119128
tags question: http://stackoverflow.com/q/49080455
tags question: http://stackoverflow.com/q/49051102
tags question: http://stackoverflow.com/q/49054375
tag name: database
tags question: http://stackoverflow.com/q/48972271
tags question: http://stackoverflow.com/q/49093469
tags question: http://stackoverflow.com/q/49101208
tags question: http://stackoverflow.com/q/49042878
tags question: http://stackoverflow.com/q/49080538
tags question: http://stackoverflow.com/q/48995023
tags question: http://stackoverflow.com/q/49003698

http://stackoverflow.com/comment/85020780
type: Comment
type: QuestionComment
score: 0
has text: Ok thanks Nae for your suggestion. As per my understanding using place we can place our frames or entry based on X, Y position. Is that correct?
comment on: http://stackoverflow.com/q/49007295

http://stackoverflow.com/q/49080405
has body: I am using InceptionV3 Model from Keras for extracting feature. Lets say I have 1000 images and I got the last layer with shape (1000, 8, 8, 2048). Which 1000 from data size and (8, 8, 2048) from last convolutional layer. How can I implement Global Average Pooling? I am expecting the shape is (1000, 1, 1, 2048).
tagged with: scikit-image
tagged with: numpy
has comment: http://stackoverflow.com/comment/85167831
downvote count: 0
type: UnansweredQuestion
tagged with: keras
has answer: http://stackoverflow.com/a/49081906
has comment: http://stackoverflow.com/comment/85172312
tagged with: keras-layer
type: Question
score: 1
has answer: http://stackoverflow.com/a/58833122
favorite count: 0
has title: Global Average Pooling from Array
answer count: 2
upvote count: 1
tagged with: python

epub
type: Tag
tags question: http://stackoverflow.com/q/49089296
tag name: epub

http://stackoverflow.com/comment/85257635
type: Comment
score: 1
type: AnswerComment
has text: Ah, sorry wasn't clear that the output should be limited to A-B and C-D, as the example given only contains A-B and C-D entries... and states "The same for the rest of pairs."
comment on: http://stackoverflow.com/a/49119429

http://stackoverflow.com/comment/85035934
comment on: http://stackoverflow.com/q/49015192
type: Comment
type: QuestionComment
score: 1
has text: It's something to do with the shape of your data

http://stackoverflow.com/comment/84938617
type: Comment
type: QuestionComment
has text: The same thing you put below to call function `main`. But it's not going to work without some reorganisation.
score: 1
comment on: http://stackoverflow.com/q/48966507

http://stackoverflow.com/q/48981395
has body: I have 10 images I want to process. How do I call all those images one by one? (Figure 1 is called-process-complete) (Figure 2 called-process-complete) and so on. How to do this in OpenCv python? Thanks
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48981483
score: -5
has comment: http://stackoverflow.com/comment/84967880
has title: How to load image by name in opencv python?
type: Question
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84968178
downvote count: 5
accepted answer: http://stackoverflow.com/a/48981483

http://stackoverflow.com/comment/85044861
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48998659
has text: it should rather be [1,1,....1,1,0] form
score: 0

http://stackoverflow.com/q/49030629
has answer: http://stackoverflow.com/a/49210913
tagged with: python
type: AnsweredQuestion
has title: Statistical Profiling in Python
has comment: http://stackoverflow.com/comment/85068381
type: Question
has answer: http://stackoverflow.com/a/58995596
upvote count: 13
accepted answer: http://stackoverflow.com/a/58995596
score: 12
answer count: 3
tagged with: usage-statistics
has body: I would like to know that the Python interpreter is doing in my production environments. Some time ago I wrote a simple tool called live-trace which runs a daemon thread which collects stacktraces every N milliseconds. But signal handling in the interpreter itself has one disadvantage: Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the “atomic” instructions of the Python interpreter. This means that signals arriving during long calculations implemented purely in C (such as regular expression matches on large bodies of text) may be delayed for an arbitrary amount of time. Source: https://docs.python.org/2/library/signal.html How could I work around above constraint and get a stacktrace, even if the interpreter is in some C code for several seconds? Related: https://github.com/23andMe/djdt-flamegraph/issues/5
tagged with: profiling
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85096765
possible better answer: http://stackoverflow.com/a/49036254
has answer: http://stackoverflow.com/a/49036254

http://stackoverflow.com/comment/85201117
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49097124
has text: In order to *create* a batch, the sequences must be padded to the common length
score: 0

http://stackoverflow.com/q/49110803
tagged with: python
has comment: http://stackoverflow.com/comment/85226659
tagged with: rdd
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85226768
has answer: http://stackoverflow.com/a/49112844
tagged with: pyspark
score: 0
has title: pyspark - Grouping and calculating data
answer count: 2
has answer: http://stackoverflow.com/a/49113823
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/49113823
has body: I have the following csv file. Index,Arrival_Time,Creation_Time,x,y,z,User,Model,Device,gt 0,1424696633908,1424696631913248572,-5.958191,0.6880646,8.135345,a,nexus4,nexus4_1,stand 1,1424696633909,1424696631918283972,-5.95224,0.6702118,8.136536,a,nexus4,nexus4_1,stand 2,1424696633918,1424696631923288855,-5.9950867,0.6535491999999999,8.204376,a,nexus4,nexus4_1,stand 3,1424696633919,1424696631928385290,-5.9427185,0.6761626999999999,8.128204,a,nexus4,nexus4_1,stand I have to create a RDD where USER MODEL AND GT are PRIMARY KEY, I don't know if I have to do it using them as a tuple. Then when I have the primary key field I have to calculate AVG, MAX and MIN from 'x','y' and 'z'. Here is an output: User,Model,gt,media(x,y,z),desviacion(x,y,z),max(x,y,z),min(x,y,z) a, nexus4,stand,-3.0,0.7,8.2,2.8,0.14,0.0,-1.0,0.8,8.2,-5.0,0.6,8.2 Any idea about how to group them and for example get the media values from "x" With my current code I get the following. # Data loading lectura = sc.textFile("Phones_accelerometer.csv") datos = lectura.map(lambda x: ((x.split(",")[6], x.split(",")[7], x.split(",")[9]),(x.split(",")[3], x.split(",")[4], x.split(",")[5]))) sumCount = datos.combineByKey(lambda value: (value, 1), lambda x, value: (x[0] + value, x[1] + 1), lambda x, y: (x[0] + y[0], x[1] + y[1])) An example of my tuples: [(('a', 'nexus4', 'stand'), ('-5.958191', '0.6880646', '8.135345'))]
possible better answer: http://stackoverflow.com/a/49112844

http://stackoverflow.com/q/49057494
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49057960
tagged with: list
downvote count: 3
has comment: http://stackoverflow.com/comment/85120118
has title: Python 3.6 - find core pattern in two list
type: Question
upvote count: 0
score: -3
has body: I am searching for an efficient way to find core patterns in two different lists, I'll explain: List 1: [10318, 6032,1518, 4061, 4380, 73160, 83607, 9202, 28812, 40359, 28457, 3292, 2678, 8492, 7149, 19417, 7372, 8534, 3889, 11123, 8415, 5989] List 2: [5760, 1541, 2085, 637,1518, 4061, 4380, 73160, 83607, 9202, 28812, 40359, 28457, 3292, 2678, 8492, 7149, 19417, 7372, 8534, 3889, 11123] The two lists could have more than 300 elements, the similar elements in each list is statisticaly very large each time (probably more than 60%) My goal, find the point where the "core" start in each list. A new list come every 5 minutes and will be compared to the previous one. What I am interested in is the part that is not the core. In other word I need to retrieve the start of the list up until the core (that was identified) of the previous list. Efficiency is the key, new list each 5 minutes, but hundreds parallels processing. Any algo or math way or solution will help :) I hope I was precise in my request
has comment: http://stackoverflow.com/comment/85119637
answer count: 1
has comment: http://stackoverflow.com/comment/85120712
has comment: http://stackoverflow.com/comment/85119645
favorite count: 0
has comment: http://stackoverflow.com/comment/85120795
has comment: http://stackoverflow.com/comment/85119764

http://stackoverflow.com/comment/85230398
has text: I think you're assuming convexity here. you should take into account the direction from which you came, and always try going e.g. CCW from it. For example, your algorithm will fail in the point (0.5,-0.5) in the OP's example
comment on: http://stackoverflow.com/a/49112197
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85173986
has text: @Flika205 yes, y it's markup text, so I have more chars in y text, so array has another shape
comment on: http://stackoverflow.com/q/49083198
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85222044
type: Comment
type: QuestionComment
has text: Show your code and data sample.
score: 0
comment on: http://stackoverflow.com/q/49108541

http://stackoverflow.com/comment/85039802
type: QuestionComment
comment on: http://stackoverflow.com/q/49016530
score: 0
has text: Even after adding that line im still getting the same error. What else can cause this issue?
type: Comment

http://stackoverflow.com/comment/85186418
type: Comment
type: QuestionComment
has text: What are you using `go` for?
score: 0
comment on: http://stackoverflow.com/q/49090447

http://stackoverflow.com/q/49016228
tagged with: python
favorite count: 0
has body: I've got a dataframe here Row dist1 dist2 dist3 variable value Smallest Group 0 0 40 101 dist2 40 Smallest SmallestGroup 1 0 40 101 dist3 101 SecondSmallest SecondSmallestGroup 2 1 30 100 dist2 30 Smallest SmallestGroup 3 1 30 100 dist3 100 SecondSmallest SecondSmallestGroup 4 2 30 20 98 dist2 20 Smallest SmallestGroup 5 2 30 20 98 dist1 30 SecondSmallest SecondSmallestGroup 6 3 20 15 72 dist2 15 Smallest SmallestGroup 7 3 20 15 72 dist1 20 SecondSmallest SecondSmallestGroup 8 4 15 16 11 dist3 11 Smallest SmallestGroup 9 4 15 16 11 dist1 15 SecondSmallest SecondSmallestGroup I'd like to pivot the data so that I have four new columns: Smallest and SecondSmallest (which contains the values from the value column) and SmallestGroup and SecondSmallestGroup (which contains the valus from the variable column). My desired output is as follows: Row dist1 dist2 dist3 Smallest SecondSmallest SmallestGroup SecondSmallestGroup 0 NaN 40 101 40 101 dist2 dist3 1 NaN 30 100 30 100 dist2 dist3 I'm certain I can achieve this with a pivot, but am unsure about how to structure the command.
upvote count: 1
accepted answer: http://stackoverflow.com/a/49016757
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49017000
score: 1
has answer: http://stackoverflow.com/a/49017000
type: Question
answer count: 2
downvote count: 0
has title: Pivoting multiple columns with pandas
has answer: http://stackoverflow.com/a/49016757
tagged with: pandas

http://stackoverflow.com/q/49055570
tagged with: python
tagged with: django-templates
score: 0
has comment: http://stackoverflow.com/comment/85117353
tagged with: django
answer count: 1
has body: I'm trying to create a dynamic form which pre-populates the initial attribute of a certain field (title) when another field (checkin_type) is selected from a drop-down menu. I'm using Django's generic CreateView, and the way I'd like to go about it is by overriding the view's post() method such that if it receives an AJAX request (which is triggered by a jQuery .change() in the aforementioned drop-down menu and contains the id of the selection option), it updates the initial property of the form's title. Here is the view I've tried so far (in views.py): from django.views import generic from .models import CheckIn, CheckInType class CheckInCreate(generic.CreateView): model = CheckIn fields = '__all__' def post(self, request, *args, **kwargs): if request.is_ajax(): checkin_type = CheckInType.objects.get(pk=request.POST['id']) form = self.get_form() form['title'].initial = checkin_type.title self.object = CheckIn.objects.create(checkin_type=checkin_type) return self.render_to_response(self.get_context_data(form=form)) else: return super().post(request, *args, **kwargs) Here is how the AJAX request is made in the form's template, called templates/dashboard/checkin_form.html in accordance with Django's naming convention (dashboard is the name of the app): {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} Here are the corresponding models (in models.py): from django.db import models class CheckInType(models.Model): title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) def __str__(self): return self.title class CheckIn(models.Model): checkin_type = models.ForeignKey(CheckInType, null=True, on_delete=models.CASCADE) title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) notes = models.TextField(blank=True) # Scheduling requested_date = models.DateField(blank=True, null=True) completed_date = models.DateField(blank=True, null=True) The p…
has answer: http://stackoverflow.com/a/49056572
type: UnansweredQuestion
tagged with: django-forms
tagged with: django-generic-views
has comment: http://stackoverflow.com/comment/85117145
type: Question
has title: How to update a ModelForm's initial values dynamically?

http://stackoverflow.com/a/49054425
answers question: http://stackoverflow.com/q/49054275
has comment: http://stackoverflow.com/comment/85113663
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85113510
type: Answer
has body: One option is to change your last line to: c.execute("INSERT INTO books (title,text,tags) VALUES (?,?,?)", (col[0], col[1], col[2])) And then commit and close the connection if you're done making changes: conn.commit() conn.close()
score: 3
has comment: http://stackoverflow.com/comment/85113627
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49054275
has comment: http://stackoverflow.com/comment/85113799

http://stackoverflow.com/comment/85087144
type: Comment
has text: This works perfectly! Thank you for the explanation as well!
comment on: http://stackoverflow.com/a/49040681
type: AnswerComment
score: 0

http://stackoverflow.com/q/48970857
has title: Maximum limit on number of threads in python
downvote count: 0
has comment: http://stackoverflow.com/comment/84947093
has comment: http://stackoverflow.com/comment/84947089
has answer: http://stackoverflow.com/a/64406494
tagged with: python
has comment: http://stackoverflow.com/comment/84947323
answer count: 4
has answer: http://stackoverflow.com/a/76548103
favorite count: 0
linked to: http://stackoverflow.com/q/481970
has comment: http://stackoverflow.com/comment/121075002
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/84947088
upvote count: 24
has body: I am using Threading module in python. How to know how many max threads I can have on my system?
has answer: http://stackoverflow.com/a/77076003
score: 24
has comment: http://stackoverflow.com/comment/84947019
type: Question
has answer: http://stackoverflow.com/a/78665811
linked to: http://stackoverflow.com/q/344203

http://stackoverflow.com/a/49081578
has body: In [22]: x = [2, 3, 4, 1, 0, 8] In [23]: length = 8 In [24]: (np.arange(length) &lt; np.array(x).reshape(-1, 1)).astype(int) Out[24]: array([[1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]) Or, create an array of the various lengths of "bars": In [46]: k = np.arange(length + 1) In [47]: bars = (k[:-1] &lt; k.reshape(-1, 1)).astype(int) In [48]: bars Out[48]: array([[0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1]]) and use it as a lookup table: In [49]: bars[x] Out[49]: array([[1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]) In the above code, the preallocated array bars has shape (length+1, length). A more memory efficient representation of bars can be created using: In [61]: from numpy.lib.stride_tricks import as_strided In [62]: u = np.zeros(2*length, dtype=int) In [63]: u[length:] = 1 In [64]: bars = as_strided(u[length-1:], shape=(length+1, length), strides=(u.strides[0], -u.strides[0])) In [65]: bars Out[65]: array([[0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1]]) Then bars is a view of the one-dimensional array u, and it only uses 2*length integers.
has comment: http://stackoverflow.com/comment/85168649
has comment: http://stackoverflow.com/comment/85169592
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49080613
type: Answer

http://stackoverflow.com/q/49097886
has comment: http://stackoverflow.com/comment/85201340
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49098647
type: Question
has answer: http://stackoverflow.com/a/49098135
tagged with: nltk
downvote count: 0
possible better answer: http://stackoverflow.com/a/49098135
has body: I'm importing a csv file via Pandas, formatted as so: test = [ ('the beer was good.', 'pos'), ('I do not enjoy my job', 'neg'), ("I ain't feeling dandy today.", 'neg'), ("I feel amazing!", 'pos'), ('Gary is a friend of mine.', 'pos'), ("I can't believe I'm doing this.", 'neg') ] I want to check any words from a stop list are contained within the defined test set, and if so, remove them. However, when trying to do this, I simply get returned the full list without any alterations. Here's my current code: df = pd.read_csv('test.csv', delimiter=',') tlist = [tuple(x) for x in df.values] tlist = [(x.lower(), y.lower()) for x,y in tlist] def remove_stopwords(train_list): new_list = [] for word in train_list: if word not in stopwords.words('english'): new_list.append(word) print new_list remove_stopwords(tlist) I'm trying to use the stopwords provided by the NLTK corpus. Like I said, all that happens when I test this code with a print(new_list) is I get back the tlist set, as it was.
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49098647
score: 1
favorite count: 0
tagged with: tuples
has title: How to check if a word is contained in a tuple and if so, remove it
has comment: http://stackoverflow.com/comment/85200999
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85201095
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85200983
has answer: http://stackoverflow.com/a/49098094

http://stackoverflow.com/a/49105140
has body: This should help. inputNumber function is returning a single tuple of both your float. def addition(num): #---&gt;Update sum = num[0] + num[1] #---&gt;using index to get first and second number. print('The sum is ', sum) def subtraction(num): #---&gt;Update sub = num[0] - num[1] #---&gt;using index to get first and second number. print('The difference is ', sub) def inputNumber(): num1 = float(input('Enter the first number: ')) num2 = float(input('Enter the second number: ')) return num1,num2 #-----&gt; Returns a tuple. EX: (3.0, 4.0) print('Enter the corresponding number to perform the operation:\n') print('1 - addition') print('2 - subtraction') print('q - quit') while True: try: operation = input('Select operation &gt; ').lower() if operation == 'q': break elif operation == '1': addition(inputNumber()) elif operation == '2': subtraction(inputNumber()) else: print('Not valid. Try again.') except Exception, e: print('Invalid!', e)
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49105070
type: Answer
accepted answer of: http://stackoverflow.com/q/49105070
has comment: http://stackoverflow.com/comment/85218503

http://stackoverflow.com/a/49077626
accepted answer of: http://stackoverflow.com/q/49077150
type: Answer
answers question: http://stackoverflow.com/q/49077150
score: 2
upvote count: 2
has body: Basically, anything that is iterating over something that is generated dynamically, rather than iterating over a completed sequence. Consider a simple iterator that flips a coin, with a head worth 1 point and a tail worth 2 points. It continues to flip the coin until you reach 4 points. def coinflip(): s = 0 while s &lt; 4: x = random.choice([1,2]) s += x yield ("H" if x == 1 else "T") How long will the sequence be? It could be as short as 2: TT. It could be as long as 4: either HHHH or HHHT. However, in the majority of cases it will be 3: HHT, HTH, HTT, THT or THH. In this case, 3 would be the "safest" guess, but that could be higher or lower.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49022331
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49022081
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49022081
has body: Try this: data['D_DATE'] = pd.to_datetime(data['D_DATE']) Indexing a single column with double brackets (df'D_DATE') returns a DataFrame with one column named 'D_DATE'. Indexing with a single set of brackets (df['D_DATE']) returns a Series named 'D_DATE'. To create a new column in a DataFrame using the form df[new_col], use single brackets.

http://stackoverflow.com/q/49028157
has title: While loading yaml file in python code, is there a way to avoid duplicate keys?
has body: Is there a way to raise exception when step is given twice under build1 (look at file.yaml content). I am using f = yaml.load(open(file.yaml, 'r')) file.yaml content - build1: step: 'step1' time: '20s' step: 'step2' build2: step: 'step1'
tagged with: yaml
downvote count: 0
score: 1
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question

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

http://stackoverflow.com/a/48992413
has body: itertools.groupby can help: from io import StringIO from itertools import groupby text = '''# abcdefgh 1fnrnf mrkfr nfoiernfr nerfnr # something njndjen kj ejkndjke #vcrvr''' with StringIO(text) as file: lines = (line.strip() for line in file) # removing trailing '\n' for key, group in groupby(lines, key=lambda x: x[0]=='#'): if key is True: # found a line that starts with '#' print('found header: {}'.format(next(group))) if key is False: # group now contanins all lines that do not start with '#' print('\n'.join(group)) note that all of this is lazy. you'd only ever have all the items between two headers in memory. you'd have to replace the with StringIO(text) as file: with; with open('test234.txt', 'r') as file:... the output for your test is: found header: # abcdefgh 1fnrnf mrkfr nfoiernfr nerfnr found header: # something njndjen kj ejkndjke found header: #vcrvr UPDATE as i misunderstood. here is a fresh attempt: from io import StringIO from collections import deque from itertools import takewhile from_line = '# abcdefgh' to_line = '# something' with StringIO(text) as file: lines = (line.strip() for line in file) # removing trailing '\n' # fast-forward up to from_line deque(takewhile(lambda x: x != from_line, lines), maxlen=0) for line in takewhile(lambda x: x != to_line, lines): print(line) where i use itertools.takewhile to get an iterator over the lines until a contition is met (until the first header is found in your case). the deque part is just the consume pattern suggested in the itertools recipes. it just fast-forwards to the point where the given condition does not hold anymore.
has comment: http://stackoverflow.com/comment/84990347
has comment: http://stackoverflow.com/comment/84999740
has comment: http://stackoverflow.com/comment/85000044
has comment: http://stackoverflow.com/comment/84990215
type: Answer
has comment: http://stackoverflow.com/comment/84998482
has comment: http://stackoverflow.com/comment/84999229
has comment: http://stackoverflow.com/comment/84992501
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48992164
answers question: http://stackoverflow.com/q/48992164
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49106889
has answer: http://stackoverflow.com/a/49110032
accepted answer: http://stackoverflow.com/a/49110032
type: Question
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/49107016
answer count: 2
tagged with: pandas
has title: get the date format on a Matplotlib plot's x-axis
upvote count: 1
downvote count: 0
has body: I generate a plot using the following code: import numpy as np import pandas as pd import matplotlib.pyplot as plt index=pd.date_range('2018-01-01',periods=200) data=pd.Series(np.random.randn(200),index=index) plt.figure() plt.plot(data) Which gives me a plot, looking as follows: It looks like Matplotlib has decided to format the x-ticks as %Y-%m (source) I am looking for a way to retrieve this date format. A function like ax.get_xtickformat(), which would then return %Y-%m. Which is the smartest way to do this?
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49107016
has comment: http://stackoverflow.com/comment/85219190
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/125381725
score: 0
comment on: http://stackoverflow.com/q/49024029
type: QuestionComment
has text: Hi @Martin , any luck on this ? I am facing the same issue with neomodel . I am able to create the nodes with properties in bulk but not the relationships
type: Comment

http://stackoverflow.com/q/49047244
downvote count: 0
favorite count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49047324
tagged with: python
type: AnsweredQuestion
has title: Splitting and converting a string column in pandas
has answer: http://stackoverflow.com/a/49047324
type: Question
has body: I am processing outputs from a piece of software that provides co-ordinates as an x, y, z triple in a single column. Is there any way to split the string out into its three separate parts and convert to floats in one fell swoop? For example, I know that I can do the following: import pandas as pd df = pd.DataFrame({'ID': {0: 3864, 1: 3864, 2: 3864, 3: 3864, 4: 3864}, 'COORDFRONT': {0: '787.547 238.639 0.000', 1: '787.141 238.847 0.000', 2: '786.729 239.057 0.000', 3: '786.310 239.271 0.000', 4: '785.886 239.488 0.000'}, 'COORDREAR': {0: '803.545 230.467 0.000', 1: '803.139 230.675 0.000', 2: '802.727 230.885 0.000', 3: '802.309 231.099 0.000', 4: '801.884 231.316 0.000'}}) df['Front_x'], df['Front_y'], df['Front_z'] = df['COORDFRONT'].str.split(' ').str To separate out the three strings, but trying for example df['COORDFRONT'].str.split(' ').astype(float) returns a ValueError.
upvote count: 5
has answer: http://stackoverflow.com/a/49047277
accepted answer: http://stackoverflow.com/a/49047277
answer count: 2
score: 5

http://stackoverflow.com/a/49013012
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85046118
answers question: http://stackoverflow.com/q/49011791
has body: Try standardizing your output (or Y) variables and bringing them between 0 and 1.
has comment: http://stackoverflow.com/comment/85047167
has comment: http://stackoverflow.com/comment/85053123
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85039279

http://stackoverflow.com/q/49061270
answer count: 1
favorite count: 0
tagged with: python
upvote count: 2
type: UnansweredQuestion
has title: Python pandas dataframe why using double squared brackets
has body: Why does print(data["column"].shape) print (1819,) whereas print(data"column".shape) prints (1819,1)
downvote count: 1
has answer: http://stackoverflow.com/a/49061300
type: Question
score: 1
tagged with: dataframe

http://stackoverflow.com/comment/85037434
has text: Great! Thank you, i will try `sqlalchemy`.
score: 0
comment on: http://stackoverflow.com/q/49015994
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49088619
has body: I have a simple server and a client script using python but I don't know what we are doing exactly with the codes. I would be grateful if you could elaborate the meaning and the function of the following lines: server.py import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = "127.0.0.1" port = 1234 s.bind((host,port)) So what do we do by socket object s.bind()? what do binding mean? s.listen(1) Now we listen for connection but what does the argument for listen mean? It is set to be maximum 5. What is the purpose of this number? c,address = s.accept() Now accept returns a socket object and a tuple which consists of host and port but what I don't understand is this. In client we only use the socket object we create but in server script why are using "c" object to do tasks for client? Why are we creating another socket object? what is the difference between this "c" and "s" objects?
has answer: http://stackoverflow.com/a/49088758
has title: Python Socket Programming Details
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: sockets
tagged with: python
type: Question

http://stackoverflow.com/a/49127123
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49114841
accepted answer of: http://stackoverflow.com/q/49114841
score: 1
upvote count: 1
has body: I don't know what you are trying to achieve here, but with the input data provided, you can get one's complement of event and then find cumulative sum over window of 5 rows preceding current row. Check this and let me know, &gt;&gt;&gt; df.show() +---+-----+ | id|event| +---+-----+ | 1| 0| | 1| 0| | 1| 0| | 1| 0| | 1| 0| | 1| 1| | 1| 1| | 1| 1| | 2| 1| | 2| 0| | 2| 0| | 2| 0| | 2| 0| | 2| 0| | 2| 1| +---+-----+ &gt;&gt;&gt; df = df.withColumn('r_event',F.when(df.event == 0,1).otherwise(0)) &gt;&gt;&gt; w = Window.partitionBy('id').orderBy('id').rowsBetween(-5,-1) &gt;&gt;&gt; df = df.withColumn('c_sum',F.sum('r_event').over(w)) &gt;&gt;&gt; df.show() +---+-----+-------+-----+ | id|event|r_event|c_sum| +---+-----+-------+-----+ | 1| 0| 1| null| | 1| 0| 1| 1| | 1| 0| 1| 2| | 1| 0| 1| 3| | 1| 0| 1| 4| | 1| 1| 0| 5| | 1| 1| 0| 4| | 1| 1| 0| 3| | 2| 1| 0| null| | 2| 0| 1| 0| | 2| 0| 1| 1| | 2| 0| 1| 2| | 2| 0| 1| 3| | 2| 0| 1| 4| | 2| 1| 0| 5| +---+-----+-------+-----+ &gt;&gt;&gt; df.where(df.c_sum == 5).select('id','event').show() +---+-----+ | id|event| +---+-----+ | 1| 1| | 2| 1| +---+-----+
has comment: http://stackoverflow.com/comment/85277132
type: AcceptedAnswer

http://stackoverflow.com/q/48997389
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/85000434
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/49333151
has title: How to send request for Non-English voice recognition to wit.ai
tagged with: python
favorite count: 0
has body: When I run my code, wit.ai try to recognize English words of "myspeech.wav" but that is Persian voice, How should I change my code? def RecognizeSpeech(AUDIO_FILENAME): audio = open('myspeech.wav','r') headers = {'authorization': 'Bearer ' + wit_access_token, 'Content-Type': 'audio/wav'} resp = requests.post(API_ENDPOINT, headers = headers, data = audio) data = json.loads(resp.content) text = data['_text'] return text
score: 2
tagged with: wit.ai
accepted answer: http://stackoverflow.com/a/49333151
downvote count: 1

http://stackoverflow.com/comment/85045447
type: Comment
comment on: http://stackoverflow.com/a/49019915
has text: That was exactly what I did but got the error. The above code does make sense but I am not sure whats wrong. res is a list of return from a function call. Is there any other way to find the type instead of using print(type)?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85195112
comment on: http://stackoverflow.com/q/49093821
has text: Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85244958
comment on: http://stackoverflow.com/q/49119628
type: QuestionComment
has text: You can use `strip` to remove whitespace including CR.
type: Comment
score: 0

http://stackoverflow.com/q/49071959
has answer: http://stackoverflow.com/a/49072608
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49072608
has title: Getting a particular package from the pcap file using the Scapy module (python)
tagged with: offline
upvote count: 2
tagged with: packet
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: scapy
has body: Is there a way to load a particular package from the pcap file using Scapy? I know that I can load a specific number of packages using the' sniff' function and count attribute, e. g.' sniff(offline='file.pcap', prn=action, count=31) However, I need to get a 30th packet without loading the previous packets. In other words, I am not satisfied with such an example: packages = (pkt for pkt in sniff (offline=path, prn=action, count=31) print(packages[30]) The attempt to load a millionth of a package is too long.
type: Question

http://stackoverflow.com/q/49004503
type: Question
tagged with: dataframe
answer count: 2
has answer: http://stackoverflow.com/a/49011624
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49004648
downvote count: 0
has comment: http://stackoverflow.com/comment/85013763
favorite count: 0
possible better answer: http://stackoverflow.com/a/49011624
has body: I have a Python dictionary which contains list as values corresponding to the keys. Now each list contains two another dictionaries and the data looks like this: data = {'A': [{'Set1': {'Apple':1, 'Banana:2'}, 'Set2': {'Orange':1}], 'B': [{'Set1': {'Apple':3, 'Banana:1', Carrot:2}, 'Set2': {}], 'C': [{'Set1': {'Apple':1, 'Banana:2'}, 'Set2': {'Pineapple':5}]} I want to convert this data to a pandas DataFrame and the result should be like this: Set1 Set2 A {'Apple':1, 'Banana:2'} {'Orange':1} B {'Set1': {'Apple':3, 'Banana:1', Carrot:2} {} C {'Apple':1, 'Banana:2'} {'Pineapple':5} How can I achieve this? P.S: I tried pd.DataFrame(data) and pd.DataFrame.from_dict(data) but that didn't work.
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/49004648
has title: Converting a dictionary with values as list of dictionaries into pandas DataFrame

http://stackoverflow.com/a/49025163
has comment: http://stackoverflow.com/comment/122882680
accepted answer of: http://stackoverflow.com/q/49011150
upvote count: 1
answers question: http://stackoverflow.com/q/49011150
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has body: This blink_once() function will show the word TEXT for .5 secs and will hide it for .5 secs afterwards. So the effect is just a one time blink. I do it writing spaces in he same place as the text after a delay. It's easy to modify the delay or the text, or adding them as parameters if you need it for your specific project. The blink(number) calls blink_once() a determined number of times. So blink(3) will show the word "TEXT" blinking 3 times. import sys import time def blink_once(): sys.stdout.write('\rTEXT') time.sleep(0.5) b = ("Loading") sys.stdout.write('\r ') time.sleep(0.5) def blink(number): for x in range(0,number): blink_once() blink(3)

http://stackoverflow.com/comment/94385778
has text: Indeed it is not, but it was not the subject of the question. Replacing a paragraph is a different thing.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49048153
type: Comment

instantiation
type: Tag
tags question: http://stackoverflow.com/q/49100309
tag name: instantiation

http://stackoverflow.com/a/49087479
has comment: http://stackoverflow.com/comment/85413421
has comment: http://stackoverflow.com/comment/85246785
score: 0
has body: Rafael! With respect to your interpolation question, I can explain the math if you want to manually come up with an interpolation function, but there is an existing resource you might want to look into: scipy.interpolate.RegularGridInterpolator (see https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.RegularGridInterpolator.html) If I have misunderstood your issue, another interpolation method from the class might be appropriate: see, scipy.interpolate For plotting the 3d surface, https://matplotlib.org/examples/mplot3d/surface3d_demo.html might help guide you! Let me know if this helps! Just comment if you would like me to expand! Hopefully those are the resources you were looking for!
has comment: http://stackoverflow.com/comment/85180434
answers question: http://stackoverflow.com/q/49061894
has comment: http://stackoverflow.com/comment/85291878
has comment: http://stackoverflow.com/comment/85414039
has comment: http://stackoverflow.com/comment/85426079
has comment: http://stackoverflow.com/comment/85373484
has comment: http://stackoverflow.com/comment/85493672
type: Answer
has comment: http://stackoverflow.com/comment/85413162

computed-properties
type: Tag
tags question: http://stackoverflow.com/q/49032297
tag name: computed-properties

http://stackoverflow.com/comment/84950837
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48972231
score: 0
has text: It's either you missed the case of your models(it's case sensitive), your `music` is wrong, your migrations are messed up, since you it's not that easy to change auth user model if you already have db. And yes, code will help.

http://stackoverflow.com/a/48988907
answers question: http://stackoverflow.com/q/48988826
score: 0
has body: I think you need compare columns and chain conditions by | for OR: users['uses_name'] = (users['last_name'] == users['password'])| (users['first_name'] == users['password']) Or compare both columns with eq and get at least one True by any: users['uses_name'] = users'first_name', 'last_name'.eq(users['password'], axis=0).any(axis=1) print (users) user_name password first_name last_name uses_name 0 vance.jennings vance vance jennings True 1 bino.lapsi dflkjdk bino lapsi False
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84990321
has comment: http://stackoverflow.com/comment/84983019
type: Answer
has comment: http://stackoverflow.com/comment/84990390
accepted answer of: http://stackoverflow.com/q/48988826

http://stackoverflow.com/comment/84997190
score: 0
has text: @LeviLesches yes I did
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48995883

http://stackoverflow.com/comment/85057919
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49003860
type: AnswerComment
has text: Great! thanks! I will look into that

http://stackoverflow.com/q/48974703
has comment: http://stackoverflow.com/comment/84954366
type: Question
duplicate of: http://stackoverflow.com/q/15933741
tagged with: numpy
tagged with: try-catch
has comment: http://stackoverflow.com/comment/84954386
has comment: http://stackoverflow.com/comment/84954429
answer count: 1
has comment: http://stackoverflow.com/comment/84954443
has comment: http://stackoverflow.com/comment/84954472
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84954498
has title: Try/Except Not Catching Error
has body: I'm trying to use try/except to take care of a divide by zero error, but the except doesn't seem to be catching the error and I can't figure out why. import numpy as np A = np.array([[0.5,0,0.25,0.125,0.05],[0.5,0.5,0.5,0.5,0.5]]) Y = np.array([[0,1,0,1,1],[0,0,0,0,1]]) p = np.shape(A)[0] q = np.shape(A)[1] m = 2 try: dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A)) except Exception: dA = np.zeros((p,q)) It returns a divide by zero error and an invalid value encountered in multiply (because of the divide by zero error), but it kills the program instead of doing what's in except. RuntimeWarning: divide by zero encountered in true_divide dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A)) RuntimeWarning: invalid value encountered in multiply dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A)) I tried specifying the error instead of just Exception, but that doesn't work either. What else could be the problem?
favorite count: 0
type: UnansweredQuestion
tagged with: error-handling
has comment: http://stackoverflow.com/comment/84954365
upvote count: 1
has comment: http://stackoverflow.com/comment/84954375
downvote count: 1
has answer: http://stackoverflow.com/a/48974909
has comment: http://stackoverflow.com/comment/84954407
linked to: http://stackoverflow.com/q/15933741

http://stackoverflow.com/comment/85242755
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49116926
has text: is the solution to change the python path on the box itself to version 3?
score: 0

http://stackoverflow.com/comment/84968895
type: AnswerComment
has text: for your first question you can read the file and get the length of the first line which is schema ( i guess its never broken in the middle with line delimiter as other lines) and use that length instead of 8
type: Comment
comment on: http://stackoverflow.com/a/48971522
score: 1

http://stackoverflow.com/q/48988232
tagged with: macos
tagged with: sudo
score: 4
tagged with: pip
answer count: 1
has comment: http://stackoverflow.com/comment/84981748
upvote count: 4
has answer: http://stackoverflow.com/a/48989475
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84985428
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48989475
has comment: http://stackoverflow.com/comment/84985398
type: Question
has title: Failed to upgrade pip3 on Mac with Homebrew Python
tagged with: python
has body: I failed at upgrading pip3 on mac and get confusing (for me) answers in the terminal: &gt; which python /usr/bin/python &gt; pip -V pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7) &gt; which python3 /usr/local/bin/python3 &gt; python3 -V Python 3.6.4 &gt; pip3 -V pip 7.1.0 from /usr/local/lib/python3.6/site-packages (python 3.6) &gt; sudo -H pip3 install --upgrade pip You are using pip version 7.1.0, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Requirement already up-to-date: pip in /usr/local/lib/python3.6/site-packages &gt; sudo -H pip3 install --upgrade pip3 Could not find a version that satisfies the requirement pip3 (from versions: ) No matching distribution found for pip3 Why can't I have pip3 upgraded to 9.0? Solution was to force reinstall: sudo -H pip3 install --upgrade pip --force-reinstall

http://stackoverflow.com/comment/85248517
type: AnswerComment
comment on: http://stackoverflow.com/a/49120201
type: Comment
has text: Shouldn't the rows with duplicate 'testtime' and 'responsetime' drop from the dataframe?
score: 0

http://stackoverflow.com/q/49057999
answer count: 1
tagged with: matplotlib-basemap
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49063515
score: 0
type: Question
has body: I got another problem with my Matplotlib Basemap code, circle on the edge of the map (coord: 180, 0) behave like this is the end, but this is just the end of projection. Anyone have the idea how to fix this? Here the image of issue import numpy as np import matplotlib.pyplot as plt def plot_mwd(RA,Dec,org=0,title='Mollweide projection', projection='aitoff'): x = np.remainder(RA+360-org,360) # shift RA values ind = x&gt;180 x[ind] -=360 # scale conversion to [-180, 180] x=-x # reverse the scale: East to the left tick_labels = np.array([150, 120, 90, 60, 30, 0, 330, 300, 270, 240, 210]) tick_labels = np.remainder(tick_labels+360+org,360) fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot(111, projection=projection, axisbg ='LightCyan') ax.scatter(np.radians(x),np.radians(Dec), s = 15, c = 'k', marker = '.') # convert degrees to radians ax.set_xticklabels(tick_labels) # we add the scale on the x axis ax.set_title(title) ax.title.set_fontsize(15) ax.xaxis.label.set_fontsize(12) ax.yaxis.label.set_fontsize(12) ax.grid(color='tab:gray', linestyle='-', linewidth=0.2) phi = np.linspace(0, 2.*np.pi, 72) #72 points r = np.radians(30) x = np.radians(180) + r*np.cos(phi) y = np.radians(0) + r*np.sin(phi) ax.plot(x, y, color="r", linewidth = '0.7') fig = plt.gcf() ax = fig.gca() coord = np.array([(180, 0)]) plot_mwd(coord[:,0],coord[:,1], org=0, title ='Galactic Coordinate System', projection = 'aitoff') plt.show()
tagged with: matplotlib
has title: Matplotlib circles on the Basemap don't transit to the other half of sphere

http://stackoverflow.com/comment/84958804
type: QuestionComment
has text: Lets stepback and ask **why speeding up the imports**. You can try rearraging imports at the start and see if that works for you. And remember **KISS**.
comment on: http://stackoverflow.com/q/48974903
score: 0
type: Comment

http://stackoverflow.com/a/54400714
answers question: http://stackoverflow.com/q/49058931
downvote count: 0
has comment: http://stackoverflow.com/comment/131541621
has body: class DemoSerializer(serializers.ModelSerializer): def __init__(self, instance=None, data=empty, **kwargs): if instance: setattr(self.Meta, 'depth', 1) else: setattr(self.Meta, 'depth', 0) super(DemoSerializer, self).__init__(instance, data, **kwargs) class Meta: model = Demo fields = '__all__' depth = 0
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/95612208
upvote count: 3

http://stackoverflow.com/a/49117047
has comment: http://stackoverflow.com/comment/85410495
score: 2
has comment: http://stackoverflow.com/comment/85539017
has comment: http://stackoverflow.com/comment/85410162
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49116389
has comment: http://stackoverflow.com/comment/85483802
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49116389
has body: Question 1 You are getting 36 integers instead of 108 because your original image had 3 channels (red, green, blue, a.k.a RGB). When you convert it to grayscale, you are flattening it to only one channel. 108 / 3 = 36, seems legit! Quesion 2 Converting it by hand: There are multiple ways to convert an RGB image to grayscale, but the most straightforward would be to take the average of the three channels, basically (red_values + green_values + blue values) / 3. So take your original image array, and run: gray_image = (image[:,:,0] + image[:,:,1] + image[:,:,2]) / 3 The above is assuming that your image array is in the form image.shape = (pixel_height, pixel_width, number_of_channels), and that the first 3 channels represent your R,G, and B channels but that's pretty standard
type: Answer

http://stackoverflow.com/q/49064463
has comment: http://stackoverflow.com/comment/85163212
tagged with: border
tagged with: pyqt
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has body: I am working about python script and I use PyQt4. When I try spanning with function setSpan(row, col, rowSpanWidth, colSpanWidth) and apply on cell with "author". I am getting this result, borderline cleared and I do not know why. Spanning works fine on cells inside table or another (right) side/edge. Left side is not right. final table Could anyone give me please a tip what I should do to span good or advice for that? Code: self.table = QTableWidget() self.table.setRowCount(7) self.table.setColumnCount(2) self.table.verticalHeader().setVisible(False) self.table.horizontalHeader().setVisible(False) # add data into table for indexRow, row in enumerate(tableDict): for indexCol, col in enumerate(tableDict[indexRow]): self.table.setItem(indexRow, indexCol, QTableWidgetItem(tableDict[indexRow][indexCol])) self.table.setSpan(3, 0, 2, 1) # table is readable only self.table.setStyleSheet("border:0px;") self.table.setFocusPolicy(Qt.NoFocus) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.table.setSelectionMode(QAbstractItemView.NoSelection) self.table.setShowGrid(True) self.table.resizeColumnsToContents()`
answer count: 1
has comment: http://stackoverflow.com/comment/85158863
has title: How fix empty border line after spanning cells in table?
favorite count: 0
has comment: http://stackoverflow.com/comment/85136262
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85149029
score: 1
type: Question
has answer: http://stackoverflow.com/a/49081365
accepted answer: http://stackoverflow.com/a/49081365

http://stackoverflow.com/a/49176329
has body: Use this link https://www.rabbitmq.com/install-windows-manual.html to register rabbitmq as a service in windows. after that try using rabbitmq as amqp://localhost:5672 in celery
type: Answer
answers question: http://stackoverflow.com/q/49114534
score: 0

http://stackoverflow.com/comment/85118316
comment on: http://stackoverflow.com/a/49056663
score: 0
has text: @Steve I would just use a for-loop... but reduce works.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/124829361
score: 0
type: Comment
has text: It seems like seeking to the end of the stream with `CAP_PROP_POS_AVI_RATIO` doesn't work all the time depending on the video type (e.g. doesn't work with QuickTime .mov files). I'd use this with caution.
comment on: http://stackoverflow.com/a/49048421
type: AnswerComment

http://stackoverflow.com/comment/85235377
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49114882
has text: Yes, that works. I am pretty new to python and wasn't aware of this. Thank you! :)

android
tags question: http://stackoverflow.com/q/49011180
tags question: http://stackoverflow.com/q/49047549
tags question: http://stackoverflow.com/q/49047674
tags question: http://stackoverflow.com/q/49044902
tags question: http://stackoverflow.com/q/49102550
tag name: android
type: Tag

http://stackoverflow.com/comment/85064133
score: 0
type: Comment
has text: column_one column_two column_three coloumn_four column_five column_six
type: AnswerComment
comment on: http://stackoverflow.com/a/49027081

http://stackoverflow.com/q/49090638
has body: I'd like to input certain value in a particular column. my data looks something like: LoanID Married ApplicantIncome CoapplicantIncome Credit_History LP00135 NaN 33460 16000 1.0 LP00234 Yes 55000 70000 1.0 LP00432 No 12000 0 0.0 (I also know the index no. corresponding to each row, in this case for the 1st row its 104) As we can see in the 1st line, the applicant is obviously married as there is an entry for coapplicant income. Is there a way I can directly impute "Yes" into in that column for that particular row using the Index no. or LoanID as these two are unique for each row? Thanks in advance.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49090673
downvote count: 0
tagged with: data-science
linked to: http://stackoverflow.com/q/49088259
tagged with: pandas
favorite count: 0
has title: Code for imputing values in a specific column using the particular rows Index number or unique ID?
accepted answer: http://stackoverflow.com/a/49090673
possible better answer: http://stackoverflow.com/a/49090658
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49090658
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85187088
tagged with: ipython

http://stackoverflow.com/comment/85211584
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49103217
has text: Duplicate of https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python
score: 0

http://stackoverflow.com/a/49079215
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has body: def function_generate(v, s1, s2): def f(): v[s1] += v[s2] return f class Operations: def __init__(self): self.a = 10 self.b = 20 self.c = 30 namespace = vars(self) self.add_operation_1 = function_generate(namespace, 'a', 'b') self.add_operation_2 = function_generate(namespace, 'a', 'c') instance = Operations() instance.add_operation_1() print(instance.a) # Should print 30 instance.add_operation_2() print(instance.a) # Should print 60
has comment: http://stackoverflow.com/comment/85164389
type: Answer
answers question: http://stackoverflow.com/q/49078780
has comment: http://stackoverflow.com/comment/85164993
accepted answer of: http://stackoverflow.com/q/49078780
has comment: http://stackoverflow.com/comment/85165427
score: 2

http://stackoverflow.com/comment/84983869
comment on: http://stackoverflow.com/a/48989179
type: AnswerComment
score: 0
type: Comment
has text: I was meddling with the code until I had some serious doubts about myself and tried other pictures and it seems only png images are showing. Maybe it's the css that is wrong or I might just have to convert all images to png. Thanks for the answer though!

http://stackoverflow.com/q/49053105
has comment: http://stackoverflow.com/comment/85112350
has comment: http://stackoverflow.com/comment/85113462
has title: Python : NameError: name 'StandardError' is not defined
has comment: http://stackoverflow.com/comment/85110891
has answer: http://stackoverflow.com/a/49053930
accepted answer: http://stackoverflow.com/a/49053930
upvote count: 2
has comment: http://stackoverflow.com/comment/85112399
has comment: http://stackoverflow.com/comment/85112169
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85112312
has comment: http://stackoverflow.com/comment/85111040
tagged with: python
has body: I'm currently developing a website with the SST - Web Test Framework (i'm very beginner) but I have a problem with python I used this Link: https://pypi.python.org/pypi/sst/0.2.2 I m using - Python 3.6.4 and SST - Web Test Framework- Latest Version: 0.2.4 My Code is: from sst.actions import * go_to('http://www.google.com/') Error is: C:\Python\scrapy-master\Projects&gt;python proxyhar.py Traceback (most recent call last): File "proxyhar.py", line 1, in &lt;module&gt; from sst.actions import * File "C:\Python\lib\site-packages\sst\actions.py", line 104, in &lt;module&gt; class EndTest(StandardError): NameError: name 'StandardError' is not defined Anyone suggest me how to resolve this. Thank you
tagged with: sst
type: AnsweredQuestion
score: 1
type: Question

http://stackoverflow.com/q/48980143
tagged with: python
has comment: http://stackoverflow.com/comment/84966392
tagged with: list
has comment: http://stackoverflow.com/comment/84965469
has answer: http://stackoverflow.com/a/48980335
upvote count: 1
has body: I've been struggling with this problem for a while and could use some help. I'm trying to append values to a list from a list of lists. I get a TypeError: float() argument must be a string or a number, not 'list'. I understand the that I'm trying to pass a list of lists to another list but I can't find a solution. I start off by reading two separate lists that are then combined to make a list of those lists. I use this list of lists to parse through and remove specific values using the is_number function. I originally had float(s) and then tried list(map(float(s))) but get the same error. I have also tried to alter a_data, b_data from being a list but my actual dataset is a df.values.tolist() so it will always be in list form. So instead of: a_data = [one_sample() for _ in range(1000)] My actual dataset is read: a_data = df'AB','AC','AD','AE'.values.tolist() So the input will always be in list from. The rest of the code is the same. An example dataset is derived from: import random from functools import partial one_sample = partial(random.sample, range(80), 20) a_data = [one_sample() for _ in range(1000)] #Makes a list b_data = [one_sample() for _ in range(1000)] #Makes another list data = [a_data,b_data] #Combine those lists to from one The actual final list of lists that I'm working with looks like this: data = [[45.10031842, 'nan', -3.5165602060000003, 41.79799446, -24.616148100000004, -22.98303729, 'nan', 3.51273869, 28.44337707, 11.06472095, -35.54419066, 'nan', 45.73116662, 29.26475119, -40.68655635, 6.110571001, 'nan', -45.11483157, 3.001018117, -1.052283362, 38.61536724], [65.74835477, 'nan', 73.73594438, 61.90991549, 67.06663915, 77.13941436, 'nan', 93.94853726, 56.51826591, 70.20955909999999, 73.07962202, 'nan', 69.78626105, 73.34402753, 64.72901307, 70.90387539, 'nan', 70.94140139, 42.78164288, 61.77394225, 72.07455255], [45.15534694, 'nan', -3.3464740539999998, 41.78674915, -24.58808435, -23.02517617, 'nan', 3.5287456269999997, 28.38370261, 10.998834…
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48980346
has title: TypeError: float() argument must be a string or a number, not 'list' when using list of lists
score: 0
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/48980409
type: UnansweredQuestion

http://stackoverflow.com/comment/85042997
type: Comment
type: QuestionComment
has text: Execuse me! It was my fault. I fixed it in my request. I changed code and link to documentation site. Check my question again, please...
comment on: http://stackoverflow.com/q/49016527
score: 0

http://stackoverflow.com/comment/85227180
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49110904
has text: If that code is copy-pasted, i should raise errors. `,sheet_name='sheet1)` is missing the closing `'`
score: 0

http://stackoverflow.com/a/49062682
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49022363
type: Answer
score: 2
upvote count: 2
has body: Ok, I have found an answer. A possible culprit was the script was stuck in connecting/downloading from the URL. So what I added was a socket timeout to limit the time to connect and download the image. And now, the issue no longer bothers me. Here is my complete code ... import multiprocessing as mp import socket # Set the default timeout in seconds timeout = 20 socket.setdefaulttimeout(timeout) def getImages(val): #Dowload images try: url= # preprocess the url from the input val local= #Filename Generation From Global Varables And Rand Stuffs... urllib.request.urlretrieve(url,local) print("DONE - " + url) return 1 except Exception as e: print("CAN'T DOWNLOAD - " + url ) return 0 if __name__ == '__main__': files = "urls.txt" lst = list(open(files)) lst = [l.replace("\n", "") for l in lst] pool = mp.Pool(processes=4) res = pool.map(getImages, lst) print ("tempw") Hope this solution helps others who are facing the same issue
answers question: http://stackoverflow.com/q/49022363

http://stackoverflow.com/comment/85186981
comment on: http://stackoverflow.com/a/49090512
has text: @C1N14 `master` references the data of `in_dict`. Changes to master also change `in_dict`. Just try assigning something to `master` and then look at `in_dict`.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85174697
type: QuestionComment
has text: This is a basic statistics question and has nothing to do with the programming aspects of using `scikit-learn`. Please direct it to the proper Q&A site, in this case [Cross Validated](https://stats.stackexchange.com/).
score: 0
comment on: http://stackoverflow.com/q/49079122
type: Comment

http://stackoverflow.com/comment/85198688
score: 2
has text: Seems like you're testing the wrong thing.
comment on: http://stackoverflow.com/q/49096810
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48971481
has body: If you can use NumPy numerical types you could use np.int16 type conversion &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.int16(0x0024) 36 &gt;&gt;&gt; np.int16(0xcafe) -13570 &gt;&gt;&gt; np.int16(0xfffc) -4 &gt;&gt;&gt; np.uint16(0xfffc) 65532 &gt;&gt;&gt; np.uint16(0xcafe) 51966 Python Language specifies a unified representation for integer numbers, the numbers.Integral class, a subtype of numbers.Rational. In Python 3 there are no specific constraints on the range of this type. In Python 2 only the minimal range is specified, that is numbers.Integral should have at least the range of -2147483648 through 2147483647, that corresponds to the 32 bit representation. NumPy implementation is closer to the machine architecture. To implement numeric operations efficiently it provides fixed width datatypes, such as int8, int16, int32, and int64.
accepted answer of: http://stackoverflow.com/q/48971438
answers question: http://stackoverflow.com/q/48971438
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85163447
type: QuestionComment
has text: No, the annotation is not in a different coordinate system.
comment on: http://stackoverflow.com/q/49078309
score: 0
type: Comment

http://stackoverflow.com/q/49027866
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49028305
type: Question
has comment: http://stackoverflow.com/comment/85060055
has body: In a 2D matrix, how do I find the number of neighbours that have the value I'm searching for? Neighbours are defined as 8-connected (vertically, horizontally and diagonally) For instance, in the example below, for every element, X[i][j], in the matrix, I want to calculate how many of of it's neighbours have the value A Sample Input: matrix = [[A, B, A], [B, A, A], [B, A, B]] Sample Output: solution = [[1, 4, 2], [3, 4, 3], [2, 2, 3]] Eg. matrix[0][0] has 1 neighbours with the value A --> matrix[1][1] matrix[0][2] has 2 neighbours with the value A --> matrix[1][1] and matrix[1][2]
downvote count: 9
answer count: 2
has comment: http://stackoverflow.com/comment/85060329
has title: Number of Nearest 'True' in a matrix or list of list
score: -7
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/65228065
tagged with: python-3.x
tagged with: list

http://stackoverflow.com/a/48966343
answers question: http://stackoverflow.com/q/48966182
downvote count: 0
score: 1
type: Answer
has body: There is no hook or option you can set to turn on regular attribute handling for all magic methods. The only way you could do that is by overriding all of them to delegate to your desired handling individually, which has a few important limitations, one of which you caught: It needs to be updated every time a magic method is introduced. It's easy to miss a method. Whatever attribute lookup process you delegate to will probably pick up your delegator method. That needs careful handling. Your attempt failed because you tried to define __slots__ as an instance method. __slots__ is not supposed to be any sort of method at all, and definitely not an instance method; it needs to be a sequence, and it needs to be processed at class definition time to decide the layout of instances of your class. You also tried to write __new__ as if it was an instance method. Even if you hadn't made those mistakes, though, most of your methods would just end up in infinite recursive loops.
upvote count: 1

http://stackoverflow.com/q/48997218
has comment: http://stackoverflow.com/comment/85000359
score: 0
has answer: http://stackoverflow.com/a/48997495
tagged with: django
has body: I'm trying to list a group of deals by category I have a Deal model and a Category Model, where the Category is a Foreign Key of a Deal like so: class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = models.TextField(default='') category = models.ForeignKey(Category) The urlpattern for a category page looks like this: url(r'^category/(?P&lt;category&gt;\w+)/$', deals_by_category, name='category') and other urls look like this: url(r'^all/$', DealListView.as_view(), name='deals'), url(r'^(?P&lt;slug&gt;.*)/$', deal_by_detail, name='deal_detail'), url(r'^category/(?P&lt;category&gt;\w+)/$', deals_by_category, name='category'), url(r'^home/$', DealHome.as_view(), name='deal_home'), url(r'^test/$', Home.as_view(), name='deal_test'), url(r'^(?P&lt;pk&gt;[0-9]+)/like', like, name='like'), The view for this urlpattern is this: def deals_by_category(request,category): category_deals = Deal.objects.filter(category__name=category, ) return render(request, 'deals/category.html', {'category_deals': category_deals}) my other views look like this: class DealListView(generic.ListView): model = Deal context_object_name = 'deal_list' queryset = Deal.objects.all() template_name = 'deal_list.html' class DealHome(generic.TemplateView): model = Deal template_name = 'deals/test.html def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) def like(request, pk): if request.method == 'POST': deal = Deal.objects.get(pk=pk) deal.likes_total += 1 deal.save() return redirect('home') and then my category.html template is looping through these returned deals like this: {% for deal in category_deals %} &lt;h5 class="card-retailer"&gt;{{ deal.retailer}}&lt;/h5&gt; &lt;p class="card-title"&gt;{{ deal.title }}&lt;/p&gt; Now the issue arises if i click on predetermined category link like this: http://localhost:8000/deals/cate…
has comment: http://stackoverflow.com/comment/85000033
has comment: http://stackoverflow.com/comment/84999949
type: Question
linked to: http://stackoverflow.com/q/2143506
has comment: http://stackoverflow.com/comment/85000096
has comment: http://stackoverflow.com/comment/84999835
possible better answer: http://stackoverflow.com/a/48997358
has answer: http://stackoverflow.com/a/48997358
accepted answer: http://stackoverflow.com/a/48997495
answer count: 2
tagged with: python
has title: DoesNotExist --Matching Query Error
type: AnsweredQuestion

http://stackoverflow.com/a/48968011
score: 4
type: AcceptedAnswer
has body: You can use np.concatenate(): np.concatenate((data1, data2, data3, data4), axis=2)
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48967979
answers question: http://stackoverflow.com/q/48967979
downvote count: 0

http://stackoverflow.com/comment/122591426
has text: It doesn't work if home() raises an exception
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51013358
type: Comment

http://stackoverflow.com/comment/85044960
has text: like i don't know the background use but i can code for u a method that takes in x as input and would give u newList x as output
comment on: http://stackoverflow.com/q/49019876
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49036849
has comment: http://stackoverflow.com/comment/85079275
answer count: 0
score: 1
upvote count: 1
type: Question
has title: Python3 OpenCV Convert Raw YUYV422 from WebCam to RGB
tagged with: opencv
has comment: http://stackoverflow.com/comment/85079149
tagged with: v4l2
downvote count: 0
has comment: http://stackoverflow.com/comment/85080404
favorite count: 0
has body: I am trying to convert a RAW YUYY422 Frame of size 640x480 to RGB in Python3 OpenCV. I've looked in the OpenCV Docs and google various solution, but cannot seem to get it to work. The error I keep getting is a variant of: Before 614400 <class 'bytes'> After 614400 <class 'numpy.ndarray'> (614400,) Traceback (most recent call last): File "./capture.py", line 111, in <module> cv2.cvtColor(dataBuffer, dataBuffer, cv2.COLOR_YUV2RGB_UYVY); TypeError: only size-1 arrays can be converted to Python scalars Here is the code that I am trying to convert with: buf = v4l2_buffer() buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE buf.memory = V4L2_MEMORY_MMAP fcntl.ioctl(vd, VIDIOC_DQBUF, buf) # get image from the driver queue mm = buffers[buf.index] dataBuffer = mm.read() print("Before",len(dataBuffer),type(dataBuffer)) dataBuffer = np.fromstring(dataBuffer, np.uint8) print("After",len(dataBuffer),type(dataBuffer)) #dataBuffer = dataBuffer.reshape( 640, 480 ) print(dataBuffer.shape) cv2.cvtColor(dataBuffer, dataBuffer, cv2.COLOR_YUV2RGB_UYVY); dbusClient.run(dataBuffer) mm.seek(0) fcntl.ioctl(vd, VIDIOC_QBUF, buf) # requeue the buffer How can I accomplish this conversion? UPDATE: Per comment: for _ in range(50): # capture 50 frames buf = v4l2_buffer() buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE buf.memory = V4L2_MEMORY_MMAP fcntl.ioctl(vd, VIDIOC_DQBUF, buf) # get image from the driver queue mm = buffers[buf.index] dataBuffer = mm.read() dataBuffer = np.fromstring(dataBuffer, dtype=np.uint8) dataBuffer2 = cv2.cvtColor(dataBuffer, cv2.COLOR_BGR2YUV) dbusClient.run(dataBuffer) mm.seek(0) fcntl.ioctl(vd, VIDIOC_QBUF, buf) # requeue the buffer Gives Error: OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /io/opencv/modules/imgproc/src/color.cpp, line 11144 Traceback (most recent call last): File "./capture.py", line 106, in <module> dataBuffer2 = cv2.cvtColor(dataBuffer, cv2.COLOR_BGR2YUV) cv2.error: /io/opencv/modules/imgproc/src/color.cpp:11144: error: (-215) scn == 3 || s…
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85079995
tagged with: python

http://stackoverflow.com/q/49061575
has answer: http://stackoverflow.com/a/49064512
accepted answer: http://stackoverflow.com/a/49064512
type: Question
tagged with: python
upvote count: 14
has body: I am using stratified 10-fold cross validation to find model that predicts y (binary outcome) from X (X has 34 labels) with the highest auc. I set the GridSearchCV: log_reg = LogisticRegression() parameter_grid = {'penalty' : ["l1", "l2"],'C': np.arange(0.1, 3, 0.1),} cross_validation = StratifiedKFold(n_splits=10,shuffle=True,random_state=100) grid_search = GridSearchCV(log_reg, param_grid = parameter_grid,scoring='roc_auc', cv = cross_validation) And then do the cross-validation: grid_search.fit(X, y) y_pr=grid_search.predict(X) I do not understand the following: why grid_search.score(X,y) and roc_auc_score(y, y_pr) give different results (the former is 0.74 and the latter is 0.63)? Why do not these commands do the same thing in my case?
answer count: 1
tagged with: auc
has comment: http://stackoverflow.com/comment/85128991
tagged with: cross-validation
score: 14
type: AnsweredQuestion
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: Why when I use GridSearchCV with roc_auc scoring, the score is different for grid_search.score(X,y) and roc_auc_score(y, y_predict)?

http://stackoverflow.com/q/49053865
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/49053998
duplicate of: http://stackoverflow.com/q/14908789
type: Question
duplicate of: http://stackoverflow.com/q/2535760
has body: I'm currently developing a website with the SST - Web Test Framework (i'm very beginner) but I have a problem with python I used this Link: https://pypi.python.org/pypi/sst/0.2.2 I m using - Python 3.6.4 and SST - Web Test Framework- Latest Version: 0.2.4 My Code is: from sst.actions import * go_to('http://www.google.com/') Error is: C:\Python\scrapy-master\Projects&gt;python proxyhar.py Traceback (most recent call last): File "proxyhar.py", line 1, in &lt;module&gt; from sst.actions import * File "C:\Python\lib\site-packages\sst\actions.py", line 274, in &lt;module&gt; except OSError, e: ^ SyntaxError: invalid syntax Anyone suggest me how to resolve this. Thank you
score: -1
answer count: 1
favorite count: 0
has title: Python : except OSError, e:
tagged with: python
tagged with: sst
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49053998
has comment: http://stackoverflow.com/comment/85112476

http://stackoverflow.com/q/49094318
favorite count: 0
linked to: http://stackoverflow.com/q/23901168
type: UnansweredQuestion
score: -3
tagged with: python
upvote count: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/49094370
type: Question
has body: I am new in python and I am using python 3.5 version. I want to add photo to python, and here's the code I wrote: from tkinter import * win=Tk() win.title("Python Image") canvas=Canvas(win,width=500,height=500) canvas.pack() my_image=PhotoImage(file="C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg") canvas.create_image(0,0,anchor=NW,image=my_image) win.mainloop() But when I run it, the following error occurred: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; ================ RESTART: C:\Users\LABE-2\Desktop\rakibul.py ================ Traceback (most recent call last): File "C:\Users\LABE-2\Desktop\rakibul.py", line 8, in &lt;module&gt; my_image=PhotoImage(file="C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg") File "C:\Users\LABE-2\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3539, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\LABE-2\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3495, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize data in image file "C:\Users\Public\Pictures\Sample Pictures\Desert.jpg" &gt;&gt;&gt;
has title: an error occured to add picture in python
tagged with: python-imaging-library
tagged with: python-3.5
downvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/85194097

http://stackoverflow.com/comment/84986798
has text: @Ev.Kounis yes, but in some cases it could dwarf the measurements.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48990886

http://stackoverflow.com/comment/85016216
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49005803
has text: Try constructing a lookup dict that uses lines in A as key and line numbers as value. The lookups should become `O(log(#line))` instead of `O(filesize)`. Not too sure though, so comment instead of answer.

http://stackoverflow.com/comment/85221652
type: QuestionComment
has text: opps , that's what i mean actually saved objects(database objects) instance objects , also saved objects are not file's , but just text content's and url's again not files... and dude i think heroku provides configured and activated PostgreSQL addon my default even for free user's already
comment on: http://stackoverflow.com/q/49108331
score: 0
type: Comment

http://stackoverflow.com/a/49055327
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49055208
accepted answer of: http://stackoverflow.com/q/49055208
type: Answer
has body: Using itertools you can do this: from itertools import product list(map(''.join, product('0123456789', repeat=2))) # ['00', '01', '02', '03', '04', '05', '06', '07', ...]
has comment: http://stackoverflow.com/comment/85115438
upvote count: 3

mongodb-query
tags question: http://stackoverflow.com/q/49030147
tag name: mongodb-query
type: Tag

http://stackoverflow.com/comment/85081782
type: Comment
has text: as a `bash` script this will be very long, fragile and pointless. If you already have `awk` why not use it. Add a redirection `> outputfile` at the end to send the output to a file instead of stdout.
comment on: http://stackoverflow.com/a/49037227
score: 0
type: AnswerComment

http://stackoverflow.com/a/49064351
has comment: http://stackoverflow.com/comment/85169905
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85169613
answers question: http://stackoverflow.com/q/49062103
has comment: http://stackoverflow.com/comment/85256046
accepted answer of: http://stackoverflow.com/q/49062103
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85249402
has comment: http://stackoverflow.com/comment/85165794
type: Answer
has body: You cannot just mix asyncio-aware code, such as discord, with synchronous websockets code. Since nothing is awaited in init_bot, calling await init_bot() completely stops the event loop. Instead, you need to run the websocket code (init_bot function in your case) in a separate thread and await an appropriate event. For example: def init_bot(loop, w): def on_message(ws, message): w.data = message['data'] loop.call_soon_threadsafe(w.event.set) # ... async def start(): # ... loop = asyncio.get_event_loop() w = Wrapper() w.event = asyncio.Event() threading.Thread(target=lambda: init_bot(loop, w)).start() # ... # instead of while Wrapper.data is None ... await w.event.wait() # ... process data w.event.clear()

http://stackoverflow.com/a/49540815
upvote count: 2
has body: I used a lambda function to pull the "clean" name from the newly created column. Try this: df2['emp3'] = df2['emp2'].apply(lambda x: x.clean_name())
accepted answer of: http://stackoverflow.com/q/49013228
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49013228
type: Answer
score: 2

http://stackoverflow.com/a/49016554
upvote count: 2
answers question: http://stackoverflow.com/q/49015547
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49015547
type: Answer
score: 2
has body: First, to clarify, the entity ancestry is not mandatory for establishing relationships (and it has some disadvantages), see Can you help me understand the nbd Key Class Documentation or rather ancestor relationship?. and related Ancestor relation in datastore You'll need to consider Balancing Strong and Eventual Consistency with Google Cloud Datastore. The rest of the answer assumes no entity ancestry is used. To associate a product to a category (or several of them, if you want, using repeated properties) you can have: class Product(ndb.Model): name = ndb.StringProperty() category = ndb.KeyProperty(kind='Category', repeated=True) category = ndb.Key("Category", "Books") new_product = Product(title="Coding Horrors Book", category=[category]).put() This approach has a scalability issue: if a product falls into many categories, updating the category list becomes increasingly slower (the entire entity, progressively growing, needs to be re-written every time) and, if the property is indexed, it is sensitive to the exploding indexes problem. This can be avoided by storing product-category relationships as separate entities: class ProductCategory(ndb.Model): product = ndb.KeyProperty(kind='Product') category = ndb.KeyProperty(kind='Category') Scales a lot better, but in this case you'll need a ProductCategory query to determine the keys of related category entities for a product, followed by key lookups to get the details of those categories, something along these lines: category_keys = ProductCategory.query(ProductCategory.product == product_key) \ .fetch(keys_only=True, limit=500) if category_keys: categories = ndb.get_multi(category_keys) logging.info('product %s categories: %s' \ % (product.title, ','.join([c.name for c in categories])))

http://stackoverflow.com/q/49054841
linked to: http://stackoverflow.com/q/35118419
has title: Fitting "quadratic" surface to data points in 3D
tagged with: python-2.7
tagged with: 3d
accepted answer: http://stackoverflow.com/a/49056137
type: Question
type: AnsweredQuestion
tagged with: python
tagged with: data-fitting
score: 0
has comment: http://stackoverflow.com/comment/85114597
answer count: 1
has answer: http://stackoverflow.com/a/49056137
has body: I am trying to fit a quadratic plane to a cloud of data points in python. My plane function is of the form f(x,y,z) = a*x**2 + b*y**2 + c*x*y + d*x + e*y + f - z Currently, my data points do not have errors associated with them, however, some errors can be assumed if necessary. Following suggestions from here, I work out the vertical distance from a point p0=(x0,y0,z0) (which correspond to my data points) to a point on the plane p=(x,y,z) following this method. I then end up with def vertical_distance(params,p0): *** snip *** nominator = f + a*x**2 + b*y**2 + c*x*y - x0*(2*a*x-c*y-d) - y0*(2*b*y-c*x-e) + z0 denominator = sqrt((2*a*x+c*y+d)**2 + (2*b*y+c*x+e)**2 + (-1)**2) return nominator/denominator Ultimately, I think it is the vertical_distance function that I need to minimise. I can happily feed a list of starting parameters (params) and the array of data points to it in two dimensions, however, I am unsure on how to achieve this in 3D. ODR pack seems to only allow data containing x,y or two dimensions. Furthermore, how do I implement the points on the plane (p) into the minimising routine? I guess that during the fit operations the points vary according to the parameter optimisation and thus the exact equation of the plane at that very moment.
tagged with: math

http://stackoverflow.com/q/49061002
linked to: http://stackoverflow.com/q/21530577
type: Question
has comment: http://stackoverflow.com/comment/85127117
has comment: http://stackoverflow.com/comment/85126995
has comment: http://stackoverflow.com/comment/85127230
has comment: http://stackoverflow.com/comment/85127092
has comment: http://stackoverflow.com/comment/85127122
has answer: http://stackoverflow.com/a/49061191
score: 0
has body: I am now trying to run a program on a super computer on which I cannot run sudo or easy_install. The program needs pandas so I need to pip install pandas but I keep getting this error message even thought I have tried "pip install --upgrade pip" already. You are using pip version 8.1.2, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. --edit-- Here is the error message when I pip3 install pandas. pip3 install pandas Collecting pandas Using cached pandas-0.22.0.tar.gz Complete output from command python setup.py egg_info: Running from numpy source directory. /tmp/easy_install-gv5il123/numpy-1.14.1/setup.py:369: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates run_build = parse_setuppy_commands() /usr/lib64/python3.4/distutils/dist.py:260: UserWarning: Unknown distribution option: 'python_requires' warnings.warn(msg) /tmp/easy_install-gv5il123/numpy-1.14.1/numpy/distutils/system_info.py:624: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. self.calc_info() /usr/lib64/python3.4/distutils/dist.py:260: UserWarning: Unknown distribution option: 'python_requires' warnings.warn(msg) /usr/lib64/python3.4/distutils/dist.py:260: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) Traceback (most recent call last): File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 154, in save_modules yield saved File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 195, in setup_context yield File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 239, in run_setup DirectorySandbox(setup_dir).run(runner) File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 269, in run return func() File "/usr/lib/python3.4…
tagged with: pandas
has comment: http://stackoverflow.com/comment/85127118
answer count: 1
has comment: http://stackoverflow.com/comment/85127082
tagged with: pip
tagged with: python
accepted answer: http://stackoverflow.com/a/49061191
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85127064
has comment: http://stackoverflow.com/comment/85127201
has title: pip install pandas without upgrading pip
has comment: http://stackoverflow.com/comment/85127732

http://stackoverflow.com/a/49093188
has comment: http://stackoverflow.com/comment/85191611
downvote count: 0
answers question: http://stackoverflow.com/q/49093056
type: Answer
has body: This should help. # -*- coding: utf-8 -*- f1 = [ { "key": 1, "value": "NY" }, { "key": 1, "value": "CA" }, { "key": 1, "value": "MA" } ] f2 = [ { "key": 1, "value": "NJ" }, { "key": 1, "value": "CA" }, { "key": 1, "value": "TX" } ] check = [i["value"] for i in f1] #check list to see if the value already exist in f1. for i in f2: if i['value'] not in check: f1.append(i) print(f1) Output: [{'value': 'NY', 'key': 1}, {'value': 'CA', 'key': 1}, {'value': 'MA', 'key': 1}, {'value': 'NJ', 'key': 1}, {'value': 'TX', 'key': 1}]
score: 1
upvote count: 1

http://stackoverflow.com/a/49118683
answers question: http://stackoverflow.com/q/49117806
has comment: http://stackoverflow.com/comment/85243116
score: 0
has body: The syntax error can be solved as follows: test_1.py: import pytest @pytest.fixture(scope='session') def colors(): # Expensive operation return ['red', 'yellow', 'blue'] @pytest.mark.parametrize('color',colors()) def test_colors(color): assert color != 'mauve' def test_colors_list(colors): assert len(colors) == 3 However, running the previous code in pytest with the --setup-show option that shows the fixture setup and teardown details will show you the following: test_1.py::test_colors[red] SETUP F color[red] test_1.py::test_colors[red] (fixtures used: color)PASSED TEARDOWN F color[red] test_1.py::test_colors[yellow] SETUP F color[yellow] test_1.py::test_colors[yellow] (fixtures used: color)PASSED TEARDOWN F color[yellow] test_1.py::test_colors[blue] SETUP F color[blue] test_1.py::test_colors[blue] (fixtures used: color)PASSED TEARDOWN F color[blue] test_1.py::test_colors_list SETUP S colors test_1.py::test_colors_list (fixtures used: colors)PASSED TEARDOWN S colors As you can see in the output the color fixture is setup/teardown for each test case and the colors fixture is setup/teardown once more for the final test case. To avoid that you can refactor your code minimally as follows: test_1.py: @pytest.fixture(scope='session') def colors(): # Expensive operation return ['red', 'yellow', 'blue'] def test_colors(colors): for color in colors: assert color != 'mauve' def test_colors_list(colors): assert len(colors) == 3 Running again pytest with --setup-show will output the following: test_1.py::test_colors SETUP S colors test_1.py::test_colors (fixtures used: colors)PASSED test_1.py::test_colors_list test_1.py::test_colors_list (fixtures used: colors)PASSED TEARDOWN S colors where you can check that the fixture is only setup/teardown once for all tests. You can take a look a the relevant section in pytest docs
type: Answer

http://stackoverflow.com/comment/85168347
type: QuestionComment
has text: getaddressinfo failed generally means it cannot connect. are you behind some proxy?
score: 1
comment on: http://stackoverflow.com/q/49081444
type: Comment

http://stackoverflow.com/q/49118032
tagged with: python
has title: Flag column if row within a time period of a previous row
favorite count: 0
has body: I have a dataframe (300 million rows) that includes patient's initial hospital stays as well as any readmits for that patient. I need to identify the readmits. The dataframe is grouped by patient ids (Key) and sorted by Key then 'admit' date ascending. There are two conditions to identify a readmit: First condition - Num1 for the row being tested must be a value between 10-15. Second Condition - the admit date of the row must fall between the discharge and 90DayPostDischarge date of a previous row. The caveat to the second rule is that there could be multiple initial hospital stays for a patient. These initial stays would be identified by being separated by more than 90 days from the initial stay. An example of this situation is in the results for Key 10003: index 0 and 2 are both initial hospital stays. df = pd.DataFrame({'Key': ['10003', '10003', '10003', '10003', '10003','10034','10034', '10034'], 'Num1': [13,13,13,13,13,13,16,13], 'Num2': [121,122,122,124,125,126,127,128], 'admit': [20120506, 20120511, 20121010,20121015,20121020,20120510,20120516,20120520], 'discharge': [20120510, 20120515, 20121012,20121016,20121023,20120515,20120518,20120522]}) df['admit'] = pd.to_datetime(df['admit'], format='%Y%m%d') df['discharge'] = pd.to_datetime(df['discharge'], format='%Y%m%d') df['90DayPostDischarge'] = df['discharge'] + timedelta(days=90) df Initial df: Key Num1 Num2 admit discharge 90DayPostDischarge 0 10003 13 121 2012-05-06 2012-05-10 2012-08-08 1 10003 13 122 2012-05-11 2012-05-15 2012-08-13 2 10003 13 122 2012-10-10 2012-10-12 2013-01-10 3 10003 13 124 2012-10-15 2012-10-16 2013-01-14 4 10003 13 125 2012-10-20 2012-10-23 2013-01-21 5 10034 13 126 2012-05-10 2012-05-15 2012-08-13 6 10034 16 127 2012-05-16 2012-05-18 2012-08-16 7 10034 13 128 2012-05-20 2012-05-22 2012-08-20 Final Result: Key Num1 Num2 admit discharge 90DayPostDischarge Readmit 0 10003 13 121 2012-05-06 2012-05-10 2012-08-08 0 #the first row of every group will be false(0) as it cannot be compared …
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
tagged with: datetime

http://stackoverflow.com/a/49107679
type: Answer
has body: The second readline() is inside the for loop that iterates over the possible messages to be matched and so the code moves on to the next line before all messages have been checked. Try moving it to the outer scope: def checkLog(path, level, message): datafile = open(path) line_file = datafile.readline() while line_file != "": for text in message: if level + " " + text in line_file: return True line_file = datafile.readline() return False Your code could be better written like this: def checkLog(path, level, message): with open(path) as datafile: for line in datafile: for text in message: if (level + " " + text) in line: return True return False This avoids the calls to readline() instead iterating over the file object, which simplifies the code. Also it opens the file using a context manager (the with statement) which will ensure the the file is properly closed.
score: 2
has comment: http://stackoverflow.com/comment/85223878
accepted answer of: http://stackoverflow.com/q/49107512
answers question: http://stackoverflow.com/q/49107512
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/49096452
score: 0
has body: Django form field entries that fail validation raise ValidationError exception(s), so you could do something like (Django 2.0): try: if password_form.is_valid(): password_form.save() # etc... except ValidationError as e: messages.error(request, e)
type: Answer
answers question: http://stackoverflow.com/q/49093335

http://stackoverflow.com/comment/85072272
type: Comment
score: 1
has text: You cannot append to a file object. You mean `myFile.write(your_content)`. Also it would need to be indented under the `with`
comment on: http://stackoverflow.com/a/49033583
type: AnswerComment

http://stackoverflow.com/comment/85001439
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48997871
has text: Because it does not return you a list of values. It returns the iterator itself. Then you call `next(some_iterator)` on it to consume the next value, one by one. Until all values are consumed. Applying `list` to it will make it for all the values and returns you a list with all the iterator values. Or you can use a for loop

http://stackoverflow.com/comment/85098276
type: AnswerComment
has text: From your models,looks like one instance of Translation is linked to a single Product, and the same applies to the Variante model... But a Product can have more than one instances of Variante as well as Translation linked to it. Is that the desired scenario?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49046457

http://stackoverflow.com/comment/85242008
comment on: http://stackoverflow.com/a/49066556
has text: Thanks @forvas for the detailed answer. Strangely when I add store=True to the industry_id field, it allows me to sort the column, but there is no data. i.e. all the previous data is missing in the entire column. When I remove the attribute, the data returns.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49063881
has comment: http://stackoverflow.com/comment/130086904
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49063738
downvote count: 0
has body: It's really easy to perform this task by - For whole data frame - df[df &lt; 0] = -1 df[df &gt; 0] = 1 For specific column - df['column_name'][df['column_name'] &lt; 0] = -1 df['column_name'][df['column_name'] &gt; 0] = 1

http://stackoverflow.com/a/49039710
type: Answer
score: 2
has body: I would recommend you to use JWT, it much more safety than what rest_framework.authtoken is provided Such as a pair of token/refresh token to set for your main token small expiration time. That reduces the chance for the token to be stolen or corrupted. Also inside your JWT token, you can store payload which is very useful in many cases. There is a very good library for DRF which implements all aspects of using JWT with DRF and it's pretty flexible to adapt to your purposes. http://getblimp.github.io/django-rest-framework-jwt/ Could I use token authentication simply for user login, and session authentication for the other 3 APIs? Yes, you definitely can. Each instance of APIView has property 'authentication_classes' and you can set SessionAuthentication specifically for APIs you want. For example: class RecommendationQuestions(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, ) def post(self, request, format = 'json'): """Save the post data when logging in.""" uid = request.data['user_id'] resp_list = MovieSerializer.provide_movie_choices(uid) return Response(resp_list, status=status.HTTP_400_BAD_REQUEST) Or you can use both class RecommendationQuestions(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication) def post(self, request, format = 'json'): """Save the post data when logging in.""" uid = request.data['user_id'] resp_list = MovieSerializer.provide_movie_choices(uid) return Response(resp_list, status=status.HTTP_400_BAD_REQUEST)
downvote count: 0
answers question: http://stackoverflow.com/q/49037812
upvote count: 2

http://stackoverflow.com/a/49024378
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49023902
type: Answer
answers question: http://stackoverflow.com/q/49023902
downvote count: 0
score: 3
has body: You could use the following script to list disks in a resource group. from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient # Tenant ID for your Azure Subscription TENANT_ID = '' # Your Service Principal App ID CLIENT = '' # Your Service Principal Password KEY = '' credentials = ServicePrincipalCredentials( client_id = CLIENT, secret = KEY, tenant = TENANT_ID ) subscription_id = '' compute_client = ComputeManagementClient(credentials, subscription_id) rg = 'shuilinux' disks = compute_client.disks.list_by_resource_group(rg) for disk in disks: print disk
has comment: http://stackoverflow.com/comment/85073833
type: AcceptedAnswer

http://stackoverflow.com/comment/85087515
type: QuestionComment
score: 1
has text: Incidentally, 0xa5 is the yen sign ¥.
comment on: http://stackoverflow.com/q/49041038
type: Comment

http://stackoverflow.com/q/48969926
score: 0
tagged with: python
has body: Django 2.0.2 Python 3.6.3 Hi, I am still trying to learn Python by jumping head first into a django project. I have a "profile" model that extends the "user" model. I have a ModelForm for the profile. I have a create action that creates a new profile and saves it and the user info. That all works. I am trying to add the other CRUD actions and am starting with an "edit" method. I have read the "Creating forms from models" django doc. I see their idiom of (copied form the link above): &gt;&gt;&gt; class ArticleForm(ModelForm): ... class Meta: ... model = Article ... fields = ['pub_date', 'headline', 'content', 'reporter'] # Creating a form to add an article. &gt;&gt;&gt; form = ArticleForm() # Creating a form to change an existing article. &gt;&gt;&gt; article = Article.objects.get(pk=1) &gt;&gt;&gt; form = ArticleForm(instance=article) In my code I am trying: 1 def edit(request, pk): 2 try: 3 profile = Profile.objects.get(pk=pk) 4 5 if request.method == 'POST': 6 form = ProfileForm(request.POST, instance=profile) 7 else: 8 form = ProfileForm(instance=profile) 9 10 if form.is_valid(): 11 profile = form.save(commit=False) 12 profile.user = request.user 13 profile.save() 14 my_render = render(request, 'Members/index.html', { 15 'profile': profile 16 }) 17 else: 18 my_render = render(request, 'Members/profile.html', { 19 'profileEdit': form, 20 'profileState': "edit" 21 }) 22 except Profile.DoesNotExist: 23 raise Http404("No Profile matches the given query.") 24 25 return my_render So, in my debugger I can do an account creation. I can then click a button that triggers this edit action. Line #3: produces what appears to be (to my eye) a valid copy of the profile I want to edit. Line #8 is the next line executed. It produces a form object but it is not populated with the profile instance. Line #18 is next because the form is obviously not valid. the render generates missing value errors in the form. Am I missing a step in which the form is populated with model data?
tagged with: django
has answer: http://stackoverflow.com/a/48974628
has title: Django populate Form from Model
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48974628
type: Question
answer count: 1

http://stackoverflow.com/comment/122940761
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49060989
has text: The only difference I see between the two is that some values were `None` instead of being empty lists.

http://stackoverflow.com/comment/85127507
comment on: http://stackoverflow.com/q/49061180
type: Comment
type: QuestionComment
has text: *This train has no breaks!!*
score: 2

http://stackoverflow.com/comment/85048394
type: Comment
type: QuestionComment
score: 2
has text: cp950? That's an interesting default encoding. What's the *actual* encoding `somefile.py` is encoded in?
comment on: http://stackoverflow.com/q/49021589

http://stackoverflow.com/q/49094098
has answer: http://stackoverflow.com/a/49094199
upvote count: 1
possible better answer: http://stackoverflow.com/a/49094199
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/49094178
score: 1
has comment: http://stackoverflow.com/comment/85244702
has comment: http://stackoverflow.com/comment/85193475
type: Question
answer count: 2
has body: I am attempting to create a poker game, and I have a list of values which can be anything from Ace to King in a list (named "number"). In order to determine whether or not the player has a "Four of a Kind", the program needs to check if four items in the list of values are identical. I have no clue how to do this. Would you somehow use the number[0] == any in number function four times, or is it something completely different?
has comment: http://stackoverflow.com/comment/85193507
tagged with: arrays
downvote count: 0
tagged with: poker
favorite count: 0
accepted answer: http://stackoverflow.com/a/49094178
tagged with: python
has comment: http://stackoverflow.com/comment/85193496
has title: Python: How to find whether a specific number of items in a list are identical?

http://stackoverflow.com/comment/94998377
has text: I happened to just answered a related question asked by @Idlehands. See [here](https://stackoverflow.com/a/54081432/5722359). From what I learned there, I conclude that the `Frame` widget should raise an Exception for unrecognised colour name. Presently, the `Frame` widget background is yielding multiple snap shots of the `Tk` window window and its content in sometime cascade and random order. I think this occurrence should not be allowed to happen, i.e. a bug fix is needed.
type: Comment
comment on: http://stackoverflow.com/a/49020726
score: 0
type: AnswerComment

http://stackoverflow.com/a/49106497
downvote count: 0
has body: Sorry for the late response, I hope it is still useful for you. Depending on your application you may need to download a specific wordembedding file, for example here yoou have the Glove files EMBEDDING_FILE='glove.6B.50d.txt' embed_size = 50 # how big is each word vector max_features = 20000 # how many unique words to use (i.e num rows in embedding vector) maxlen = 100 # max number of words in a comment to use word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i &gt;= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector #this is how you load the weights in the embedding layer inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix])(inp) I took this code from Jeremy Howard, I think this is all you need, if you want to load other file the process is pretty similar, usually you just have to change the loading file
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49048758
answers question: http://stackoverflow.com/q/49048758
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49119044
has comment: http://stackoverflow.com/comment/85244650
tagged with: django-rest-framework
tagged with: django-rest-auth
has body: I am running in a issue of UPDATING the extended user profile in django-rest-auth library ( here is the library http://django-rest-auth.readthedocs.io/en/latest/introduction.html ) I extended the User with UserProfile: class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, related_name='userprofile') platformLanguage = models.TextField(null=True) mentorApprovalRequest = models.BooleanField(default=False) approvedAsMentor = models.BooleanField(default=False) fullName = models.TextField(null=True) dateOfBirth = models.DateField(null=True) placeOfBirth = models.TextField(null=True) bio = models.TextField(null=True) Basically I am creating the initial User which consists of (username, email, password), see the attached pic: Registration of User And then I am trying to update the information of the userProfile, see the pic for update: Userprofile Update And here we go, when I try to update it says, "Not found", but the user was registered. And then when I look at the email decoding instead of admin@gmail.com, I have the wrong email decoding admin%40gmail.com, I guess this might be the issue why I cannot update the details of the userprofile.
tagged with: python
has answer: http://stackoverflow.com/a/49119731
type: AnsweredQuestion
has title: django-rest-auth encoding email/username
type: Question
has comment: http://stackoverflow.com/comment/104828876
has comment: http://stackoverflow.com/comment/85243759
has comment: http://stackoverflow.com/comment/85244373
accepted answer: http://stackoverflow.com/a/49119731
score: 0
answer count: 1

http://stackoverflow.com/comment/85020996
has text: No problem. I don't know what you mean.
type: AnswerComment
comment on: http://stackoverflow.com/a/49007882
type: Comment
score: 0

http://stackoverflow.com/comment/85193391
score: 0
comment on: http://stackoverflow.com/q/49089934
type: Comment
type: QuestionComment
has text: it should add x to the list only if in there is not variable with value x already in list.. and it count how many iterations it need to find this value.

http://stackoverflow.com/comment/85223892
type: Comment
comment on: http://stackoverflow.com/a/49104344
score: 1
has text: @desertnaut Done. Thanks. I was using mostly because some tools dont make such difference known explicitly. I was also thinking of scenarios in which labels are encoded and then the user can calculate the accuracy although which dont apply to this case.
type: AnswerComment

http://stackoverflow.com/q/49032732
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85128512
has comment: http://stackoverflow.com/comment/85079618
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/85091803
tagged with: gmm
has comment: http://stackoverflow.com/comment/85076783
has comment: http://stackoverflow.com/comment/85071556
score: 0
has title: Python for testing of wav files using UBM
tagged with: covariance
has body: While using scipy.stats.multivariate_normal how can I use a diagonal covariance matrix of dimension 128 * 39 using python. I am implementing UBM and need some information about testing of a sound wav file given I have adapted parameters.
type: UnansweredQuestion

http://stackoverflow.com/a/49006794
has body: is checks for memory address. Immutable objects that are wrappers around C type tends to have same memory address, whereas others don't. The difference here is the bytes required to store the integers.
downvote count: 2
has comment: http://stackoverflow.com/comment/85018037
upvote count: 1
score: -1
answers question: http://stackoverflow.com/q/49006750
has comment: http://stackoverflow.com/comment/88847881
type: Answer
has comment: http://stackoverflow.com/comment/85018057

http://stackoverflow.com/comment/84966681
has text: I will rewrite my question to simplify things.
comment on: http://stackoverflow.com/q/48967987
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85090617
has text: @LouisSugy i edited the question, does it make more sense?
type: QuestionComment
comment on: http://stackoverflow.com/q/49042486
score: 0
type: Comment

http://stackoverflow.com/a/73100177
downvote count: 0
has body: You could try using pandas_udf instead of udf: # other imports from pyspark.sql.pandas.functions import pandas_udf # make sure arrow is actually used spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true") spark.conf.set("spark.sql.execution.arrow.pyspark.fallback.enabled", "false") def cos_sim2(vec: pd.Series) -> pd.Series: value_norm = np.linalg.norm(value) cs_value = vec.apply(lambda v: np.dot(value, v) / (np.linalg.norm(v) * value_norm)) return cs_value.replace(np.inf, np.nan) cos_sim_udf = pandas_udf(cos_sim2, FloatType())
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49019091
upvote count: 2

http://stackoverflow.com/q/49059681
tagged with: python
upvote count: 6
favorite count: 0
tagged with: user-input
type: UnansweredQuestion
score: 6
tagged with: recursion
has answer: http://stackoverflow.com/a/49059752
type: Question
has body: I currently have a bit of Python code that looks like this: for set_k in data: for tup_j in set_k: for tup_l in tup_j: The problem is, I'd like the number of nested for statements to differ based on user input. If I wanted to create a function which generated n number of for statements like those above, how might I go about doing that?
has title: How to create a function for recursively generating iterating functions
tagged with: for-loop
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85124487

http://stackoverflow.com/a/49049194
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49049193
answers question: http://stackoverflow.com/q/49049193
has body: I have fixed the problem, however still don't know the root cause. My solution was: 1) Install Redis windows build https://github.com/rgl/redis/downloads 2) Reboot PC 3) pip install pypiwin32 4) run project Even works after turning on all firewalls
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/comment/91151510
type: AnswerComment
score: 0
type: Comment
has text: Where'd k/v come from in convert_json?
comment on: http://stackoverflow.com/a/49085020

http://stackoverflow.com/comment/85199076
has text: `IndexError: tuple index out of range`
type: Comment
comment on: http://stackoverflow.com/a/49096878
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85211832
comment on: http://stackoverflow.com/q/49103333
score: 0
type: Comment
type: QuestionComment
has text: Update: I'm getting the impossibly low number of 8311680 on a better device. I'm sure my int has circled around at least once or the print function is having issues displaying the large number. Any way to avoid this?

http://stackoverflow.com/comment/85073929
has text: My solution seems to be about 4-5 times faster :) https://repl.it/repls/AliveTechnoGraph
type: Comment
score: 1
comment on: http://stackoverflow.com/a/49000891
type: AnswerComment

http://stackoverflow.com/comment/85238779
has text: Give a [**Minimal, Complete, Verifiable** Example](https://stackoverflow.com/help/how-to-ask) in your question.
comment on: http://stackoverflow.com/q/49116750
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85031919
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49007291
has text: Let me give you this analogy. Suppose I asked you to tell me what a bus is. You then tell me: "it has a number, depending on a number, it will take you to different places, you must be careful because the the same number goes in two opposite directions". This doesn't tell me what a bus is. It tells me what it does. The answer I'm looking for is "bus is a machine that uses a combustion engine to spin its wheels. friction than allows it to move". Second has an ability to explain why, if I hurl a bus into a pond, it won't go, first doesn't.
type: AnswerComment

http://stackoverflow.com/a/49076533
has comment: http://stackoverflow.com/comment/85159935
has body: def save_device_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form = form.save(commit=False) # &lt; use these 3 below lines for save data form.usr = request.user form.save() According to your device model that need usr also So you need to save usr as i did in my code
has comment: http://stackoverflow.com/comment/85159318
score: 0
has comment: http://stackoverflow.com/comment/85176260
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49076444
answers question: http://stackoverflow.com/q/49076444

http://stackoverflow.com/comment/84980918
score: 0
type: Comment
has text: hi ramesh, first of all, let me paste what i have right now so you see what i'm trying to do:
type: QuestionComment
comment on: http://stackoverflow.com/q/48986917

http://stackoverflow.com/comment/85078971
type: QuestionComment
comment on: http://stackoverflow.com/q/49036759
has text: @YotamSalmon In this case it doesn't really matter, because the file will never contain more than 10 lines of short usernames. It is perfectly okay to read them all into the memory. For longer lists, I'll keep the other solutions in mind! Thank you!
score: 0
type: Comment

http://stackoverflow.com/comment/85173893
comment on: http://stackoverflow.com/q/49084255
type: Comment
score: 1
type: QuestionComment
has text: What do you mean by "don't contain any character"? Does that mean letters and not numbers?

http://stackoverflow.com/comment/85219925
comment on: http://stackoverflow.com/q/49107183
type: Comment
type: QuestionComment
has text: I think it is the funny newfolder(2). rename it as something sensible.
score: 0

http://stackoverflow.com/comment/85003326
has text: Change `if forward and backward and down and up == -1:` to `if forward == backward == down == up == -1:`
comment on: http://stackoverflow.com/q/48998972
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/92972100
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49049003
type: Comment
has text: Thank you Richard for your post. Killed over 30 minutes till found this port, the conda install mkl=2017 informed me that some of the installed packages would be downgraded -> selected "y" -> now no more errors after selecting import theano. Yes!!

http://stackoverflow.com/a/48996102
answers question: http://stackoverflow.com/q/48996047
score: 0
type: Answer
has body: I don’t understand why you test an equality in the last statement. For me the easiest is the following: cond_str = 'negative' if user_val &lt; 0 else 'non-negative' You can chain an if statement with an assignation in Python to test which value you want to assign. This is called « ternary operator ».

http://stackoverflow.com/comment/84954259
comment on: http://stackoverflow.com/q/48966769
has text: `read_csv(sys.stdin)`... You're making every map task read the exact same file completely (or only processing one line of it) ... MapReduce won't speed up this code. Hadoop Streaming is supposed to read lines from stdin, and write to stdout, not entire files as input
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/49004773
score: 1
downvote count: 0
has body: I have accepted jezrael's answer. For sake of completeness, I am adding a couple of lines to remove the duplicates. # from jezrael's solution df1 = df.stack().rename_axis(('from','to')).reset_index(name='value') # drop the dupes df1.loc[:, ['from', 'to']] = df1.loc[:, ['from', 'to']].apply(sorted, axis=1) df1.drop_duplicates() # result - from to 0 A A 1 A B 2 A C 4 B B 5 B C 8 C C
type: Answer
answers question: http://stackoverflow.com/q/49004398
upvote count: 1

http://stackoverflow.com/q/49074599
tagged with: pandas
has body: I have a list that looks like this: hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)] And I am simply trying to write it to a csv file, looking like this: keyword 1 keyword 2 frequency case iphone 91524 adapter iphone 12233 battery smartphone 88884 I can't figure my way around it. I couldn't transform the list into a DataFrame, either. I tried to apply some code suggested here Writing a Python list of lists to a csv file without any success.
has comment: http://stackoverflow.com/comment/85155146
upvote count: 1
accepted answer: http://stackoverflow.com/a/49074723
has answer: http://stackoverflow.com/a/49074773
favorite count: 0
has answer: http://stackoverflow.com/a/49074716
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49074723
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/49074773
has title: Writing a nested list into CSV (Python)
type: Question
has answer: http://stackoverflow.com/a/49074684
linked to: http://stackoverflow.com/q/14037540
has comment: http://stackoverflow.com/comment/85155192

http://stackoverflow.com/q/49121178
linked to: http://stackoverflow.com/q/323972
has body: I have a process that spawns new threads and does work, when the threads are done I start a new batch of threads. I have an issue where a thread may do an RPC call that sometimes never returns. The RPC unfortunately does not support a timeout feature. I know we can use signals to help timeout a function but since this is multi-threaded I can't utilize that. Is there any recommended way to timeout a function that is called in a thread to a set interval?
score: 0
answer count: 1
has title: Python: Timing out a function that is called in a separate thread
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/49121562
tagged with: timeout
type: Question

http://stackoverflow.com/a/49082865
upvote count: 1
answers question: http://stackoverflow.com/q/49018833
downvote count: 0
has body: You can't run two instances of appJar, instead, you need to create subWindows: http://appjar.info/pythonSubWindows/ So, using your current code: from appJar import gui def press(btn): if btn == "Revision": app.showSubWindow("Revision page") app = gui("Menu", "500x200") app.setBg("green") app.setFont(18) app.addLabel("title1", "Menu") app.addButtons(["Revision", "Quiz", "Progress"], press) app.startSubWindow("Revision page", "500x200") app.setBg("green") app.setFont(18) app.addLabel("title2", "Please select a topic you would like to rveise") app.stopSubWindow() app.go() It's easier to visualise if you use contextManagers: from appJar import gui def press(btn): app.showSubWindow(btn + " page") with gui("Menu", "500x200") as app: app.setBg("green") app.setFont(18) app.addLabel("title1", "Menu") app.addButtons(["Revision", "Quiz", "Progress"], press) with app.subWindow("Revision page", size="500x200"): app.addLabel("revTitle", "Please select a topic you would like to rveise") with app.subWindow("Quiz page", size="500x200"): app.addLabel("quizTitle", "Quiz Page") with app.subWindow("Progress page", size="500x200"): app.addLabel("progTitle", "Check Progress") And, in the latest release, a lot of the properties can be set as parameters and there are new functions for adding widgets: from appJar import gui def press(btn): app.showSubWindow(btn + " page") with gui("Menu", "500x200", bg='green', font={'size':18}) as app: app.label("Menu") app.buttons(["Revision", "Quiz", "Progress"], press) with app.subWindow("Revision page", size="500x200", bg='red'): app.label("Please select a topic you would like to rveise") with app.subWindow("Quiz page", size="500x200", bg='blue'): app.label("Quiz Page") with app.subWindow("Progress page", size="500x200", bg='orange'): app.label("Check Progress")
type: Answer
score: 1

http://stackoverflow.com/comment/85187406
comment on: http://stackoverflow.com/q/49090847
has text: @LukeH. Put `numValues = len(newList)` at the top of `abo_bel_equ()`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85101019
comment on: http://stackoverflow.com/q/49044610
score: 0
type: Comment
type: QuestionComment
has text: With Chromedriver this is no problem. See the discussion here: https://github.com/mozilla/geckodriver/issues/1173

http://stackoverflow.com/q/49100222
linked to: http://stackoverflow.com/q/48988776
tagged with: python
tagged with: list
answer count: 0
duplicate of: http://stackoverflow.com/q/48988776
has title: Preserve nested list structure with itemgetter in Python
upvote count: 1
type: Question
score: 1
has body: As an example, suppose a = [[1, 2, 3], [2, 3, 4], [1, 2], [3, 5]], and inds is a list of indices of a whose entries I would like to extract. For instance, In [1]: from operator import itemgetter In [2]: itemgetter(*inds)(a) Out[2]: ([1, 2, 3], [2, 3, 4]) which works fine. However, if inds contains only one element, then the result is no longer a tuple of (sub-)lists: In [3]: itemgetter(*[0])(a) Out[3]: [1, 2, 3] Is there a way to make itemgetter still return the same format: ([1, 2, 3]) in this case? I need the output format to have the same level of depth for latter processing regardless of the number of elements it contains.
downvote count: 0
has comment: http://stackoverflow.com/comment/85205870
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/49002713
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49001370
answers question: http://stackoverflow.com/q/49001370
has comment: http://stackoverflow.com/comment/85010257
has body: Qt provides some of its own types for things like strings because Qt is a C++ library and apparently these things are hard in C++. When using PyQt, you have the option of either using Qt strings (QString) or Python native strings. Old versions of PyQt (PyQt4) use QString by default where as new versions (PyQt5) use Python strings. The best option in my opinion is to use native Python types, which allows you to easily integrate with other libraries that also expect native Python types without doing a whole bunch of annoying conversions. To do this, prior to importing PyQt (so put it at the top the python script you launch), add the following code: # do this BEFORE importing PyQt for the first time import sip for name in ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"]: sip.setapi(name, 2) # now you can import PyQt... This ensures that you use native Python types instead of the types listed above, and your error will vanish.
type: AcceptedAnswer

http://stackoverflow.com/a/49050095
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49049822
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49049822
type: Answer
score: 1
has body: This might help from xml.dom.minidom import parse dom = parse('C:\Users\qxn5622\Desktop\EF10018\DEFAULT.tbc') propertyList = dom.getElementsByTagName('PROPERTY') for prop in propertyList: if prop.getAttribute('name') == "PrjFile": myString = prop.getElementsByTagName("VALUE") print myString[0].firstChild.nodeValue Output: W:\_fdsw\Projects\HIL\releases\release_9_1_0\Config\CDNG\UX_EF_TSHIL\UX_EF_TSHIL.CDP

http://stackoverflow.com/comment/85187877
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49091121
has text: Why are you running `sudo` with the `-H` flag? Try it without the `-H` flag.

http://stackoverflow.com/q/49015864
tagged with: file
has comment: http://stackoverflow.com/comment/85036667
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49015893
has answer: http://stackoverflow.com/a/49015897
has comment: http://stackoverflow.com/comment/85037361
has body: if I have: fdata = open(pathf, "r").read().splitlines() Will the file automatically close after getting the data? If not how can I close it since fdata is not a handle? Thank you
score: 4
linked to: http://stackoverflow.com/q/2404430
type: Question
possible better answer: http://stackoverflow.com/a/49015897
has title: Is file closing necessary in this situation?
favorite count: 0
has answer: http://stackoverflow.com/a/49015916
has answer: http://stackoverflow.com/a/49015945
has comment: http://stackoverflow.com/comment/85037055
tagged with: python
upvote count: 4
answer count: 4
accepted answer: http://stackoverflow.com/a/49015893
downvote count: 0
has comment: http://stackoverflow.com/comment/85036630

http://stackoverflow.com/a/49113914
type: Answer
has body: A simple way: Creating a list with the names of csvs: files=listdir() csvs=list() for file in files: if file.endswith(".csv"): csvs.append(file) concatenate the csvs: data=pd.DataFrame() for i in csvs: table=pd.read_csv(i) data=pd.concat([data,table])
answers question: http://stackoverflow.com/q/49111093
score: 0

http://stackoverflow.com/comment/85133063
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49063586
has text: @questnofinterest Post console output for `console.log(data)` to your question.

http://stackoverflow.com/a/56854883
type: Answer
score: 2
has body: The only useful workaround I could find was to include cluster markers. from folium.plugins import FastMarkerCluster x = #your centering coordinates here LAT y = #your centering coordinates here LONG z = #your zoomlevel here your_map = folium.Map(location=[x, y], tiles="OpenStreetMap", zoom_start=z) callback = ('function (row) {' 'var circle = L.circle(new L.LatLng(row[0], row[1]), {color: "red", radius: 10000});' 'return circle};') your_map.add_child(FastMarkerCluster(your_df'your_LAT_col', 'your_LONG_col'.values.tolist(), callback=callback)) your_map
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49017491

http://stackoverflow.com/q/48976565
has body: How would you store a multi-line input into an list? For example: 3 2 1 1 1 0 2 1 1 4 3 0 1 2 2 1 2 1 3 How would I take that input and store it as a list like so: examList = [ [3], [2,1], [1,1,0], [2,1,1], [4,3,0,1,2], [2], [1,2], [1,3] ] How do you identify the end user input if there any no specific indicators?
upvote count: 1
has answer: http://stackoverflow.com/a/62611470
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48978270
score: 0
answer count: 3
favorite count: 0
tagged with: arr
has title: How to store multi-line input into a list (python)
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48976616
tagged with: list

http://stackoverflow.com/comment/85166914
comment on: http://stackoverflow.com/q/49080555
score: 0
has text: `new_image = frame_image(images[n])`, Here `images[n]` is an Image object, and not a path to it.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49108603
has comment: http://stackoverflow.com/comment/85222495
has body: How about: ext = "bbb" a = "http://januapp.com/demo/search.php?search=" print a+ext Where ext is what you want to search for, a is the link and just add them together. Or you could replace values like this: ext = "bbb" a = "http://januapp.com/demo/search.php?search=aaa" print a.replace('aaa', ext) Using regex: import re ext = "bbb" a = "http://januapp.com/demo/search.php?search=aaa" b=re.compile(r".+search=") print re.search(b,a).group()+ext
upvote count: 1
has comment: http://stackoverflow.com/comment/85222417
type: Answer
has comment: http://stackoverflow.com/comment/85222832
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49108465

http://stackoverflow.com/comment/84950512
type: Comment
type: QuestionComment
has text: Dictionaries have no order. Is the output order important?
score: 0
comment on: http://stackoverflow.com/q/48972764

file
tags question: http://stackoverflow.com/q/49101325
type: Tag
tags question: http://stackoverflow.com/q/48990191
tags question: http://stackoverflow.com/q/48984897
tags question: http://stackoverflow.com/q/48994256
tags question: http://stackoverflow.com/q/49029337
tags question: http://stackoverflow.com/q/49087139
tags question: http://stackoverflow.com/q/49015864
tag name: file
tags question: http://stackoverflow.com/q/49060184
tags question: http://stackoverflow.com/q/49090281
tags question: http://stackoverflow.com/q/49054134
tags question: http://stackoverflow.com/q/49095047
tags question: http://stackoverflow.com/q/48982698
tags question: http://stackoverflow.com/q/48989604
tags question: http://stackoverflow.com/q/49095664
tags question: http://stackoverflow.com/q/49046972
tags question: http://stackoverflow.com/q/49066799
tags question: http://stackoverflow.com/q/48966229
tags question: http://stackoverflow.com/q/49094805
tags question: http://stackoverflow.com/q/49078417
tags question: http://stackoverflow.com/q/49061202
tags question: http://stackoverflow.com/q/49084255
tags question: http://stackoverflow.com/q/49047902
tags question: http://stackoverflow.com/q/48977530
tags question: http://stackoverflow.com/q/49061216
tags question: http://stackoverflow.com/q/49068121
tags question: http://stackoverflow.com/q/49012927
tags question: http://stackoverflow.com/q/49104049
tags question: http://stackoverflow.com/q/49060282
tags question: http://stackoverflow.com/q/49101273
tags question: http://stackoverflow.com/q/49110725
tags question: http://stackoverflow.com/q/49029873
tags question: http://stackoverflow.com/q/49066831

http://stackoverflow.com/comment/85238476
type: QuestionComment
comment on: http://stackoverflow.com/q/49112581
has text: @vivek Kumar Yes I agree, transformation of text data is easy but its too much time consuming for larger dataset.so thought of doing by considering feature list
score: 0
type: Comment

http://stackoverflow.com/comment/85340218
type: Comment
comment on: http://stackoverflow.com/a/49030065
has text: @N.Mittal - Data was changed?
type: AnswerComment
score: 0

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/49065003
tags question: http://stackoverflow.com/q/49072355

http://stackoverflow.com/comment/85220949
has text: Actually, `feed_data` is meant to be called by the underlying stream protocol, I don't think it's safe to use it this way. For instance, the protocol might receive more data from the client and feed it before you can feed the header back, therefore corrupting the request. I'd use `remote_writer.write(data)` instead (before piping the streams).
type: Comment
comment on: http://stackoverflow.com/a/49107831
score: 0
type: AnswerComment

http://stackoverflow.com/a/49177255
score: 1
has comment: http://stackoverflow.com/comment/85410635
upvote count: 1
has body: Ive modified the implementation of heapq by adding a parameter to heappop(), and heappush() - which is heapIndex. That takes a dictionary of {item: index} and updates the heapIndex as it pops or pushes into heap. Ive also added a new method heappop_arbitrary() which deletes an arbitrary element and updates the heapIndex The code is available here: https://github.com/emoen/heapq_with_index Ive renamed the methods heappop(),heappush() to heappop2(), heappush2() to avoid confusion with the original methods. I havent implemented this for any of the other functions available in heapq. Edit: please star if you can use the repo :)
accepted answer of: http://stackoverflow.com/q/49114499
has comment: http://stackoverflow.com/comment/85405297
has comment: http://stackoverflow.com/comment/85614371
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49114499
type: Answer

http://stackoverflow.com/q/49100244
has answer: http://stackoverflow.com/a/49100451
has body: This is a rather simple operation, but it is repeated millions of times in my actual code and, if possible, I'd like to improve its performance. import numpy as np # Initial data array xx = np.random.uniform(0., 1., (3, 14, 1)) # Coefficients used to modify 'xx' a, b, c = np.random.uniform(0., 1., 3) # Operation on 'xx' to obtain the final array 'yy' yy = xx[0] * a * b + xx[1] * b + xx[2] * c The last line is the one I'd like to improve. Basically, each term in xx is multiplied by a factor (given by the a, b, c coefficients) and then all terms are added to give a final yy array with the shape (14, 1) vs the shape of the initial xx array (3, 14, 1). Is it possible to do this via numpy broadcasting?
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85206858
upvote count: 3
accepted answer: http://stackoverflow.com/a/49100451
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49100574
has comment: http://stackoverflow.com/comment/85205892
answer count: 2
tagged with: array-broadcasting
has title: NumPy broadcasting to improve dot-product performance
downvote count: 0
possible better answer: http://stackoverflow.com/a/49100574
favorite count: 0
has comment: http://stackoverflow.com/comment/85205847

http://stackoverflow.com/q/49046889
upvote count: 1
has answer: http://stackoverflow.com/a/49047333
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/85098409
accepted answer: http://stackoverflow.com/a/49047333
answer count: 1
has body: I crawl this web site https://movies.yahoo.com.tw/movieinfo_main.html/id=7819 I use scarpy shell 'https://movies.yahoo.com.tw/movieinfo_main.html/id=7819' on my terminal I want to crawl the six li href under the ul When i want to get the li tag i type command response.xpath('//ul[@class="trailer_list imglist slick-initialized slick-slider"]/li') but get a empty list [] I try to type this command response.xpath('//div[@class="l_box_inner"]/ul/li/a/@href').extract() Here is what i get: In [14]: response.xpath('//div[@class="l_box_inner"]/ul/li/a/@href').extract() Out[14]: [u'https://movies.yahoo.com.tw/name_main/1000', u'https://movies.yahoo.com.tw/name_main/2595', u'https://movies.yahoo.com.tw/video/%E9%81%8A%E6%88%B2%E5%A4%9C%E6%AE%BA%E5%BF%85%E6%AD%BB-%E4%B8%AD%E6%96%87%E9%A0%90%E5%91%8A-095130014.html?movie_id=7819', u'https://movies.yahoo.com.tw/movieinfo_photos.html/id=7819?movie_photo_id=189047', u'https://movies.yahoo.com.tw/movieinfo_photos.html/id=7819?movie_photo_id=189050', u'https://movies.yahoo.com.tw/movieinfo_photos.html/id=7819?movie_photo_id=189053', u'https://movies.yahoo.com.tw/movieinfo_photos.html/id=7819?movie_photo_id=189056', u'https://movies.yahoo.com.tw/movieinfo_photos.html/id=7819?movie_photo_id=189059', u'https://movies.yahoo.com.tw/movieinfo_photos.html/id=7819?movie_photo_id=189062', u'https://movies.yahoo.com.tw/post/169756772517/傑森貝特曼捲進失控遊戲夜-全是他惹的禍'] But i just want to get the six href they id is 189047'189050'189053'189056'189059'189062 What is the correct xpath command if i just want to get the li six href ? Any help would be appreciated. Thanks in advance.
downvote count: 0
has comment: http://stackoverflow.com/comment/85098508
favorite count: 0
has title: Scrapy use xpath crawl ul class is no working
tagged with: python
type: AnsweredQuestion
tagged with: xpath
has comment: http://stackoverflow.com/comment/85100192
score: 1

http://stackoverflow.com/q/49090796
has comment: http://stackoverflow.com/comment/85187166
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/69870814
has body: I want to change the behavior of isinstance for a live python object. One solution is to create a simple wrapper like the following, but I do not like it: class Widget: def __init__(self, obj): self.inner_self = obj lizard = ['head', 'nose', 'tail'] wlizard = Widget(lizard) assert(isinstance(wlizard, Widget)) # no assertion error thrown What I don't like about this particular wrapper, is that we must extract the lizard from wlizard before we can use the lizard again try: wlizard[0] except: print('sorry, wlizard doesn\'t behave like a lizard') lizard = wlizard.inner_self print(lizard[0]) # works fine What I really want is for wlizard to behave exactly like lizard except that isinstance returns True for wlizard and it returns false for lizard. The following sort-of works, but has some drawbacks: class Widget: pass def MakeAWidget(obj): class Blah(type(obj), Widget): pass # inherits type(obj)'s __init__ method wobj = Blah(obj) # calls type(obj)'s copy constructor return wobj One problem is that this only works if type(obj)'s __init__() method takes in more than just self; in particular, that __init__ can take in an instance of type(obj), and when it does, it copies the attributes of obj into self. I would like something that works even if obj does not have a copy constructor. Something like the following might be possible to force the existence of a copy-constructor: import copy class Blah(type(obj), Widget): def __init__(*args, **kwargs): if isinstance(args[0], type(obj)): self = copy.deepcopy(args[0]) return self return super(type(self), self).__init__(*args, **kwargs) However, I would rather not copy the object, only modify it in-place. Something like the following might be possible, but I am not sure what __BLAH__ would be: obj = ['apple', 'pear', 'banana'] assert(not isinstance(obj, Widget)) # no error thrown obj.__BLAH__.append('Widget') assert(isinstance(obj, Widget)) # no error thrown
has comment: http://stackoverflow.com/comment/85187320
tagged with: metaclass
has title: How to change a live object's isinstance() behavior?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85187579
tagged with: inheritance
tagged with: class
has comment: http://stackoverflow.com/comment/85187265
score: 0
has comment: http://stackoverflow.com/comment/85187227
has comment: http://stackoverflow.com/comment/85187235
has comment: http://stackoverflow.com/comment/85187289
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49119574

http://stackoverflow.com/a/48993005
answers question: http://stackoverflow.com/q/48993004
score: 9
type: Answer
has body: Prediction distribution After playing around with it for a while, I decided to visualize the actual prediction distribution for both models: predicted_distribution = tf.nn.softmax(logits, name='distribution') Below are the histograms of the distributions and how they evolved over time. With ReLu (wrong model) Without ReLu (correct model) The first histogram makes sense, most of probabilities are close to 0. But the histogram of the ReLu model is suspicious: the values seem to concentrate around 0.15 after few iterations. Printing the actual predictions confirmed this idea: [0.14286 0.14286 0.14286 0.14286 0.14286 0.14286 0.14286] [0.14286 0.14286 0.14286 0.14286 0.14286 0.14286 0.14286] I had 7 classes (for 7 different languages at that moment) and 0.14286 is 1/7. It turns out, the "perfect" model learned to output 0 logits, which in turn translated in uniform prediction. But how can this distribution be reported as 99% accurate? tf.nn.in_top_k Before diving into tf.nn.in_top_k I checked an alternative way to compute accuracy: true_correct = tf.equal(tf.argmax(logits, 1), tf.cast(y, tf.int64)) alternative_accuracy = tf.reduce_mean(tf.cast(true_correct, tf.float32)) ... which performs honest comparison of the highest predicted class and the ground truth. The result is this: iteration=2 loss=3.992 train-acc=0.13086 train-alt-acc=0.13086 iteration=4 loss=3.590 train-acc=0.13086 train-alt-acc=0.12207 iteration=6 loss=2.871 train-acc=0.21777 train-alt-acc=0.13672 iteration=8 loss=2.466 train-acc=0.37695 train-alt-acc=0.16211 iteration=10 loss=2.099 train-acc=0.62305 train-alt-acc=0.10742 iteration=12 loss=2.066 train-acc=0.79980 train-alt-acc=0.17090 iteration=14 loss=2.016 train-acc=0.84277 train-alt-acc=0.17285 iteration=16 loss=1.954 train-acc=0.91309 train-alt-acc=0.13574 iteration=18 loss=1.956 train-acc=0.95508 train-alt-acc=0.06445 iteration=20 loss=1.923 train-acc=0.97754 train-alt-acc=0.11328 Indeed, tf.nn.in_top_k with k=1 diverged from the right accuracy quick…
upvote count: 9
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48993004

http://stackoverflow.com/comment/85229610
has text: Thanks, is there a reason why it only plots the one category and only plots a single date from the list?
type: Comment
comment on: http://stackoverflow.com/a/49111132
score: 0
type: AnswerComment

http://stackoverflow.com/q/49047336
tagged with: class
has title: Module of Instance in Python
answer count: 1
has comment: http://stackoverflow.com/comment/85099293
has answer: http://stackoverflow.com/a/49050163
has body: Using __name__ inside a method references the module where the class was defined. Is there a way instead for an object to get the module where it has been instantiated?
has comment: http://stackoverflow.com/comment/85099236
has comment: http://stackoverflow.com/comment/85099205
tagged with: python
tagged with: module
tagged with: object
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49050163
type: Question
has comment: http://stackoverflow.com/comment/85099590

http://stackoverflow.com/q/49095047
accepted answer: http://stackoverflow.com/a/49095427
has comment: http://stackoverflow.com/comment/85195863
has comment: http://stackoverflow.com/comment/85195316
has answer: http://stackoverflow.com/a/49095427
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49095162
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49095162
downvote count: 0
tagged with: file
has body: I have a file which has a content like below 14.678 14.652 14.636 14.623 14.615 14.608 14.603 14.599 14.596 17.448 17.427 17.413 17.402 17.395 17.390 17.386 17.384 17.382 18.271 18.252 18.240 18.231 18.223 18.217 18.212 18.211 18.209 20.239 20.216 20.198 20.188 20.168 20.164 20.165 20.147 20.125 20.500 20.480 20.458 20.438 20.421 20.400 20.382 20.368 20.355 17.195 17.173 17.159 17.150 17.143 17.138 17.134 17.132 17.130 18.652 18.628 18.611 18.600 18.590 18.583 18.580 18.571 18.565 18.721 18.697 18.684 18.673 18.665 18.656 18.648 18.645 18.644 19.501 19.452 19.396 19.314 19.166 18.936 18.629 18.325 18.089 18.470 18.449 18.434 18.421 18.413 18.406 18.401 18.399 18.397 18.288 18.266 18.254 18.245 18.237 18.232 18.229 18.228 18.227 18.691 18.669 18.653 18.641 18.631 18.622 18.614 18.612 18.606 17.407 17.387 17.375 17.366 17.360 17.355 17.352 17.349 17.348 16.691 16.672 16.659 16.649 16.643 16.639 16.635 16.632 16.631 19.293 19.271 19.253 19.244 19.233 19.226 19.218 19.209 19.201 18.530 18.509 18.493 18.482 18.474 18.469 18.463 18.457 18.452 18.769 18.742 18.725 18.712 18.701 18.695 18.688 18.682 18.681 18.356 18.335 18.320 18.310 18.300 18.294 18.288 18.283 18.281 18.332 18.313 18.298 18.286 18.280 18.276 18.271 18.267 18.265 14.998 14.977 14.963 14.953 14.945 14.940 14.936 14.933 14.930 I want to delete every first column value from every other values.The operation should be something like this 14.678 - 17.448 14.678 - 18.271 14.678 - 18.271 and so on... Similarly 17.448 - 14.678 17.448 - 18.271 17.448 - 20.239 and so on... So far what I am able to do is with open("geodata.txt", "r") as fo: for i in fo: for j in fo: print(float(i.split(" ")[0]) - float(j.split(" ")[0])) But it only does the operation one time and then it stops. -2.7699999999999996 -3.593 -5.561 -5.821999999999999 -2.5169999999999995 -3.974 -4.042999999999999 -4.823 -3.791999999999998 -3.6099999999999994 -4.012999999999998 -2.728999999999999 -2.012999999999998 -4.614999999999998 -3.8520000000000003 -4.0…
type: Question
upvote count: 2
answer count: 2
has title: How to subtract every first column value form every other values from a file?
tagged with: arrays

http://stackoverflow.com/comment/85141365
comment on: http://stackoverflow.com/a/49067921
has text: thank you for answering, all of these ids are not videoid, I want specifically video id's, is it possible to get from this tag <a class="icon-font-before icon-chain-solid-before" href="http://www.espncricinfo.com/video/clip?id=22615485"
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49003391
score: 1
answers question: http://stackoverflow.com/q/49000834
upvote count: 1
has body: input always result in a single str. If you want to parse this string as being JSON-like you can use the json module. import json classes=json.loads(input("Enter your classes: " )) def printsched(classes): for n in classes: print(n) return len("".join(classes)) printsched(classes) For more user friendly input you can use the split function and trim function. classes=[x.trim() for x in input("Enter your classes: " ).split(",")] def printsched(classes): for n in classes: print(n) return len("".join(classes)) printsched(classes) Note: do not add multiple things in a single method. The method will become cluttered and unclear. What is the single responsibility of this method, (printing or calculating the length of the input string) classes=[x.trim() for x in input("Enter your classes: " ).split(",")] def print_classes(classes): for n in classes: print(n) def calc_length(classes return len("".join(classes)) print_classes(classes) print(calc_length(classes))
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85158991
has text: @qqqwww: yep, just change `'test'` -> `'expected'` and you're good to go!
type: AnswerComment
comment on: http://stackoverflow.com/a/49076129
score: 0
type: Comment

http://stackoverflow.com/comment/84960159
comment on: http://stackoverflow.com/q/48976002
has text: Traceback (most recent call last): File "/home/akash/Coded/VideoCode/Test3", line 70, in <module> out.write(gray) # It's not work without proper size of frame cv2.error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/videoio/src/cap_mjpeg_encoder.cpp:834: error: (-215) img.cols == width && img.rows == height*3 in function write
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48982496
type: UnansweredQuestion
tagged with: keypress
has title: Listbox getting `Key` events with diacritics instead of national characters
has body: When I switch the keyboard to Russian layout, my widget gets key events with some diacritics in keysym instead of Russian letters. Here's a demonstration (using the dump module): import Tkinter as tkinter from dump import dump def show_event(e): dump(e) root=tkinter.Tk() lb = tkinter.Listbox(root) lb.grid() root.bind_class('Listbox','&lt;Control-Key&gt;', show_event) root.mainloop() Now, when I focus the listbox and press Ctrl with letters фыва (that correspond to asdf), the keysyms in the printed events are: ocircumflex,ucircumflex,acircumflex,agrave. While I, naturally, expected to get Cyrillic_ef, Cyrillic_yeru etc. At the same time, if I type text into an Entry, Russian letters are inserted correctly. Any ideas of what is going on &amp; how to fix? That said, maybe it doesn't even need fixing (it may allow one to use the same binding for any non-English keyboard layout) but I'd still like to know the reason for this highly counterintuitive effect incl. if it's by design.
tagged with: tkinter
type: Question
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51509436
score: 0
tagged with: tk-toolkit
linked to: http://stackoverflow.com/q/14455625

web-scraping
tags question: http://stackoverflow.com/q/49090882
tags question: http://stackoverflow.com/q/48996872
tags question: http://stackoverflow.com/q/48965080
tags question: http://stackoverflow.com/q/49036063
tags question: http://stackoverflow.com/q/49118596
tags question: http://stackoverflow.com/q/49042076
tags question: http://stackoverflow.com/q/49102430
tags question: http://stackoverflow.com/q/49119922
tags question: http://stackoverflow.com/q/49022447
tags question: http://stackoverflow.com/q/49103186
tags question: http://stackoverflow.com/q/49015037
tags question: http://stackoverflow.com/q/49075355
tags question: http://stackoverflow.com/q/49062845
tags question: http://stackoverflow.com/q/48999393
tags question: http://stackoverflow.com/q/49109399
tags question: http://stackoverflow.com/q/49112398
tags question: http://stackoverflow.com/q/48990275
tags question: http://stackoverflow.com/q/49085716
tags question: http://stackoverflow.com/q/49063237
tags question: http://stackoverflow.com/q/49031894
tags question: http://stackoverflow.com/q/49062469
tags question: http://stackoverflow.com/q/49077851
tags question: http://stackoverflow.com/q/49082933
tags question: http://stackoverflow.com/q/48969332
tags question: http://stackoverflow.com/q/49085421
tags question: http://stackoverflow.com/q/49017547
tags question: http://stackoverflow.com/q/49025442
tags question: http://stackoverflow.com/q/49099520
tags question: http://stackoverflow.com/q/49040735
tags question: http://stackoverflow.com/q/49088851
tags question: http://stackoverflow.com/q/49057247
tags question: http://stackoverflow.com/q/49095848
tags question: http://stackoverflow.com/q/48976977
tags question: http://stackoverflow.com/q/49088106
tags question: http://stackoverflow.com/q/48991501
tags question: http://stackoverflow.com/q/49023861
tags question: http://stackoverflow.com/q/49019168
tags question: http://stackoverflow.com/q/49003764
tags question: http://stackoverflow.com/q/49088880
tags question: http://stackoverflow.com/q/48970724
tags question: http://stackoverflow.com/q/48983551
tags question: http://stackoverflow.com/q/48967679
tags question: http://stackoverflow.com/q/48984639
tags question: http://stackoverflow.com/q/49083438
tags question: http://stackoverflow.com/q/48994782
tags question: http://stackoverflow.com/q/48999841
tags question: http://stackoverflow.com/q/49102639
tags question: http://stackoverflow.com/q/49042064
tags question: http://stackoverflow.com/q/48977468
tags question: http://stackoverflow.com/q/49073323
tags question: http://stackoverflow.com/q/48982416
tags question: http://stackoverflow.com/q/49046887
tags question: http://stackoverflow.com/q/49031703
tag name: web-scraping
tags question: http://stackoverflow.com/q/48970217
tags question: http://stackoverflow.com/q/49005519
tags question: http://stackoverflow.com/q/49105772
tags question: http://stackoverflow.com/q/49041589
tags question: http://stackoverflow.com/q/49071064
tags question: http://stackoverflow.com/q/49088524
tags question: http://stackoverflow.com/q/48985234
tags question: http://stackoverflow.com/q/49019048
tags question: http://stackoverflow.com/q/48966964
tags question: http://stackoverflow.com/q/49084094
type: Tag
tags question: http://stackoverflow.com/q/48989448
tags question: http://stackoverflow.com/q/48985758
tags question: http://stackoverflow.com/q/49111534
tags question: http://stackoverflow.com/q/48975310
tags question: http://stackoverflow.com/q/49011726
tags question: http://stackoverflow.com/q/49010813
tags question: http://stackoverflow.com/q/49109263
tags question: http://stackoverflow.com/q/49012090
tags question: http://stackoverflow.com/q/49035188
tags question: http://stackoverflow.com/q/49007301
tags question: http://stackoverflow.com/q/49018025
tags question: http://stackoverflow.com/q/49101595
tags question: http://stackoverflow.com/q/49120065
tags question: http://stackoverflow.com/q/48973101
tags question: http://stackoverflow.com/q/49061657

http://stackoverflow.com/comment/85136859
type: AnswerComment
score: 0
type: Comment
has text: thanks, the code fails for just a tree with one node: -3. the code returns 0.
comment on: http://stackoverflow.com/a/49065745

http://stackoverflow.com/a/49037011
score: 1
has comment: http://stackoverflow.com/comment/85098450
type: Answer
has body: It looks like PyCharm is replacing sys.stdout with its own stream, so when you replace it with a file stream, PyCharm fails to use it. So, limit your interventions to the scope of one function, to avoid interference with PyCharm. This is the general idea: def testTitle(self): original_stdout = sys.stdout sys.stdout = open("C:\\Users\\Marialena\\Downloads\\out2.log", 'wt') # your test code goes here sys.stdout = original_stdout Now, from the outside, it will look like sys.stdout was never modified. Of course, you'll want to improve on some things: handle exceptions in test - restore stdout in a finally block avoid deleting the file in each test - open the file in append mode avoid having to copy-and-paste this code in each test - make a context manager @contextmanager def redirected_stdout(filename): original_stdout = sys.stdout sys.stdout = open(filename, 'at') try: yield finally: sys.stdout = original_stdout and then: def testTitle(self): with redirected_stdout("C:\\Users\\Marialena\\Downloads\\out2.log"): # your test code goes here Alternatively: Investigate how PyCharm expects sys.stdout to behave and make your own class which does both: writes to file and provides the API which PyCharm expects.
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49012927

http://stackoverflow.com/q/49118974
upvote count: 2
type: UnansweredQuestion
has body: I am implementing a map in folium taking the information from a dataframe df. I contains the longitude, latitude, name and region information. Using a GeoJson file I have taken here: https://github.com/martinjc/UK-GeoJSON, I am able to define the regions in UK, highlight them when hovering with the mouse pointer and show some information. I would like to create a popup for each region with a button. If the button is clicked all the entries in the df which are in that region appear like markers. Is it possible? The code I am using right now is below: ...operations on df and definition of the map m... width = 10 heigth = 4 resolution = 75 def style_function(feature): return { 'fillColor': '#ffaf00', 'color': 'grey', 'weight': 1.5, 'dashArray': '5, 5' } def highlight_function(feature): return { 'fillColor': '#ffaf00', 'color': 'black', 'weight': 3, 'dashArray': '5, 5' } c = folium.GeoJson(geojsonFile, name = 'Highlight', overlay=True, style_function = style_function, highlight_function = highlight_function) html = '{}&lt;br&gt; Info: {} &lt;br&gt; &lt;buttononclick="window.location.reload()"&gt;Reload&lt;/button&gt;'.format frame = IFrame(html(name, info), width=(width*resolution)+20, height=(height*resolution)+20) popup_text = folium.Popup(iframe, max_width=2650) c.add_child(folium.Popup(popup_text)) c.add_to(m) I can add the button in the popup; what I am trying to do is to define a function like: def testFunction(df, region): markerCluster = folium.plugins.MarkerCluster().add_to(map) for index, row in df.iterrows(): if row['region'] == region: folium.Marker([row['lat'], row['lon']], popup='some text').add_to(markerCluster) that will be run when the button is clicked. The final effect I am looking for should be: open the map, click on the selected region, click the button, the markers on the region appear. But I haven't found any solution yet (I have tried with Flask without success).
tagged with: python
score: 2
tagged with: mapping
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/117360893
tagged with: dataframe
has title: Markers appear on folium map when clicking on button
downvote count: 0
tagged with: folium
favorite count: 0

http://stackoverflow.com/a/48963994
type: Answer
score: 2
downvote count: 0
has body: Hope this helps. Here you need to use the object which has been created. class Animal: def __init__(self,name,age): self.name = name self.age = age def display_age(self): print("{} Age: {}".format(self.name,self.age)) def create(): name = input("enter name: ") age = input("enter age: ") return Animal(name, age) a = create() a.display_age()
upvote count: 2
answers question: http://stackoverflow.com/q/48963842

http://stackoverflow.com/comment/85207603
type: AnswerComment
score: 0
type: Comment
has text: good point, didn't know about the list() function, never good to use preserves.
comment on: http://stackoverflow.com/a/49101091

http://stackoverflow.com/q/49008122
has title: Django: "initial_value must be str or None, not bytes" error
has body: While learning Django and Python I am trying to download a pdf file. The files content should be from a html template. I am trying to do this using the pisaDocument example(and any other example from the internet are exactyle the same). In my case I am getting the: initial_value must be str or None, not bytes error on the StringIO(html.encode("utf-8")) part. I understand that the problem is that StringIo need a str and it returns bytes, but how can i convert the bytes to str? from django.http import HttpResponse, Http404 from django.shortcuts import render, redirect from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from io import StringIO, BytesIO from cgi import escape def export(request): if(request.POST): client = request.POST.get('client') doc = request.POST.get('doc') template = get_template('files/insurance.html.twig') html = template.render() result = StringIO(html) pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors %s ' % escape(html)) else: raise Http404("POST data not found")
tagged with: http://stackoverflow.com/tag/pdf
tagged with: django
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85021109
has comment: http://stackoverflow.com/comment/85020703
score: 0

http://stackoverflow.com/q/48984449
tagged with: anaconda
linked to: http://stackoverflow.com/q/43700354
has comment: http://stackoverflow.com/comment/85053277
has comment: http://stackoverflow.com/comment/84974031
has body: Conda and Visual Studio Code debugging I saw the above answer and was able to choose the correct Conda env from Python: Select Interpreter on the the Cmd-Shift-P command palette. However, I installed tensorflow in the root environment and in the current config it is not available from the vscode debugger. I need to add this line at the top of my script to makes things work in debug: sys.path.append('/[...]/anaconda/anaconda3/lib/python3.6/site-packages') import tensorflow as tf how do I configure this properly within vscode? NOTE: if I install tensorflow in my active conda env, then all works fine. but I should have to do that, right?
has title: vscode debugging with conda: how to access root pkgs?
tagged with: python
tagged with: vscode-debugger
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85053250
type: Question
tagged with: visual-studio-code

http://stackoverflow.com/comment/84967539
type: Comment
score: 0
has text: `audit_items_list` is a list.
type: AnswerComment
comment on: http://stackoverflow.com/a/48981212

http://stackoverflow.com/q/48984289
has body: I am using docker-compose to deploy multiple microservices in flask. Here is the compose code version: '3' services: test-api: volumes: - ./test-api:/test-api build: test-api ports: - "5000:5000" redis: image: "redis:alpine" search: volumes: - ./seach:/search environment: - HTTP_PORT=5000 - REDIS_URL=redis://redis:6379/0 build: search ports: - "5001:5000" link: - redis Now I have to access this service from single URL eg: http://example.com/test-api or http://example.com/search, but I am unable to figure it out since the 2 services are running are on 2 different ports. I know I need to use nginx and configure it so that I can access them. But I am not sure how to do that. Can someone help me with this or at least give me some docs to read so as to understand the routing? Also both the services use /health to report the result of health-check. How do I access the health check for both the services?
possible better answer: http://stackoverflow.com/a/48984966
answer count: 2
has answer: http://stackoverflow.com/a/48984966
upvote count: 1
tagged with: docker-compose
tagged with: nginx
tagged with: docker
has answer: http://stackoverflow.com/a/49269429
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: microservices
tagged with: python
has title: Accessing multiple services using single url docker-compose
accepted answer: http://stackoverflow.com/a/49269429

http://stackoverflow.com/q/49113933
type: Question
has answer: http://stackoverflow.com/a/49114128
answer count: 1
has comment: http://stackoverflow.com/comment/85232949
score: 0
has comment: http://stackoverflow.com/comment/85233018
tagged with: geopandas
tagged with: python
favorite count: 0
has body: so I'm getting really nervous about that. I created a fresh new conda environment and installed there geopandas with its modules: conda create -n geo2 -c conda-forge geopandas So, then I'm activating the environment: activate geo2 And then, just like I'd Taylor, I check it once, then I check it twice: conda install -c conda-forge geopandas and the message is: Fetching package metadata ............... Solving package specifications: . # All requested packages already installed. # packages in environment at C:\Users\mikomi\AppData\Local\Continuum\Anaconda3\envs\geo2: # geopandas 0.3.0 py36_0 conda-forge So, you'd think that's it, but no. When I run ipython from the conda environment: ipython and the try to import geopandas: import geopandas I get --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-1-e0ae602b2f92&gt; in &lt;module&gt;() ----&gt; 1 import geopandas ModuleNotFoundError: No module named 'geopandas' I just dont understand this and it's driving me mad. Additional info: 1) this is the output of sys.path: ['', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\Scripts', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\python36.zip', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\DLLs', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\Sphinx-1.5.6-py3.6.egg', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\Users\\mikomi\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\setuptools-27.2…
has comment: http://stackoverflow.com/comment/85232926
has comment: http://stackoverflow.com/comment/85233081
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85233198
has title: Python doesn't see installed module when running ipython
tagged with: anaconda
tagged with: ipython
has comment: http://stackoverflow.com/comment/85233035
tagged with: conda

http://stackoverflow.com/comment/84939715
type: Comment
comment on: http://stackoverflow.com/q/48966973
score: 0
type: QuestionComment
has text: What do you mean ? (It's juste a quick code I wrote to practice, nothing really relevant)

http://stackoverflow.com/a/49015453
score: 2
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/49014589
has body: For each i less than len(t), and each character c that occurs in t, make a mapping from (i,c)-&gt;j, where j is the first index >= i that at which c occurs. Then you can iterate through each Sk, using the map to find the next occurrence of each required character, if it exists. This is essentially making a deterministic finite automaton that matches subsequences of t (https://en.wikipedia.org/wiki/Deterministic_finite_automaton).

http://stackoverflow.com/a/49107076
has comment: http://stackoverflow.com/comment/85220536
upvote count: 1
has body: To find the spokes, sample the image with a small circle, close to the axle and a large one, close to the hoop. These will intercept white (angular) intervals. Join the middles of the intervals and check continuity of the spokes. When an interval is missing, you can extrapolate to the center.
has comment: http://stackoverflow.com/comment/85220738
has comment: http://stackoverflow.com/comment/85242827
has comment: http://stackoverflow.com/comment/85240719
accepted answer of: http://stackoverflow.com/q/49101544
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49101544
has comment: http://stackoverflow.com/comment/85242947
type: Answer
has comment: http://stackoverflow.com/comment/85220394
score: 1

http://stackoverflow.com/a/49040788
has body: In Python 2, print is a keyword. It can only be used for its intended purpose. I can't be the name of a variable or a function. In Python 3, print is a built-in function, not a keyword. So methods, for example, can have the name print. If you are using Python 2 and want to override its default behavior, you can import Python 3's behavior from __future__: from __future__ import print_function class MyClass: def print(self): print ('MyClass') a = MyClass() a.print()
type: AcceptedAnswer
upvote count: 10
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/85087502
has comment: http://stackoverflow.com/comment/85091551
answers question: http://stackoverflow.com/q/49040765
score: 10
accepted answer of: http://stackoverflow.com/q/49040765

http://stackoverflow.com/comment/85123564
score: 0
type: Comment
type: QuestionComment
has text: Python isn't statically typed
comment on: http://stackoverflow.com/q/49058729

http://stackoverflow.com/comment/85189249
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49091961
has text: In any case it says: AttributeError: ("'Series' object has no attribute 'allText'", 'occurred at index allText')
type: Comment

http://stackoverflow.com/q/48981913
answer count: 4
type: AnsweredQuestion
score: 2
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/48982001
has body: I am trying to learn Python by following the book "Python Crash Course", but I'm stuck because the book does not use the IDE I am using, PyCharm. The problem I encounter is when I try to import pygame it says module not found. I successfully installed pygame using this command: python -m pip install --user pygame command prompt screenshot I get the message "successfully installed pygame" but I'm still unable to import it. I noticed that PyCharm uses the interpreter from this location: \HelloWorld\venv\Scripts\python.exe which is inside the project folder. My python is installed in: \AppData\Local\Programs\Python\Python36-32\python.exe How can I give PyCharm's virtual environment access to pygame? Thanks!
has answer: http://stackoverflow.com/a/48982006
upvote count: 2
has answer: http://stackoverflow.com/a/48982001
type: Question
has answer: http://stackoverflow.com/a/48981994
tagged with: python-venv
downvote count: 0
has title: How to enable venv to access pygame module in PyCharm?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48981994
has answer: http://stackoverflow.com/a/49000449
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/85165696
has text: I love Option 2 a lot, but I encounter this error: `TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed`. Any idea why?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49079236
score: 0

http://stackoverflow.com/q/49037140
possible better answer: http://stackoverflow.com/a/49037223
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/49037348
score: 1
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/85079364
tagged with: python
answer count: 2
has title: How to print unique values of a column in a group using Pandas?
upvote count: 1
has answer: http://stackoverflow.com/a/49037348
has answer: http://stackoverflow.com/a/49037223
has body: I am trying to print unique values of the column ADO_name in my data set. Following is the example data set and code I tried (which gives error): import numpy as np import pandas as pd from pandas import Series, DataFrame data = {'ADO_name':['car1','car1','car1','car2','car2','car2'], 'Time_sec':[0,1,2,0,1,2], 'Speed.kph':[50,51,52,0,0,52]} dframe = DataFrame(data) for ado in dframe.groupby('ADO_name'): ado_name = ado["ADO_name"] adoID = ado_name.unique() print(adoID) Traceback (most recent call last): File "C:\Users\Quinton\AppData\Local\Temp\Rtmp88ifpB\chunk-code-188c39fc7de8.txt", line 14, in &lt;module&gt; ado_name = ado["ADO_name"] TypeError: tuple indices must be integers or slices, not str What am I doing wrong and how to fix it? Please help.

http://stackoverflow.com/a/55685210
upvote count: 1
type: Answer
downvote count: 0
has body: A little too late to answer. You can try adding the yapfArgs flag in your VS Code settings file. "python.formatting.yapfArgs": [ "--style", "{based_on_style: pep8, split_before_bitwise_operator: true}" ] Here the based_on_style field can be pep8, google, chromium and facebook. You can check out the values for the fields in the style.py file here. With split_before_bitwise_operator you can override the default settings specified for pip8 which is false. I wanted spaces in between the operators so I've set it. This will eliminate the E225 error you've been facing.
score: 1
answers question: http://stackoverflow.com/q/49005228

http://stackoverflow.com/comment/84973275
comment on: http://stackoverflow.com/q/48979045
has text: OK, so we have provided code that works, which happens to error when used with code that messes up the input? Is that correct?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85246049
comment on: http://stackoverflow.com/a/49117847
type: Comment
has text: I think the docs are wrong. Look at the image in the question. The byte `\x01` represents the bits `00000001`, which gives lines of seven black pixels and one white pixel.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85010362
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49002928
score: 0
has text: I formatted your code, please correct if I made any errors in interpreting what you intended. Remember code blocks must be indented 4 spaces.

http://stackoverflow.com/a/49030352
answers question: http://stackoverflow.com/q/49030147
has body: Upsert is another way to avoid duplicate entries, bulk upsert document bulk upsert pymongo updateBulk = db.collection.initialize_unordered_bulk_op() updateBulk.find({ "field1":"field1", "field2":"field2", ... ... ... "fieldn":"fieldn" }).upsert().update_one({'$set': { "field1":"field1", "field2":"field2", ... ... ... "fieldn":"fieldn", }}) result1 = updateBulk.execute();
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/85202405
type: Comment
comment on: http://stackoverflow.com/q/49098401
has text: You could select `By.CSS_SELECTOR` instead: `div.buying-tools-component a.js-buy`
score: 0
type: QuestionComment

http://stackoverflow.com/q/49026919
tagged with: python
has answer: http://stackoverflow.com/a/49027549
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85059791
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/85058503
has body: I have been trying, unsuccessfuly, to use numpy.genfromtxt() to import the data from a text file into an array. The problem I have is these data files should have five columns but from time to time a data entry is missing on a line and I only have 4 or fewer columns. I've read through the numpy documentation for genfromtxt() and eventually found the comment "When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields". Unfortunately this is exaclty the situation I am in. Can somebody suggest or show me another function/module that I can use to handle this kind of data? Thanks Update with an example of what I tried: data = np.genfromtxt(matches[0], skip_header = 6, usecols = (0,1,2,3,4), dtype=['S15','f8','f8','f8','i8']) The error I get is: ValueError: Some errors were detected ! Line #7 (got 4 columns instead of 5) Line #17 (got 4 columns instead of 5) Line #27 (got 4 columns instead of 5) Line #78 (got 4 columns instead of 5) As expecetd when I eyeball the data file the fourth data point on said lines is missing (therefore it only sees 4 columns). I have looked at the many data files I have to import in this way and it happens randomly that data in the fourth column is sometimes missing. For completeness here here is an excerpt of the data file: Start voltage = 0.000000V Final voltage = 30.000000V Voltage step = 5.000000V Acquisition time = 10s Post Irradiation 1 20180214_162747 -6.07967e-07 7.24649e-10 00000000000 20180214_162748 -3.69549e-07 6.10220e-10 +0.52310E-10 00000009504 20180214_162749 -6.19888e-07 5.97525e-10 +0.61081E-10 00000009239 20180214_162750 -1.27554e-06 6.65617e-10 +0.63719E-10 00000009053 20180214_162751 4.42266e-06 6.88171e-10 +0.70692E-10 00000009188 20180214_162752 1.99080e-06 6.10995e-10 +0.67934E-10 00000009321 20180214_162753 5.60284e-07 7.29239e-10 +0.71260E-10 00000009007 20180214_162754 1.04904e-06 6.29222e-10 +0.72195E-10 00000009386 20180214_162755 -1.8477…
has answer: http://stackoverflow.com/a/49027071
tagged with: numpy
answer count: 2
tagged with: genfromtxt
downvote count: 0
has title: Import data from a text file with random missing data in python
favorite count: 0
has comment: http://stackoverflow.com/comment/85060233

http://stackoverflow.com/comment/85101209
type: Comment
has text: Please see edits. Also please note that the program is to be run by people with no programming knowledge and therefore I would require the program to set up the resizing on its own.
comment on: http://stackoverflow.com/a/49048441
score: 0
type: AnswerComment

http://stackoverflow.com/a/52678595
has comment: http://stackoverflow.com/comment/105515463
upvote count: 18
score: 18
has comment: http://stackoverflow.com/comment/119537948
has comment: http://stackoverflow.com/comment/105527447
has comment: http://stackoverflow.com/comment/104105650
downvote count: 0
answers question: http://stackoverflow.com/q/49053741
type: Answer
has body: I know the answer has been chosen already, but there is a slightly different approach that also works. First, import from flask import current_app as app in the resource file, and when calling the logger, do: app.logger.info("This is an info message")

http://stackoverflow.com/a/48971022
score: 1
upvote count: 1
has body: When working with url paths that come in a variety of forms, different schemes, or without domain anchors, I like to use urlpath. Installation: pip install urlpath You could use the urlpath library to check each of the parts of the url after the domain to see if they contain a colon without an underscore. This example is useful if you want to avoid regex. Example: &gt;&gt;&gt; from urlpath import URL &gt;&gt;&gt; url = URL('https://en.wikipedia.org/wiki/Special:BookSources/0-8018-1841-9') &gt;&gt;&gt; any(':' in i and not ':_' in i for i in url.parts[1:]) True &gt;&gt;&gt; url2 = URL('https://en.wikipedia.org/wiki/The_Post_Card:_From_Socrates_to_Freud_and_Beyond') &gt;&gt;&gt; any(':' in i and not ':_' in i for i in url2.parts[1:]) False In this example, the any statement are returning true for urls you want to ignore. If you want to make this example a little more functional, you can also filter using regex. &gt;&gt;&gt; any(re.search(':[^_]',i) for i in url.parts[1:]) True &gt;&gt;&gt; any(re.search(':[^_]',i) for i in url2.parts[1:]) False If you are doing any request with these urls, I'd recommend giving the urlpath library a go. It combines the flexibility of pathlib, the functional urllib.parse, and has requests built it. &gt;&gt;&gt; url.get() &lt;Response [200]&gt;
type: Answer
answers question: http://stackoverflow.com/q/48969862
downvote count: 0

http://stackoverflow.com/a/48978221
answers question: http://stackoverflow.com/q/48976902
has comment: http://stackoverflow.com/comment/84996357
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84961559
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48976902
has body: The \busername (.+?)(,| |$) pattern contains 2 capturing groups, and re.findall will return a list of tuples once a match is found. See findall reference: If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match. So, there are three approaches here: Use a (?:...) non-capturing group rather than the capturing one: re.findall(r'\busername (.+?)(?:,| |$)', s). It will consume a , or space, but since only captured part will be returned and no overlapping matches are expected, it is OK. Use a positive lookahead instead: re.findall(r'\busername (.+?)(?=,| |$)', s). The space and comma will not be consumed, that is the only difference from the first approach. You may turn the (.+?)(,| |$) into a simple negated character class [^ ,]+ that matches one or more chars other than a space or comma. It will match till end of string if there are no , or space after username.

http://stackoverflow.com/comment/85123047
type: QuestionComment
has text: Presumably because adding a float and an int will normally produce a float
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49058729

http://stackoverflow.com/comment/85070770
score: 0
comment on: http://stackoverflow.com/q/49025274
has text: Also, it's not always possible to switch the backend after having loaded matplotlib.pyplot (at least that used to be the case). Hence I would advise having different matplotlibrc files for you local machine and the server, and set the backend there.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49000535
has comment: http://stackoverflow.com/comment/85007255
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49004440
answer count: 1
tagged with: postgresql
score: 0
tagged with: sql
has body: We have a database server and access is given to the users. Our database resides on this server. It is created using Postgresql. We create tables and perform other operations on different tables within this database through a python script. Right now, the python script, the database tables, and the database are on the same server. Basically, anybody with access to the server can access the database with its name. The user would have to put the name inside the python script to get access. How can we give privileges to different users? So, even if users have the access to the database server, we want only selected users can alter the database. How can we achieve that? I found this link - https://www.postgresql.org/docs/9.0/static/user-manag.html. However, my concern is anybody with python script and with the knowledge of the database name will be able to alter the table. Thanks for your input.
has title: privileges postgresql
type: UnansweredQuestion

http://stackoverflow.com/q/49025795
has comment: http://stackoverflow.com/comment/85057415
has comment: http://stackoverflow.com/comment/95053933
favorite count: 0
has answer: http://stackoverflow.com/a/74475646
tagged with: python
tagged with: http://stackoverflow.com/tag/mp4
has answer: http://stackoverflow.com/a/49027310
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85059028
tagged with: frame-rate
possible better answer: http://stackoverflow.com/a/74475646
has comment: http://stackoverflow.com/comment/85058908
has body: This is my video This is the script to find fps: import cv2 if __name__ == '__main__' : video = cv2.VideoCapture("test.mp4"); # Find OpenCV version (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') if int(major_ver) &lt; 3 : fps = video.get(cv2.cv.CV_CAP_PROP_FPS) print "Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps) else : fps = video.get(cv2.CAP_PROP_FPS) print "Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps) video.release(); This is the output of the script for this video: Frames per second using video.get(cv2.CAP_PROP_FPS) : 0.0 Why is it returning 0.0? The FPS is 14.0
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49027310
score: 22
upvote count: 22
has comment: http://stackoverflow.com/comment/85056606
has title: Python OpenCV video.get(cv2.CAP_PROP_FPS) returns 0.0 FPS

sqlite
tags question: http://stackoverflow.com/q/49009114
tags question: http://stackoverflow.com/q/49102080
tags question: http://stackoverflow.com/q/48967641
tags question: http://stackoverflow.com/q/48991884
tags question: http://stackoverflow.com/q/48965052
tags question: http://stackoverflow.com/q/49015969
tags question: http://stackoverflow.com/q/48965355
type: Tag
tags question: http://stackoverflow.com/q/49089158
tags question: http://stackoverflow.com/q/49082424
tags question: http://stackoverflow.com/q/49033913
tags question: http://stackoverflow.com/q/49119734
tags question: http://stackoverflow.com/q/49053285
tags question: http://stackoverflow.com/q/49080455
tags question: http://stackoverflow.com/q/49061103
tags question: http://stackoverflow.com/q/49038171
tags question: http://stackoverflow.com/q/49054275
tags question: http://stackoverflow.com/q/49010709
tags question: http://stackoverflow.com/q/49093469
tags question: http://stackoverflow.com/q/49054375
tags question: http://stackoverflow.com/q/49056545
tags question: http://stackoverflow.com/q/49014754
tags question: http://stackoverflow.com/q/49076444
tags question: http://stackoverflow.com/q/49103406
tags question: http://stackoverflow.com/q/49068438
tags question: http://stackoverflow.com/q/49056587
tags question: http://stackoverflow.com/q/49111556
tags question: http://stackoverflow.com/q/49064851
tags question: http://stackoverflow.com/q/49039734
tags question: http://stackoverflow.com/q/48990017
tags question: http://stackoverflow.com/q/49046930
tags question: http://stackoverflow.com/q/49120123
tags question: http://stackoverflow.com/q/49034403
tag name: sqlite
tags question: http://stackoverflow.com/q/49037807
tags question: http://stackoverflow.com/q/49082093
tags question: http://stackoverflow.com/q/49048533

http://stackoverflow.com/a/49100105
has body: from textwrap import dedent def add_new_variable(variables): name = input('Enter a name for the new variable: ') value = get_number( msg='Enter a value for the new variable: ', num_type=float ) return variables + [(name, value)] def add_to_existing_variable(variables): result = list(variables) for i, (k, v) in enumerate(variables, start=1): print('{}) {} = {}'.format(i, k, v)) variable = get_number( msg='Choose a variable to add to: ', num_type=int, minimum=1, maximum=len(variables) ) amount = get_number( msg='Enter a value to add: ', num_type=float ) prev_name, prev_value = result[variable - 1] result[variable - 1] = (prev_name, prev_value + amount) return result def get_menu_option(): menu_options = dedent(""" 1) Add to existing variable 2) Add a new variable """) print(menu_options) return get_number( msg='Choose an option: ', num_type=int, minimum=1, maximum=2 ) def get_number(msg, num_type, minimum=float('-inf'), maximum=float('inf')): while True: try: number = num_type(input(msg)) except ValueError: pass else: if minimum &lt;= number &lt;= maximum: return number def main(): variables = [ ('A', 0), ('B', 0), ('C', 0) ] while True: menu_option = get_menu_option() if menu_option == 1: variables = add_to_existing_variable(variables) else: variables = add_new_variable(variables) if __name__ == '__main__': main()
type: Answer
answers question: http://stackoverflow.com/q/49099798
score: 0

http://stackoverflow.com/comment/85151590
has text: @mzjn Tnx for info... New on stackoverflow and didn't know everything yet...
type: Comment
comment on: http://stackoverflow.com/q/49053029
score: 0
type: QuestionComment

tkinter-entry
tags question: http://stackoverflow.com/q/48966649
tags question: http://stackoverflow.com/q/48991884
tags question: http://stackoverflow.com/q/49100146
tags question: http://stackoverflow.com/q/49007295
tags question: http://stackoverflow.com/q/49035753
tag name: tkinter-entry
tags question: http://stackoverflow.com/q/49001710
type: Tag
tags question: http://stackoverflow.com/q/48977312

http://stackoverflow.com/comment/85184525
comment on: http://stackoverflow.com/a/49084672
score: 0
type: AnswerComment
type: Comment
has text: @Olaf I actually gave an answer to your comment about answering an off topic question: I am not sure it is off topic. The meta link you gave gives absolutely no right to decide for me what I am or am not allowed to do. Please refrain from appointing yourself to the position of a SO censor.

http://stackoverflow.com/comment/119535214
score: 1
type: AnswerComment
type: Comment
has text: @kjohnsen editable install should work - most probably the module in question is not included in the list of distributed modules. If you want, ask another question with a [mcve] and ping me in the comments here.
comment on: http://stackoverflow.com/a/49033954

http://stackoverflow.com/q/49041038
has comment: http://stackoverflow.com/comment/85088920
answer count: 1
downvote count: 0
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/49062054
has comment: http://stackoverflow.com/comment/85087515
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85093705
has comment: http://stackoverflow.com/comment/85090311
score: 1
has comment: http://stackoverflow.com/comment/85087415
upvote count: 1
type: Question
tagged with: encoding
has body: I have a 'csv' file that contains columns of str, int, and datetime. When I open the file using pd.read_csv(file_name, encoding='utf-8'), I get the following errors: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa5 in position 109: invalid start byte I tried using the code below but I get a 'str' type outcome of all of my columns, each value separated by a comma. file = open(file_name, "r", encoding='utf-8', errors='ignore') df = file.read() How do I read the file as a dataframe or transform the outcome of the code above into a dataframe?
has title: File Cannot be Read: UnicodeDecodeError

http://stackoverflow.com/q/49067869
has comment: http://stackoverflow.com/comment/85173812
has comment: http://stackoverflow.com/comment/85213542
has comment: http://stackoverflow.com/comment/85197032
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 7
has comment: http://stackoverflow.com/comment/85141322
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85153372
has answer: http://stackoverflow.com/a/64820371
has comment: http://stackoverflow.com/comment/86564619
score: 7
type: Question
has title: Tensorflow, negative KL Divergence
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85141229
favorite count: 0
tagged with: statistics
tagged with: python
has comment: http://stackoverflow.com/comment/85143153
has body: I am working with a Variational Autoencoder Type model and part of my loss function is the KL divergence between a Normal Distribution with mean 0 and variance 1 and another Normal Distribution whose mean and variance are predicted by my model. I defined the loss in the following way: def kl_loss(mean, log_sigma): normal=tf.contrib.distributions.MultivariateNormalDiag(tf.zeros(mean.get_shape()), tf.ones(log_sigma.get_shape())) enc_normal = tf.contrib.distributions.MultivariateNormalDiag(mean, tf.exp(log_sigma), validate_args=True, allow_nan_stats=False, name="encoder_normal") kl_div = tf.contrib.distributions.kl_divergence(normal, enc_normal, allow_nan_stats=False, name="kl_divergence") return kl_div The input are unconstrained vectors of length N with log_sigma.get_shape() == mean.get_shape() Now during training I observe a negative KL divergence after a few thousand iterations up to values of -10. Below you can see the Tensorboard training curves: KL divergence curve Zoom in of KL divergence curve Now this seems odd to me as the KL divergence should be positive under certain conditions. I understand that we require "The K-L divergence is only defined if P and Q both sum to 1 and if Q(i) > 0 for any i such that P(i) > 0." (see https://mathoverflow.net/questions/43849/how-to-ensure-the-non-negativity-of-kullback-leibler-divergence-kld-metric-rela) but I don't see how this could be violated in my case. Any help is highly appreciated!
tagged with: distribution

http://stackoverflow.com/q/49082196
downvote count: 0
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/85172417
has body: I have a model Banks. and I have six entities in it. This is my prefetch code. queryset = Banks.objects.all().prefetch_related('field1','field2') when I enter new entity into my Banks model and get the data, I still get only the old data. The newly added entity is not getting reflected when I download the data.
tagged with: django-models
answer count: 1
tagged with: django-rest-framework
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/49085443
has comment: http://stackoverflow.com/comment/85172343
tagged with: python
upvote count: 4
has title: Django prefetch_related cache not reflecting the changes
tagged with: python-3.x

http://stackoverflow.com/q/48987959
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84984588
has comment: http://stackoverflow.com/comment/84984819
score: 23
upvote count: 23
type: Question
has answer: http://stackoverflow.com/a/67491229
accepted answer: http://stackoverflow.com/a/48991515
has body: I have created an ANN with numerical inputs and a single categorical output which is one hot encoded to be 1 of 19 categories. I set my output layer to have 19 units. I don't know how to perform the confusion matrix now nor how to classifier.predict() in light of this rather than a single binary output. I keep getting an error saying classification metrics can't handle a mix of continuous-multioutput and multi-label-indicator targets. Not sure how to proceed. #Importing Datasets dataset=pd.read_csv('Data.csv') x = dataset.iloc[:,1:36].values # lower bound independent variable to upper bound in a matrix (in this case only 1 column 'NC') y = dataset.iloc[:,36:].values # dependent variable vector print(x.shape) print(y.shape) #One Hot Encoding fuel rail column from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_y= LabelEncoder() y[:,0]=labelencoder_y.fit_transform(y[:,0]) onehotencoder= OneHotEncoder(categorical_features=[0]) y = onehotencoder.fit_transform(y).toarray() print(y[:,0:]) print(x.shape) print (y.shape) #splitting data into Training and Test Data from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.1,random_state=0) #Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() #x_train = sc.fit_transform(x_train) #x_test=sc.transform(x_test) y_train = sc.fit_transform(y_train) y_test=sc.transform(y_test) # PART2 - Making ANN, deep neural network #Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense #Initialising ANN classifier = Sequential() #Adding the input layer and first hidden layer classifier.add(Dense(activation= 'relu', input_dim =35, units=2, kernel_initializer="uniform"))#rectifier activation function, include all input with one hot encoding #Adding second hidden layer classifier.add(Dense(activation= 'relu', units=2, kernel_initializer="uniform")) #rectifier acti…
possible better answer: http://stackoverflow.com/a/67491229
has title: classification metrics can't handle a mix of continuous-multioutput and multi-label-indicator targets
answer count: 2
has comment: http://stackoverflow.com/comment/84984762
downvote count: 0
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/84984490
has comment: http://stackoverflow.com/comment/84985131
has comment: http://stackoverflow.com/comment/84986569
has comment: http://stackoverflow.com/comment/84984292
has answer: http://stackoverflow.com/a/48991515

http://stackoverflow.com/comment/85344922
score: 1
comment on: http://stackoverflow.com/a/49061904
type: Comment
has text: Thanks for the suggestion and guidance
type: AnswerComment

http://stackoverflow.com/a/49105370
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49074392
upvote count: 2
has body: I think you would better to modify the process of grabbing input and output. Actually according to your REGISTER_OP, it is not reference input, so context-&gt;mutable_input(0, true) would be context-&gt;input(0) Also, setting the output would be changed to context-&gt;set_output(0, context-&gt;input(0)) I think it will work after setting the output.
score: 2
answers question: http://stackoverflow.com/q/49074392

http://stackoverflow.com/q/49090416
tagged with: gil
favorite count: 0
type: Question
has body: The GIL locks cores so that threads cannot run in parallel. Why is this the case? There is little information about this online.
tagged with: python
has comment: http://stackoverflow.com/comment/85186378
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/85186446
has title: Why is the Python interpreter not thread safe?
upvote count: 2
tagged with: multithreading
tagged with: thread-safety
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49090434
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85105542
score: 0
type: AnswerComment
has text: @Evk using ASCII resulted in *lost* data, ie the `?` character. If you mean the OP shouldn't have tried to decode the buffer, yes. He probably got another error (that's way too short for AES) and thought the buffer didn't contain the correct data. Instead of comparing byte values, he converted it to text using the wrong codepage
comment on: http://stackoverflow.com/a/49050424
type: Comment

http://stackoverflow.com/comment/85283901
comment on: http://stackoverflow.com/a/49118914
has text: @Rodrigues: I filed a bug report to address the missing dependencies, and updated my answer with a work-around for now.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48971290
has answer: http://stackoverflow.com/a/48972632
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to make a Firefox driver using Selenium. However, I am having trouble creating the driver in the first place. I try to make it like this: from selenium import webdriver driver = webdriver.Firefox() Running this opens a warning window saying: "Your Firefox profile cannot be loaded. It may be missing or inaccessible." Then the following error is raised: 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 162, in __init__ keep_alive=True) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 1 I have tried several solutions, including: I placed the geckodriver in the PATH Typing out the path name (driver = webdriver.Firefox(firefox_profile="default")) Specifying the profile path (as in the answer on https://groups.google.com/forum/#!topic/selenium-users/Q8CpIFiZcBk) Creating a new Firefox profile and attempting that path instead I am using Python 3.6.4 and Firefox 58.0.1. Edit: While there are several similar questions, most of them relate either to tor, or result in a different error. Also, I forgot to mention but I am using Debian Linux
tagged with: python
upvote count: 7
tagged with: selenium-webdriver
has title: Python Selenium Firefox Profile Missing error
score: 7
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/84948062
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/17580730
has comment: http://stackoverflow.com/comment/84958965
duplicate of: http://stackoverflow.com/q/17580730
favorite count: 0

http://stackoverflow.com/comment/85187235
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49090796
has text: @user2357112 I create a wrapper which allows one to access an object's `__getitem__` method through `__getattribute__`. `wrap_obj.key == obj[key]` However, I want to know if the value returned came from `__getitem__` or was an attribute of `obj`. One solution seems to be to call `isinstance` on the returned value to see what it is.
score: 0

http://stackoverflow.com/comment/85439975
comment on: http://stackoverflow.com/a/49099276
type: AnswerComment
score: 0
type: Comment
has text: The problem of this solution is I need to stop_recording, and than start_recording. This will slow the camera. Alre each time I need to create a new name for recordintg

http://stackoverflow.com/comment/85137874
comment on: http://stackoverflow.com/q/49066351
has text: Hi Ayza. Please write your code and approach for your problem, then only people will be able to help you.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48981416
answer count: 3
has answer: http://stackoverflow.com/a/48981494
favorite count: 0
has title: Find IPv4 and ignore IPv6 IP addresses with Python
has answer: http://stackoverflow.com/a/66770236
has answer: http://stackoverflow.com/a/48981484
accepted answer: http://stackoverflow.com/a/48981484
has comment: http://stackoverflow.com/comment/84967909
has comment: http://stackoverflow.com/comment/84967905
linked to: http://stackoverflow.com/q/1894269
tagged with: python
has body: I have a strings as mentioned in the below format, i would like to remove only IPv6 address from the string and print only the IPv4 address as a string. I tried with sub string and regex , but I am unable to get correct regex for this string. Could any one help to provide the solution. Actual format of Inputs string given to python program as below format (square brackets included), Where Ipv6 address can be present either at starting or ending of the string. ['fe80::2ff:fe21:30f/64', '17.2.1.2/24'] ['fe80::2ff:fee4:2b43/64', '17.2.1.3/24'] ['17.2.10.2/24', 'fe80::2ff:fe42:f251/64] ['192.168.4.1/30', 'fe80::2ff:fe19:cdd7/64'] ['fe80::2ff:fe1e:e328/64', '17.2.4.1/24'] Output should be display as only ipv4 address as strings "17.2.1.2/24" "17.2.1.3/24" "17.2.10.2/24" "192.168.4.1/30" "17.2.4.1/24"
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48981494
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/84967906
upvote count: 2

http://stackoverflow.com/q/49095497
linked to: http://stackoverflow.com/q/14547916
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85196284
favorite count: 0
tagged with: parsing
has body: I'm working with the following JSON structures { "-L6Tr0Wl5fuG3tDgUPCa": { "List": "{'x': [0.02245, 0.02196], 'y': [0.96941, 0.97014], 'z': [0.05344, 0.05368]}", "Index": "17361" }, "-L6Tr4j05NV6BJKcaRSe": { "List": "{'x': [0.03196, 0.01537], 'y': [0.96795, 0.96966], 'z': [0.05051, 0.04929]}", "Index": "17362" } } The name of each entry is random (e.g. L6Tr0Wl5fuG3tDgUPCa) that is generated by firebase whenever we push a new entry. What is the best way to parse and iterate through each entry of such a JSON file in python? The file is huge with a couple of thousands of such entries.
has title: Parsing Firebase JSON with Python
tagged with: firebase-realtime-database
tagged with: python
tagged with: firebase
has answer: http://stackoverflow.com/a/49096975
upvote count: 3
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
has comment: http://stackoverflow.com/comment/85195982
has comment: http://stackoverflow.com/comment/97941991
type: Question
has comment: http://stackoverflow.com/comment/85195957

http://stackoverflow.com/comment/85033462
type: QuestionComment
has text: I should mention that Python does not convert to numeric type implicitly, while it *does* convert implicitly to strings for some operations. For that, you do need to override all the methods (`__add__()` etc. as well as `__eq__()` etc.). You could write a mixin class for that so as not to have to repeat yourself.
comment on: http://stackoverflow.com/q/49014127
score: 0
type: Comment

http://stackoverflow.com/q/48972231
tagged with: django
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/84953238
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84949797
has comment: http://stackoverflow.com/comment/84950837
has comment: http://stackoverflow.com/comment/84953933
has comment: http://stackoverflow.com/comment/84953457
tagged with: django-custom-user
downvote count: 0
has comment: http://stackoverflow.com/comment/84953071
favorite count: 0
has comment: http://stackoverflow.com/comment/84953143
has comment: http://stackoverflow.com/comment/84953519
has body: I wanted to add some more fields to Django's default User model I imported AbstractUser and inherit it in my User class and added my app to INSTALLED_APPS and added this line in settings.py AUTH_USER_MODEL='music.User' in which music is my app's name and User is my model name but in migration, i got this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'music.user', but app 'music' doesn't provide model 'user'. what should I do?
type: UnansweredQuestion
has title: Error in Customizing Default User Class in Django

http://stackoverflow.com/comment/85187227
type: Comment
type: QuestionComment
has text: What kind of Python object is `lizard`?
score: 0
comment on: http://stackoverflow.com/q/49090796

http://stackoverflow.com/comment/85175266
has text: Have you tried using `asyncio.set_event_loop`?
comment on: http://stackoverflow.com/q/49084650
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49072394
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85150596
type: Answer
accepted answer of: http://stackoverflow.com/q/49072154
answers question: http://stackoverflow.com/q/49072154
has body: You have a circular import. app.models tries to import app to resolve the name bcrypt: File "C:/Users/Orbit/RPOSS/app/models.py", line 1, in &lt;module&gt; from app import bcrypt The app/__init__.py file first imports another module however, app.views: File "C:\Users\Orbit\RPOSS\app\__init__.py", line 7, in &lt;module&gt; from app.views import Rmod This module wants to import from app.models: File "C:\Users\Orbit\RPOSS\app\views.py", line 3, in &lt;module&gt; from app.models import Employee This is the file you started with, but you probably ran it as a script so was imported by Python as __main__, meaning Python will import it again under the app.model name. But now you have a problem, because it imports app again: File "C:\Users\Orbit\RPOSS\app\models.py", line 1, in &lt;module&gt; from app import bcrypt At this point, app has already been created, but has not yet completed importing. The name bcrypt has not yet been assigned to. You need to move the name bcrypt to a line before you import app.model. Move the line from app.views import Rmod to below the bcrypt = Bcrypt(app) line, or use a separate function to import your blueprints later on. I prefer using an Application Factory to set up the app and blueprints. Alter your __init__ method to import blueprints in the factory function.
score: 3
upvote count: 3

http://stackoverflow.com/q/49035107
type: Question
has comment: http://stackoverflow.com/comment/85100428
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49048125
has comment: http://stackoverflow.com/comment/85090947
has body: I am pretty new with scikitlearn and right now I am struggling with the preprocessing stage. I have the following categorical features (I parsed a JSON file and place it in a dictionary) so: dct['alcohol'] = ["Binge drinking", "Heavy drinking", "Moderate consumption", "Low consumption", "No consumption"] dct['tobacco']= ["Current daily smoker - heavy", "Current daily smoker", "Current on-and-off smoker", "Former Smoker", "Never Smoked", "Snuff User"] dct['onset'] = "Gradual", "Sudden"] My first approach is to convert it first to integers with label enconder and then to the one-hot-coding method: OH_enc = sklearn.preprocessing.OneHotEncoder(n_values=[len(dct['alcohol']),len(dct['tobacco']),len(dct['onset'])]) le_alc = sklearn.preprocessing.LabelEncoder() le_tobacco = sklearn.preprocessing.LabelEncoder() le_onset = sklearn.preprocessing.LabelEncoder() le_alc.fit(dct['alcohol']) le_tobacco.fit(dct['tobacco']) le_onset.fit(dct['onset']) list_patient = [] list_patient.append(list(le_alc.transform(['Low consumption']))) list_patient.append(list(le_tobacco.transform(['Former Smoker']))) list_patient.append(list(le_onset.transform(['Sudden']))) list1 = [] list1.append(np.array(list_patient).T[0][:]) list1.append([1,2,0]) OH_enc.fit(list1) print(OH_enc.transform([[4,2,0]]).toarray()) So eventually if you OHE (4,2,0) you get : [[0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 1. 0.]] Which is what I want since the first 5 columns refers to the "alcohol" feature, the 6 next columns refers to tobacco, and the last 2 columns refers to the onset feature. However, let's assume that one example could have more than one value in one feature. Let's say one example gets "Binge drinking" and "Heavy drinking" from the alcohol feature. Then, if you OHE ([0,1],2,0) you would get: [[1. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 1. 0.]] This last step I do not know how to code it with sklearn.preprocessing.OneHotEncoder. I mean, how can I code 2 values in one feature per example? I know that there might be a better wa…
has title: one-hot encoding more than 1 value in each feature categorical data
answer count: 1
tagged with: scikit-learn
tagged with: data-science
accepted answer: http://stackoverflow.com/a/49048125
score: 0
tagged with: categorical-data
tagged with: python
tagged with: machine-learning

http://stackoverflow.com/comment/85150688
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49072392
has text: Actually, I don't think the OP is using that `User` model at all, so I would remove those imports to avoid confusion.

object-detection
tags question: http://stackoverflow.com/q/49013181
tags question: http://stackoverflow.com/q/49031102
tags question: http://stackoverflow.com/q/49028608
tag name: object-detection
tags question: http://stackoverflow.com/q/49102978
tags question: http://stackoverflow.com/q/49048262
tags question: http://stackoverflow.com/q/49081043
type: Tag

http://stackoverflow.com/a/49034506
downvote count: 0
upvote count: 1
has body: If you want to do this in a one-liner: INPUT: output = [[k.lower() for k in [' '.join(re.findall(r'[^\]\[.!-][A-z0-9]+[^\]\[.!-]', j)) for j in i]] for i in csvarticles] OUTPUT: [['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension in the pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', 'la nouvelle']] REGEX: [^\]\[.!-][A-z0-9]+[^\]\[.!-]
has comment: http://stackoverflow.com/comment/85099694
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49034230

http://stackoverflow.com/a/49041152
answers question: http://stackoverflow.com/q/49041028
downvote count: 0
score: 1
type: Answer
has body: you must have installed numpy manually using setup.py and apt pkg as well you could do: import sys print(sys.path) sys.path.remove('/usr/lib/python/path/2/numpy') in your app/__init__.py set PYTHONHOME to your preference. you could also use virtualenv to keep multiple python environments and switch between them.
upvote count: 1

http://stackoverflow.com/a/49057696
upvote count: 3
answers question: http://stackoverflow.com/q/49057589
accepted answer of: http://stackoverflow.com/q/49057589
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
has body: You can simply append two tables together: df_train_scaled = df_train.iloc[:,1:].replace(['Ex','Gd','TA','Fa','Po'], [5, 4, 3, 2, 1]) df_train_scaled.columns = [x + "_new" for x in df_train_scaled.columns] pd.concat([df_train, df_train_scaled], axis=1)

http://stackoverflow.com/comment/85067642
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165973/discussion-between-user177324-and-ascripter).
comment on: http://stackoverflow.com/a/49019425
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85131228
type: Comment
comment on: http://stackoverflow.com/q/49062970
has text: [https://stackoverflow.com/help/mcve](https://stackoverflow.com/help/mcve)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85108488
has text: Also don't assign values in the getters. Please read up on python properties
comment on: http://stackoverflow.com/q/49051965
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/85102286
has text: What exactly is "unexpected behavior"? There is no such formal term.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/49048501
type: AnswerComment

http://stackoverflow.com/a/49004058
answers question: http://stackoverflow.com/q/49003113
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85012562
has body: You should not specify the field explicitly inthe ModelForm because it is already defined in the model. class StudentDataForm(forms.ModelForm): class Meta: model = StudentData fields = ('enrolled', ) That's for the form definition. If you want to pass initial values then instantialize it like form = StudentDataForm(initial={'enrolled': True}) and it will magically(not so) create the ModelForm instance with initially enrolled field checked. Now in template all you have to render this form is (You must pass the form in the template render in context context={'form': form}) ... {{ form }} ... and that will render the form but if you want to render it manually, do it like this ... {{ form.enrolled }} ... and it will render only the checkbox. Keep in mind that you must nest it in &lt;form&gt; tags and add here a submit button. more resources: Model Form | Django docs Providing initial values | Django docs

http://stackoverflow.com/comment/85063343
type: QuestionComment
type: Comment
has text: Possible duplicate of [Flatten nested Python dictionaries, compressing keys](https://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys)
score: 1
comment on: http://stackoverflow.com/q/49029562

vscode-debugger
type: Tag
tags question: http://stackoverflow.com/q/48984449
tag name: vscode-debugger

http://stackoverflow.com/comment/85180939
score: 0
has text: Yes, you can replace `1 - alpha` with the actual value. I wrote it that way because it is common to refer to the significance level of the t-test as "alpha" (e.g. https://onlinecourses.science.psu.edu/statprogram/node/137, https://onlinecourses.science.psu.edu/statprogram/node/137).
type: Comment
comment on: http://stackoverflow.com/a/49086079
type: AnswerComment

http://stackoverflow.com/comment/85238705
type: QuestionComment
comment on: http://stackoverflow.com/q/49116693
score: 0
has text: Know nothing about python's dataframes, but it doesn't look as if your python script is outputting anything to `stdout` at all?
type: Comment

http://stackoverflow.com/comment/85197766
type: Comment
type: QuestionComment
has text: Where is your initial attempt that failed?
score: 1
comment on: http://stackoverflow.com/q/49096235

http://stackoverflow.com/a/49057201
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48997083
has body: The error is caused by this issue submitted to the widget's Github page, and has not yet been solved. So I switched to django-bootstrap-datepicker-plus, and it is working in my DJango version 2.0.2 just fine. But the question remains that needs to be answered. What is a reversible object? Why we get this Error? The error is raised by the python built-in function reversed, that takes a sequence as only parameter and reverses the sequence. reversed() Parameters seq - sequence that should be reversed. Could be an object that supports sequence protocol (__len__() and __getitem__() methods) as tuple, string, list or range Could be an object that has implemented __reversed__() So all sequences (eg. lists, tuples) are reversible. But to make an object reversible we need to implement a method named __reversed__, or both __len__() and __getitem__() methods. If we pass an object to reversed() function which does not fulfill any of the above criteria, it will raise an Exception TypeError - object is not reversible. DJango 2.0 use this reversed() function to the assets added by any widget. As the JSFiles object used in the above widget does not implement reversible criteria, the error is raised.
answers question: http://stackoverflow.com/q/48997083

http://stackoverflow.com/q/49086911
favorite count: 0
score: -3
tagged with: python
upvote count: 1
has title: Function of print() in a particular Python Tutorial example
has answer: http://stackoverflow.com/a/49086966
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49087019
has body: The function fib() below taken from chapter 4.6 in The Python Tutorial includes at the end of the definition a line containing print() with no apparent reason since the same function without that line -fib0()- produces the same output. So what is the reason of including that in the function definition? Which function between fib() and fib0() is more efficient? # -*- coding: utf-8 -*- from __future__ import print_function def fib(n): """print a fibonacci series up to n""" a, b = 0, 1 while a &lt; n: print(a, end=', ') a, b = b, a+b print() def fib0(n): """print a fibonacci series up to n""" a, b = 0, 1 while a &lt; n: print(a, end=', ') a, b = b, a+b fib(2000) fib0(2000) Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
type: Question
answer count: 2
downvote count: 4
accepted answer: http://stackoverflow.com/a/49086966
possible better answer: http://stackoverflow.com/a/49087019

http://stackoverflow.com/comment/85194289
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49094309
has text: Can you copy all the code an paste it in your reply? Also try just running this code i made for you to see if it works.
type: AnswerComment

http://stackoverflow.com/comment/85180100
has text: Improve the title of the question, it is very general. It also shows what you have tried. read [ask]
type: QuestionComment
comment on: http://stackoverflow.com/q/49087309
type: Comment
score: 2

http://stackoverflow.com/q/49108793
favorite count: 0
score: 0
answer count: 3
tagged with: python
has body: how can I split strings into continuous sub strings e.g: string_inputs: AAAATTTT ATATATAT output_needed: AA,AA,AA,AT,TT,TT,TT
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49109003
has title: how can I split strings into continuous substrings e.g: string_inputs: IN PYTHON3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49109018
has comment: http://stackoverflow.com/comment/85222434
has answer: http://stackoverflow.com/a/49109088
has comment: http://stackoverflow.com/comment/85222609
type: Question

http://stackoverflow.com/q/49079440
answer count: 2
has title: Access an element of a binary number in python
has answer: http://stackoverflow.com/a/49079560
has comment: http://stackoverflow.com/comment/85165082
favorite count: 0
upvote count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49079722
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/85164838
score: 2
has comment: http://stackoverflow.com/comment/85165511
has body: Given such a binary number, I would like to access each element in the number. For example, I use the following code to access the 3rd element: bin(125) # '0b1111101' bin(125)[::-1][3] Yes, it works. But I am not sure whether this is a good way or not. It looks dangerous and I wonder if there are other better, more efficient, ways to access each element of binary numbers.
has comment: http://stackoverflow.com/comment/85165375
type: Question
has comment: http://stackoverflow.com/comment/85164862

http://stackoverflow.com/comment/140141204
comment on: http://stackoverflow.com/a/51163124
type: AnswerComment
score: 0
type: Comment
has text: Helpful but should be `.Popup()` not `.PopUp()`. Also this solution helps with non-HTML characters in popup strings but does not address the problem with "too many markers"

http://stackoverflow.com/comment/85245975
comment on: http://stackoverflow.com/q/49120113
type: Comment
type: QuestionComment
has text: @vaultah only the leading space is essential, although the trailing space is nice for symmetry perhaps
score: 2

http://stackoverflow.com/q/48986874
has comment: http://stackoverflow.com/comment/100559651
has comment: http://stackoverflow.com/comment/108037952
has comment: http://stackoverflow.com/comment/99170739
has comment: http://stackoverflow.com/comment/107962533
has comment: http://stackoverflow.com/comment/84979752
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/97003791
linked to: http://stackoverflow.com/q/55411666
has title: How to use py_func with a function that returns dict
has body: I'm writing an input pipeline using tf.data.Dataset. I'd like to use python code to load and transform my samples, the code returns a dictionary of tensors. Unfortunately I don't see how I can define that as the output type that is passed to tf.py_func. I have a workaround where my function returns list of tensors instead of a dictionary, but it makes my code less readable as I have 4 keys in that dict. The code looks somehow as follows file_list = .... def load(file_name): return {"image": np.zeros(...,dtype=np.float32), "label": 1.0} # there is more labels, in the original code ds = tf.data.Dataset.from_tensor_slices(file_list) ds.shuffle(...) out_type = [{'image':tf.float32, "label":tf.float32 }] # ???? ds.map(lambda x: tf.py_func(load, [x], out_type)) ds.batch(...) ds.prefetch(1)
tagged with: tensorflow
score: 12
type: Question
has comment: http://stackoverflow.com/comment/90654619
has comment: http://stackoverflow.com/comment/107957211
upvote count: 12
has answer: http://stackoverflow.com/a/61025155
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/98432372
tagged with: tensorflow-datasets
favorite count: 0

http://stackoverflow.com/a/49001020
has body: Try the below if you need recursion. def presPosition(pres, preslst, i=0): if i == len(preslst): return "Pres Not Found!" if preslst[i][0] == pres: return i else: return presPosition(pres, preslst, i+=1) In your code, you are removing the first element, therefore your index will always be 0.
has comment: http://stackoverflow.com/comment/85007110
has comment: http://stackoverflow.com/comment/85007095
answers question: http://stackoverflow.com/q/49000947
score: 0
type: Answer

http://stackoverflow.com/comment/85134488
comment on: http://stackoverflow.com/a/49064734
has text: @VikashB - it is input data
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84957001
score: 0
comment on: http://stackoverflow.com/q/48976017
type: Comment
type: QuestionComment
has text: You must declare it `global` with `global gameMenuText` at the beginning of your `gameMenuApp` function.

http://stackoverflow.com/comment/85213643
type: QuestionComment
has text: @Iosif Livadaru Thanks for accepting! An upvote would also be appreciated :P
comment on: http://stackoverflow.com/q/49104049
score: 0
type: Comment

http://stackoverflow.com/comment/123475797
type: Comment
has text: @zabop The link is updated to a valid one
type: AnswerComment
comment on: http://stackoverflow.com/a/49047015
score: 0

http://stackoverflow.com/a/49082697
accepted answer of: http://stackoverflow.com/q/49082679
has body: This should help. for i in response['Images']: print(i['Name']) print(i['ImageId']) Output: aws-elasticbeanstalk-amzn-2018.01.05.x86_64-WindowsServer2012R2-hvm-201801102240 ami-c3554ea7 aws-elasticbeanstalk-amzn-2018.01.12.x86_64-WindowsServer2012R2-hvm-201802141022 ami-dd15f0ba
answers question: http://stackoverflow.com/q/49082679
has comment: http://stackoverflow.com/comment/85170786
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/49097944
has answer: http://stackoverflow.com/a/49098062
upvote count: 2
score: 2
type: AnsweredQuestion
has title: Subtract from one column of a numpy array
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49098062
answer count: 1
tagged with: arrays
downvote count: 0
has body: I have a Numpy array of the form: 40002 1511863545 40000 1511863546 156 1511863547 40005 1511863547 40003 1511863548 40008 1511863549 340 1511863550 40011 1511863550 ... The first column is data, the second timestamps. The data is in two parts, separated by a gap of 40000. What I need is two datasets: 156 1511863547 340 1511863550 ... and: 2 1511863545 0 1511863546 5 1511863547 3 1511863548 8 1511863549 11 1511863550 How can I, Split the data according to the value in the first column? Subtract 40000 from the first column of the second new dataset (leaving the timestamps intact)?
tagged with: python
favorite count: 0

http://stackoverflow.com/a/48965757
score: 1
upvote count: 1
has body: You have installed Python projects with compiled components that are loaded into the Python binary. Those components are conflicting with the embedded Python version of your software package (which may not be able to load them). Because you used the --user switch to install these packages there is still a way out to recover your installation. The packages were all installed into the site.USER_SITE location, which means you can remove them again, manually. First, you need to run Python with a switch that disables loading code from that location. You can try to do this with either the -s switch (which disables the USER_SITE option) or the -I switch (enabling isolated mode, ignoring environment variables and the USER_SITE option), to verify that disabling these options actually gives you a working Python prompt: path/to/software/python -s # or -I When this works, you can run the site module as a script, to print out where the USER_SITE directory is: path/to/software/python -s -m site # or -I -m site Look for the USER_SITE: &lt;path&gt; line, it should end in site-packages. Then, move the contents of that directory somewhere else (to keep as a backup). Then try to run Python without the -s / -I switch again.
has comment: http://stackoverflow.com/comment/84953466
accepted answer of: http://stackoverflow.com/q/48965493
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48965493
has comment: http://stackoverflow.com/comment/84953454
type: Answer
has comment: http://stackoverflow.com/comment/84953261

http://stackoverflow.com/q/49052142
has comment: http://stackoverflow.com/comment/85109207
linked to: http://stackoverflow.com/q/4690585
type: UnansweredQuestion
has title: Turn `matplotlib.pyplot` plot into `Flowable` object to embed in ReportLab PDF without external libraries
tagged with: python
has body: Is there a way to turn a matplotlib.pyplot plot into a Flowable object within reportlab so that I can render it within a pdf? My question is very similar to the question asked here. However, I am limited because I am working on a system where I can only use a certain set of libraries. These are: The libraries installed with Anaconda 2 reportlab Is this possible with the set of packages that I have? EDIT: I would like to avoid saving the plot as a png
answer count: 0
tagged with: matplotlib
tagged with: reportlab
linked to: http://stackoverflow.com/q/3448365
linked to: http://stackoverflow.com/q/5835795
type: Question
has comment: http://stackoverflow.com/comment/85110009
score: 0

http://stackoverflow.com/comment/84961410
type: Comment
type: QuestionComment
has text: What is `names['name']=n` supposed to accomplish? Given what follows, it ought to be data about a person whose name is "name".
score: 0
comment on: http://stackoverflow.com/q/48978063

django-1.9
tags question: http://stackoverflow.com/q/48969292
tag name: django-1.9
type: Tag

http://stackoverflow.com/comment/84960104
has text: @NathanVērzemnieks between 6 - 12 times is ok. The maximum nr of times to run the function is 15 times per second.
comment on: http://stackoverflow.com/a/48976411
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49001647
has answer: http://stackoverflow.com/a/49001890
accepted answer: http://stackoverflow.com/a/49001890
has body: I noticed that exceptions that are handled do not result in a call to sys.excepthook... which makes sense in retrospect. But, how do I log or otherwise customize the way that handled exceptions are dealt with? When this code executes... try: 1/0 except: pass I would like to be able to log the fact that a ZeroDivisionError was handled. Is there a way to do this?
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has title: sys.excepthook -vs- handled exceptions
type: Question
linked to: http://stackoverflow.com/q/6598053
tagged with: exception
upvote count: 1
tagged with: python
answer count: 1

optimization
tags question: http://stackoverflow.com/q/49010360
tags question: http://stackoverflow.com/q/49054768
tags question: http://stackoverflow.com/q/49088752
tags question: http://stackoverflow.com/q/49056911
tags question: http://stackoverflow.com/q/48964555
tags question: http://stackoverflow.com/q/49094917
tags question: http://stackoverflow.com/q/48989632
tag name: optimization
tags question: http://stackoverflow.com/q/49047555
tags question: http://stackoverflow.com/q/49015138
tags question: http://stackoverflow.com/q/49018116
tags question: http://stackoverflow.com/q/48997698
tags question: http://stackoverflow.com/q/49040843
tags question: http://stackoverflow.com/q/48968242
tags question: http://stackoverflow.com/q/49098713
tags question: http://stackoverflow.com/q/49094774
type: Tag

http://stackoverflow.com/comment/85372362
type: AnswerComment
comment on: http://stackoverflow.com/a/49116828
score: 0
type: Comment
has text: That brings in new information that makes this simpler. See updated answer.

http://stackoverflow.com/a/48999325
answers question: http://stackoverflow.com/q/48995284
accepted answer of: http://stackoverflow.com/q/48995284
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85039310
has body: You need to also set an explicit height for each contained widget, so that the GridLayout can add them together to calculate its minimum height. For instance, in your example you could add the following lines to each button: size_hint_y: None height: dp(30)
type: Answer
has comment: http://stackoverflow.com/comment/85039571
upvote count: 1
has comment: http://stackoverflow.com/comment/85464945

http://stackoverflow.com/a/49053442
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49053296
has body: S, X and T are all scalar. I am assuming you want to plot a vector against vector. I think you are trying to do this: import math import matplotlib.pyplot as mpl import numpy as np Q = 13.6 m_e = 9.11e-31 k = 8.6e-5 c = 3e8 eta = 4e-10 S=[] X=[] for T in np.arange(3000,4500): tmp=3.84*eta*((k*T)/(m_e*c**2))**(3/2)*(Q/(k*T)) S.append(tmp) X.append((-1 + np.sqrt(1+(4*tmp)))/(2*tmp)) %matplotlib inline mpl.plot(S, X) mpl.show()

http://stackoverflow.com/q/49051706
has answer: http://stackoverflow.com/a/49051985
accepted answer: http://stackoverflow.com/a/49051985
has comment: http://stackoverflow.com/comment/85108247
has title: What's new in python 3.7 about circular imports?
answer count: 1
favorite count: 0
tagged with: python-3.7
tagged with: python
has body: This is a point from python 3.7 changelog. bpo-30024: Circular imports involving absolute imports with binding a submodule to a name are now supported. What is the example of code that wouldn't work in 3.6 but works now?
score: 2
upvote count: 3
downvote count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/85121243
type: Comment
score: 0
type: AnswerComment
has text: Excellent! This is what I was looking for!
comment on: http://stackoverflow.com/a/48988701

http://stackoverflow.com/a/50508046
answers question: http://stackoverflow.com/q/49108809
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49108809
type: Answer
downvote count: 0
score: 6
upvote count: 6
has body: Even i was facing this problem but i figured out that even while uploading Millions of rows(19 Million to be exact) into Cassandra its didn't take much time. Coming to your problem,you can use cassandra Bulk LOADER to get your job done. EDIT 1: You can use prepared statements to help uplaod data into cassandra table while iterating through the dataFrame. from cassandra.cluster import Cluster cluster = Cluster(ip_address) session = cluster.connect(keyspace_name) query = "INSERT INTO data(date,time,open,high,low,last) VALUES (?,?,?,?,?,?)" prepared = session.prepare(query) "?" is used to input variables for item in dataFrame: session.execute(prepared, (item.date_value,item.time_value,item.open_value,item.high_value,item.low_value,item.last_value)) or for item in dataFrame: session.execute(prepared, (item[0],item[1],item[2],item[3],item[4],item[5])) What i mean is that use for loop to extract data and upload using session.execute(). for more info on prepared statements Hope this helps..

http://stackoverflow.com/a/56464737
has comment: http://stackoverflow.com/comment/99522566
has body: roleVer = 'BOT' #role to add user = ctx.message.author #user role = roleVer # change the name from roleVer to role await ctx.send("""Attempting to Verify {}""".format(user)) try: await user.add_roles(discord.utils.get(user.guild.roles, name=role)) #add the role except Exception as e: await ctx.send('There was an error running this command ' + str(e)) #if error else: await ctx.send("""Verified: {}""".format(user)) # no errors, say verified
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/49076798
upvote count: 7
type: Answer

http://stackoverflow.com/q/49033814
tagged with: seaborn
upvote count: 1
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/49034450
type: Question
tagged with: scatter-plot
has title: Python scatterplot design - select specific values of a variable for the x axis based on another columns values
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49034450
has body: I am relatively new to python and am currently trying to generate a scatterplot based off of some data using pandas &amp; seaborn. The data I'm using ('ErrorMedianScatter') is as follows (apologies for the link, I have yet to get permissions to embed images!): Image of data Each participant has two data points of interest. The mean when MissingLimb = 0 or 1 I want to create a scatterplot for participants where the x-axis represents their value for 'mean' when 'MissingLimb' = 0, and the y-axis represents their value for 'mean' when 'MissingLimb' = 1. I am using the current code so far to create a scatterplot: sns.lmplot(("mean", "mean", data=ErrorMedianScatter, fit_reg=False, hue="participant") This generates a perfectly functional, but very uninteresting, scatterplot. What I'm stuck on is creating an x-/y-axis variable that allows for me to specify that I'm interested in the mean of a participant based on the value of 'MissingLimb' column. Many thanks in advance!
favorite count: 0

http://stackoverflow.com/comment/85070973
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49033130
has text: This is not related to machine learning or natural language processing in any way.

http://stackoverflow.com/a/48970164
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84946161
has comment: http://stackoverflow.com/comment/86052906
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84947283
has comment: http://stackoverflow.com/comment/84946795
accepted answer of: http://stackoverflow.com/q/48969813
type: Answer
has comment: http://stackoverflow.com/comment/84947339
answers question: http://stackoverflow.com/q/48969813
has comment: http://stackoverflow.com/comment/85018205
has body: As you can see your foggy images have very low horizontal variance. Therefore you could compute average horizontal variance for each image. Here's a quick example: import Image import glob def slow_horizontal_variance(im): '''Return average variance of horizontal lines of a grayscale image''' width, height = im.size if not width or not height: return 0 vars = [] pix = im.load() for y in range(height): row = [pix[x,y] for x in range(width)] mean = sum(row)/width variance = sum([(x-mean)**2 for x in row])/width vars.append(variance) return sum(vars)/height for fn in glob.glob('*.png'): im = Image.open(fn).convert('L') var = slow_horizontal_variance(im) fog = var &lt; 200 # FOG THRESHOLD print ('%5.0f - %5s - %s' % (var, fog and 'FOGGY' or 'SHARP', fn)) Output: 104 - FOGGY - 00.png 298 - SHARP - 01.png 597 - SHARP - 02.png 130 - FOGGY - 03.png The images: 00.png 01.png 02.png 03.png So using numpy, instead of your code: avg_color_per_row = numpy.average(img, axis=0) avg_color = numpy.average(avg_color_per_row, axis=0) You would have something like: intensity_variance_per_row = numpy.var(img, axis=0) avg_variance = numpy.average(intensity_variance_per_row, axis=0) fog = avg_variance &lt; 200 # FOG THRESHOLD print ('%5.0f - %5s - %s' % (avg_variance, fog and 'FOGGY' or 'SHARP', filename)) (Unfortunately, I'm too lazy to install numpy on this machine, so I cannot confirm it works as well as my slow code above. If it doesn't, you might need to change numpy.var(img, axis=0) to numpy.var(img, axis=1).)

http://stackoverflow.com/comment/85038923
score: 3
comment on: http://stackoverflow.com/q/49016939
type: Comment
type: QuestionComment
has text: What is wrong? What are the actual and expected results?

http://stackoverflow.com/comment/85085894
has text: Another way that you could do it would be to create a list of synonyms, and replace `"prescribed"` with the list. A way to get around the formatting of the sentences would be to either provide templates in the code, which will be very much hardcoding, or you could count the how far the word is from the name of the medicine. But if it really becomes a problem, you might want to consider to create a default medical note format for the doctors to follow.
comment on: http://stackoverflow.com/a/49039900
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85225078
has text: I think its better to declare `testfile` as list and append the dict each time.
comment on: http://stackoverflow.com/q/49110073
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84964906
comment on: http://stackoverflow.com/a/48979813
type: Comment
has text: I like this approach. It's fairly straightforward without the seeming duplicate process, but I think Levi Lesches' reasoning may appeal to me more - readability. I am not far beyond just literate in Python (my first program language since Basic), and I just may confuse myself going back to my code later using the 'all' and 'any' approach. Or maybe not. I'll need to cogitate on it for a while ;). Thanks.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85007924
type: QuestionComment
has text: @krismath Glad to hear that!
comment on: http://stackoverflow.com/q/49000591
score: 0
type: Comment

http://stackoverflow.com/comment/85077644
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49019876
has text: People with power to just down vote without explanation is bad for learning

http://stackoverflow.com/q/49020650
score: 0
has comment: http://stackoverflow.com/comment/85046656
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: If I have a class defined as such in one file (called gui.py), (where QtWidgets is an imported module (PyQt5)) class Window(QtWidgets.QMainWindow): def __init__(self): super(Window, self).__init__(self) # other regular stuff in init... How in another file do I create an instance of this object? i.e. when I do the following, import gui window = gui.Window() I get error "super-class__init__() of type Window was never called". Also when I try window = gui.Window.super().__init__() I get the error type Object 'Window' has no attribute 'super'.
has comment: http://stackoverflow.com/comment/85058471
tagged with: super
has title: Creating an instance of a python object error - how to call the super method?
has comment: http://stackoverflow.com/comment/85046637
type: Question
has answer: http://stackoverflow.com/a/49031812
tagged with: object
tagged with: init

http://stackoverflow.com/comment/85067822
score: 0
type: QuestionComment
type: Comment
has text: Do you have a setup.py file?
comment on: http://stackoverflow.com/q/49031491

http://stackoverflow.com/comment/85075167
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49035085
has text: Idk how I couldn't come up with this but this was what I was thinking of. Thank you.

qt5
tags question: http://stackoverflow.com/q/49049828
type: Tag
tags question: http://stackoverflow.com/q/49106763
tags question: http://stackoverflow.com/q/49109428
tag name: qt5
tags question: http://stackoverflow.com/q/49029780

http://stackoverflow.com/q/49085813
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I have such DataFrame W2 N V1 V2 ba EX 62069 30014 ba ADV 12325 8218 ba X 23 22 b X 164831 39425 b PRT 41543 16708 I need groupby W2 with same values in one row summing V1, V2 values. This row should be where V1==max. I do it: df_4=df_2.sort_values(['W2','V1'],ascending=[True, False]).drop_duplicates(['W2']) df_3= df_2.groupby(['W2'],as_index=False).sum() but when i search max i need ignore row where N==EX(only max, sum should include V1 and V2 of this rows). So result should be: W2 N V1 V2 ba ADV 74417 38254 b X 206374 56133 I hope i can do it with pandas. Any thoughts?
has title: pandas groupby with ignore some rows
has answer: http://stackoverflow.com/a/49085932
accepted answer: http://stackoverflow.com/a/49085932
tagged with: pandas
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/85245547
has text: How long are you training for and what is your loss?
comment on: http://stackoverflow.com/q/49118967
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85074576
type: Comment
has text: ok you should be able to do it by patching `__builtins__.print`. patch still won't work with anything that isnt importable though.
type: QuestionComment
comment on: http://stackoverflow.com/q/49034642
score: 0

http://stackoverflow.com/comment/109885301
score: 3
type: AnswerComment
has text: @Parfait how do I level the axis to say `array1, array2, array3, array4, array5` instead of `0,1,2,3,4` or add a legend to the plot?
type: Comment
comment on: http://stackoverflow.com/a/49119776

http://stackoverflow.com/comment/85228593
type: QuestionComment
score: 3
has text: How about looking where that file is instead of randomly picking directories?
comment on: http://stackoverflow.com/q/49111774
type: Comment

http://stackoverflow.com/q/48969754
type: Question
tagged with: python-2.7
has body: I have two separate pandas dataframes (df1 and df2) which have multiple columns with some common columns. I would like to find every row in df2 that does not have a match in df1. Match between df1 and df2 is defined as having the same values in two different columns A and B in the same row. df1 A B C text 45 2 1 score 33 5 2 miss 20 1 3 score df2 A B D text 45 3 1 shot 33 5 2 shot 10 2 3 miss 20 1 4 miss Result df (Only Rows 1 and 3 are returned as the values of A and B in df2 have a match in the same row in df1 for Rows 2 and 4) A B D text 45 3 1 shot 10 2 3 miss Is it possible to use the isin method in this scenario?
answer count: 1
score: 0
tagged with: pandas
tagged with: python
tagged with: pattern-matching
has comment: http://stackoverflow.com/comment/84945019
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/48969784
has title: Comparing dataframes in pandas
accepted answer: http://stackoverflow.com/a/48969784

http://stackoverflow.com/comment/85080164
score: 0
has text: Yes, except for Column name PKID, if all other columns have same values, then merge the rows as 1 and make the PKID column's value as a List of integers.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49037428

http://stackoverflow.com/q/49042976
score: 2
has title: Tablib xlsx file badZip file issue
has comment: http://stackoverflow.com/comment/85097649
has body: I am getting error on opening xlsx extension file in windows 8 using tablib library. python version - 2.7.14 error is as follows: python suit_simple_sheet_product.py Traceback (most recent call last): File "suit_simple_sheet_product.py", line 19, in &lt;module&gt; data = tablib.Dataset().load(open(BASE_PATH).read()) File "C:\Python27\lib\site-packages\tablib\core.py", line 446, in load format = detect_format(in_stream) File "C:\Python27\lib\site-packages\tablib\core.py", line 1157, in detect_format if fmt.detect(stream): File "C:\Python27\lib\site-packages\tablib\formats\_xls.py", line 25, in detect xlrd.open_workbook(file_contents=stream) File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 120, in open_workbook zf = zipfile.ZipFile(timemachine.BYTES_IO(file_contents)) File "C:\Python27\lib\zipfile.py", line 770, in __init__ self._RealGetContents() File "C:\Python27\lib\zipfile.py", line 811, in _RealGetContents raise BadZipfile, "File is not a zip file" zipfile.BadZipfile: File is not a zip file path location is as follows = BASE_PATH = 'C:\Users\anju\Downloads\automate\catalog-5090 fabric detail and price list.xlsx'
type: Question
has comment: http://stackoverflow.com/comment/85095398
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49045482
favorite count: 0
has comment: http://stackoverflow.com/comment/85098402
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: tablib

http://stackoverflow.com/q/48971338
type: AnsweredQuestion
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49000617
score: 0
tagged with: arduino
tagged with: loops
answer count: 1
tagged with: arduino-uno
has body: So I started using an Arduino kit I bought recently, and have been attempting to make a motor move (for now) before I go onto more complex things. The point of my little project in the future will be for the Arduino to sense light from near my window at night. From there it will hopefully turn a motor that hits my alarm clock. Though for now I simply want to get the motor moving when it sees light, and off once it stops seeing light, as I can add an automatic turn off after a few seconds later. Here is the current code: const int motorPin = 9; const int sensorPin = 10; int lightLevel, high = 0, low = 1023; void setup() { // Set up the motor pin to be an output: pinMode(motorPin, OUTPUT); // Set up the serial port: Serial.begin(9600); } void loop() { motormoveLevel = analogRead(sensorPin); manualTune(); analogWrite(motorPin, lightLevel); } void manualTune() { lightLevel = map(lightLevel, 0, 1023, 0, 255); lightLevel = constrain(lightLevel, 0, 255); } It does not compile, however the codes I derived it from do, here is one that turns on the motor for a few seconds then turns it off intermittently: const int motorPin = 9; void setup() { // Set up the motor pin to be an output: pinMode(motorPin, OUTPUT); // Set up the serial port: Serial.begin(9600); } void loop() { motorOnThenOff(); } // This function turns the motor on and off like the blinking LED. // Try different values to affect the timing. void motorOnThenOff() { int onTime = 3000; // milliseconds to turn the motor on int offTime = 3000; // milliseconds to turn the motor off digitalWrite(motorPin, HIGH); // turn the motor on (full speed) delay(onTime); // delay for onTime milliseconds digitalWrite(motorPin, LOW); // turn the motor off delay(offTime); // delay for offTime milliseconds } And this code turns an led on and off based on the photosensor: const int sensorPin = 0; const int ledPin = 9; int lightLevel, high = 0, low = 1023; void setup() { pinMode(ledPin, OUTPUT); } void loop() { lightLevel = analogRead(se…
has title: Moving a motor with an arduino and a photo-sensor
has answer: http://stackoverflow.com/a/49000617

http://stackoverflow.com/comment/85021263
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49003440
has text: I am getting this error , when i return the results and tried dumps methods. raise TypeError(repr(o) + " is not JSON serializable")
score: 0

http://stackoverflow.com/q/49069683
tagged with: javascript
has answer: http://stackoverflow.com/a/49069923
tagged with: jquery
has title: How can I hide a form after submission?
has comment: http://stackoverflow.com/comment/85144755
answer count: 2
accepted answer: http://stackoverflow.com/a/49069923
downvote count: 0
score: 1
has body: I was wondering how can I hide a form after submission. I tried something with JavaScript, but I keep getting a message from the form that no file was chosen. {% csrf_token %} {{ form.as_p }} Submit
favorite count: 0
possible better answer: http://stackoverflow.com/a/49069737
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49069737
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85144581
has comment: http://stackoverflow.com/comment/85144481
type: Question

http://stackoverflow.com/comment/85181781
type: QuestionComment
comment on: http://stackoverflow.com/q/49088117
score: 0
has text: Use `df = df1.mul(df2)`
type: Comment

http://stackoverflow.com/comment/105744823
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49019091
type: QuestionComment
has text: what if to through RDD way instead of DataFrame and use sparks cache and persist options to optimize the result.

http://stackoverflow.com/a/48993501
score: 1
answers question: http://stackoverflow.com/q/48993338
accepted answer of: http://stackoverflow.com/q/48993338
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You can create a partial function specific to your host name: from functools import partial check_directory_host = partial(check_directory, hostname=hostname) with Pool(thread_count) as p: results = p.map(check_directory_host, directory_list) partial creates a new function with the argument hostname "fixed": partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords. Here an example: def add(a, b): return a + b add_10 = partial(add, b=10) Now the second argument b is fixed and you can (and must) call the function only with a value for a: &gt;&gt;&gt; add_10(5) 15
downvote count: 0

http://stackoverflow.com/a/49049064
score: 1
has comment: http://stackoverflow.com/comment/85110481
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49047655
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: In your DisplayPage class you are overwriting the __init__ method, so you need to call the __init__ method of the parent (Screen class). With BoxLayout.__ init __ (self, * args) you just call the constructor of BoxLayoutbut not the constructor of Screen. I don't understand why you try to do a multiple subclassing here, you can simply inherit from Screen and call its constructor (preferably using super). Screen is a RelativeLayout, if you need to use another layout in your screen simply add it as any widget (being careful with certain peculiarities): &lt;MenuPage&gt;: BoxLayout: # Rest of screen's content here You can do something like: main.py: import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang.builder import Builder import json Builder.load_file('VocabularyJournal.kv') class MenuPage(Screen): pass class DisplayPage(Screen): def __init__(self, **kwargs): # Call __init__ method of parent class (Screen) super(DisplayPage, self).__init__(**kwargs) with open('vocab_words.json') as rfile: data = json.load(rfile) class WordInsertPage(Screen): pass class NewWordPage(Screen): pass class FlashCard(Screen): pass class WordGroups(Screen): pass class Manager(ScreenManager): pass class VocabularyJournalApp(App): def build(self): return Manager() if __name__ == "__main__": object = VocabularyJournalApp() object.run() VocabularyJournal.kv: &lt;Manager&gt;: MenuPage: name: 'menu' WordInsertPage: name: 'insertword' NewWordPage: name: 'newword' FlashCard: name: 'flashcard' WordGroups: name: 'wordgroup' DisplayPage: name: 'display' &lt;MenuPage&gt;: # Your code here &lt;WordInsertPage&gt;: FloatLayout: Button: text: "New Word" on_press: root.manager.current='newword' font_size: 30 color: 0,0,0,1 size_hint: .2, .1 pos_hint: {"center_x": .5, "center_y": 0.3} Button: text: "search word" on_press: root.manager.current='display' font_size: 30 color: 0,0,0,1 size_hint: .2, .1 pos_hint: {"center_x": .5, "center_…
answers question: http://stackoverflow.com/q/49047655

http://stackoverflow.com/q/49040371
type: UnansweredQuestion
tagged with: python
tagged with: sqlalchemy
type: Question
has body: Disclaimer: I recently took over someone else's codebase so some of the code you see here was already premade. I've also changed certain variable names to more generic code names that probably wouldn't actually work. I am trying to bulk upsert on a postgres DB using SQLAlchemy but am having trouble. It seems that when SQLAlchemy goes to access the data it needs to update the table (excluded.columnName) It is unable to be found. First here is the error I'm getting: Missing FROM-clause entry for table "excluded" LINE 1: ...tablename) VALUES (excluded.tablename... And my code: index_fields = list(billocity_db.get_indexes(self.table_name)) for row in self.data: if 'id' in self.column_info.keys(): del row['id'] data = row.to_dict() insert_stmt = insert(self.table).values(data) for i in index_fields: if i in data: del data[i] for key in data.keys(): data[key] = insert_stmt.excluded[key] print(data[key]) print(data) insert_stmt = insert_stmt.on_conflict_do_update( #Tried both constraint and index_elements with same result #constraint=self.table_name, #None of my columns are 'id'. Could that be an issue? index_elements=['id'], set_=data ) try: print(insert_stmt) self.session.execute(insert_stmt) except Exception as e: self.session.rollback() self.log.exception(str(e)) finally: self.session.commit() The error comes immediately after calling self.session.execute(insert_stmt) And this is what insert_stmt prints as right before execute, obviously column_name and table_name is just place holder. INSERT INTO table_name (column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name, column_name) VALUES ( excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.column_name, excluded.…
has title: SQLAlchemy Upsert unable to find table "excluded"
score: 0
tagged with: upsert
answer count: 1
has answer: http://stackoverflow.com/a/49043016
tagged with: postgresql

http://stackoverflow.com/q/49054977
has comment: http://stackoverflow.com/comment/85116361
has comment: http://stackoverflow.com/comment/85141034
has title: pyglet - Smooth text rendering
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has body: I've been looking on the internet for about an hour, and I can't seem to find a way to create smooth text. Here is the code I currently have: self.nameLabel = pyglet.text.Label(name, font_name='Tahoma', y=self.y + 6, font_size=12, batch=batch.overlay2, height=self.scale_y, bold=True) And then I draw it using a batch: batch.overlay2.draw() The rendered text is not smooth, as shown in the following image: How can I make this text look smoother? Thanks in advance. David
tagged with: pyglet
score: 0

http://stackoverflow.com/q/49012987
has title: s2sphere Cell ID to Corner Vertices
has answer: http://stackoverflow.com/a/49113782
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49113782
tagged with: python
type: AnsweredQuestion
has body: I've got a list of S2 Level 17 Cell ID's from OSMCoverer in the format 487a73cc7c and I need to get the corner points of each one. I've found a script by a user on Reddit here using the Python s2sphere library which I believe I can use but it doesn't output the correct co-ords, they should around 52.80xxxx,-2.xxxxx range. I think it's something to do with the shift operation on line 5 but I don't know enough to correct it. import s2sphere from s2sphere import CellId, LatLng, Cell def get_corners(s2CellId_str, level): c1 = Cell(CellId(int(s2CellId_str,16)&lt;&lt;(60 - 2*level))) print(c1) c0 = LatLng.from_point(c1.get_center()) # center lat/lon of s2 cell v0 = LatLng.from_point(c1.get_vertex(0)) # lat/lon of upper/left corner v1 = LatLng.from_point(c1.get_vertex(1)) # lat/lon of lower/left corner v2 = LatLng.from_point(c1.get_vertex(2)) # lat/lon of lower/right corner v3 = LatLng.from_point(c1.get_vertex(3)) # lat/lon of upper/right corner print(' // s2 level ' + str(level) + ' cell id = ' + s2CellId_str) print('Center = ' + str(c0)) print('Vertex0 = ' + str(v0)) print('Vertex1 = ' + str(v1)) print('Vertex2 = ' + str(v2)) print('Vertex3 = ' + str(v3)) get_corners("487a73cc7c", 17) Thanks in advance.
score: 1
tagged with: geolocation
upvote count: 1
type: Question

http://stackoverflow.com/q/48964465
type: Question
tagged with: pandas
tagged with: python
score: 1
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/48964498
upvote count: 1
has body: Using: Python3.6, Pandas 0.22 Looking for any tips or documentation that would steer me in the right direction.. I have a DataFrame which calculates averages for snowfall based on month and location. The file has two years, 2016 and 2017. I am trying to understand if the code I have written is capable of writing to two different files, one for 2016 and one for 2017. df = pd.read_csv("Data.csv") df['DATE'] = pd.DatetimeIndex(df['DATE'], format='%M/%D/%Y') df['Year'] = df['DATE'].dt.year df['Month'] = df['DATE'].dt.month df['Day'] = df['DATE'].dt.day (df .assign(MONTH=df['DATE'].dt.strftime('(%m) %B (%y)')) .groupby(['NAME', 'MONTH', 'Year'], as_index=False)['SNOW'] .agg({'AVERAGE': 'mean'}) ) I have attempted many different methods, placing the DF both inside, and outside of these loops: if 'Year' == '2016': df = pd.to_csv('average2016.csv', index=False) else: df = pd.to_csv('average2017.csv', index=False) and: if df.loc[df['Year'] == 2016]: df = pd.to_csv('average2016.csv', index=False) else: df = pd.to_csv('average2017.csv', index=False) I have also tried using pd.Series, but it seems as though you can't use df.assign with this? df = pd.Series(['1/1/2016']) if df.item(): I have also attempted for loops, using the range of dates but they just skip the condition and write all of the dates to one file.
has answer: http://stackoverflow.com/a/48964527
type: AnsweredQuestion
has title: Python Pandas Write Two Different Files Based on Date Condition
downvote count: 0
possible better answer: http://stackoverflow.com/a/48964527
has answer: http://stackoverflow.com/a/48964498
favorite count: 0

http://stackoverflow.com/comment/85153753
type: Comment
comment on: http://stackoverflow.com/a/49038999
type: AnswerComment
has text: @JustinLiang "I can just densify the points": the median curve needn't be more accurate/smooth than the given curves. So there is no need to densify.
score: 0

http://stackoverflow.com/comment/85086912
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49040490
has text: Thanks for your reply. Unforunatley your first line of code defines the tempTarget as 24 however, what i am trying to do is rather than specify the tempTarget, it will get specified by using the request.get to get the current tempTarget and then adding 1 to that.
type: Comment

http://stackoverflow.com/q/49003059
tagged with: python
possible better answer: http://stackoverflow.com/a/49003882
type: AnsweredQuestion
tagged with: performance
tagged with: a-star
score: 1
has title: N-puzzle a-star python solver efficiency
has answer: http://stackoverflow.com/a/49022238
upvote count: 1
has comment: http://stackoverflow.com/comment/85017158
type: Question
has body: I've written an a-star algorithm designed to solve sliding-block/n puzzles. It works just fine on small puzzles, but struggles heavily with increasing complexity. I've already implemented several methods to improve efficiency (heapq, etc) but I've reached the end of my ideas. Can you think of anything else I can do to improve it? My code is here: https://repl.it/@Jaspirian/SimilarWoodenMemoryallocator Some important parts: The heuristic: def heuristic_estimate_manhattan(self, other): """ Finds the heuristic estimation of the cost to reach another state from this one. This heuristic is based on "manhattan distance." """ estimate = 0 for index in range(len(self.blocks)): estimate += abs(other.blocks[index][0] - self.blocks[index][0]) + abs(other.blocks[index][1] - self.blocks[index][1]) return estimate The neighbor function: def get_neighbors(self, previous): """ Gets all adjacent neighbors of the state, minus the previous. This function gives 7 neighbors: 4 orthogonal, 4 diagonal, with the previous state trimmed. """ neighbors = [] moves = ((-1,0),(1,0),(0,-1),(0,1)) zeroLoc = self.blocks[0] for move in moves: # swap 0 and whatever newBlocks = copy.deepcopy(self.blocks) newZeroLoc = (zeroLoc[0] + move[0], zeroLoc[1] + move[1]) # skip this state if we've moved off the board if newZeroLoc[0] &lt; 0 or newZeroLoc[1] &lt; 0 or newZeroLoc[0] &gt; self.width-1 or newZeroLoc[1] &gt; self.height-1: # print("we've moved off the board.") continue # skip this state if it's the same as the previous if previous and previous.blocks[0] == newZeroLoc: # print("this is just the same!") continue # move the 0 newBlocks[0] = newZeroLoc # move whatever's in that location... # to the previous one for face, location in newBlocks.items(): if face != 0 and location == newZeroLoc: newBlocks[face] = zeroLoc neighbor = Block_Puzzle(newBlocks) neighbors.append(neighbor) return neighbors The a-star algorithm: def aStar(start, goal): """ A star search algorithm. Takes a start state and an end stat…
has comment: http://stackoverflow.com/comment/85049435
has answer: http://stackoverflow.com/a/49003882
has answer: http://stackoverflow.com/a/49007608
accepted answer: http://stackoverflow.com/a/49007608
answer count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/85246983
comment on: http://stackoverflow.com/q/49120232
type: Comment
type: QuestionComment
score: 0
has text: I find that surprising, considering `df`s are mutable, and assigning a column inside the loop should update the original.

http://stackoverflow.com/comment/84951474
has text: Great my misunderstanding was du to encoding ... I have (é) in one of the index
type: Comment
comment on: http://stackoverflow.com/a/48972526
type: AnswerComment
score: 0

http://stackoverflow.com/q/49028239
answer count: 1
has answer: http://stackoverflow.com/a/49028483
favorite count: 0
has title: Counting in Pandas
tagged with: datetime
tagged with: count
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85060962
has comment: http://stackoverflow.com/comment/85060816
accepted answer: http://stackoverflow.com/a/49028483
has body: I'm trying to get a df from: df = pd.DataFrame({'Start Time': ['27/02/2018 12:56', '27/02/2018 12:56', '27/02/2018 12:51', '28/02/2018 12:51', '28/02/2018 12:46', '28/02/2018 12:46', '28/02/2018 12:41', '28/02/2018 12:41', '01/03/2018 12:36', '01/03/2018 12:36', '01/03/2018 12:31', '01/03/2018 12:31', '02/03/2018 12:27', '02/03/2018 12:27', '02/03/2018 12:27', '02/03/2018 12:27'], 'Event_type': ['Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer', 'Transfer'], 'Status': ['S', 'S', 'S', 'S', 'F', 'S', 'F', 'S', 'F', 'S', 'S', 'F', 'S', 'S', 'F', 'F'], 'Job Number': [1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0, 1000000000000.0]}, columns=['Job Number','Start Time','Event_type','Status']) print (df) Job Number Start Time Event_type Status 0 1.000000e+12 27/02/2018 12:56 Transfer S 1 1.000000e+12 27/02/2018 12:56 Transfer S 2 1.000000e+12 27/02/2018 12:51 Transfer S 3 1.000000e+12 28/02/2018 12:51 Transfer S 4 1.000000e+12 28/02/2018 12:46 Transfer F 5 1.000000e+12 28/02/2018 12:46 Transfer S 6 1.000000e+12 28/02/2018 12:41 Transfer F 7 1.000000e+12 28/02/2018 12:41 Transfer S 8 1.000000e+12 01/03/2018 12:36 Transfer F 9 1.000000e+12 01/03/2018 12:36 Transfer S 10 1.000000e+12 01/03/2018 12:31 Transfer S 11 1.000000e+12 01/03/2018 12:31 Transfer F 12 1.000000e+12 02/03/2018 12:27 Transfer S 13 1.000000e+12 02/03/2018 12:27 Transfer S 14 1.000000e+12 02/03/2018 12:27 Transfer F 15 1.000000e+12 02/03/2018 12:27 Transfer F to: Status F S Grand Total Start Time 2018-01-03 2 2 4 2018-02-03 2 2 4 2018-02-27 0 3 3 2018-02-28 2 3 5 Grand Total 6 10 16 What I need to do is get a count of the Destination file names with an 'S' tag that occur on a gi…
downvote count: 3
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85061101
score: -2
has comment: http://stackoverflow.com/comment/85061007
has comment: http://stackoverflow.com/comment/85060720
tagged with: pandas
tagged with: crosstab

http://stackoverflow.com/a/49082481
has comment: http://stackoverflow.com/comment/85170500
answers question: http://stackoverflow.com/q/49082316
has comment: http://stackoverflow.com/comment/85172241
score: 3
accepted answer of: http://stackoverflow.com/q/49082316
has body: Try this, I guess this will be your answer. from collections import OrderedDict d = OrderedDict(zip(data_ids, tag_ids)) for i, j in d.items(): print(i) print(j) Outputs: 22630876 WATCH - Stokes faces unpredictable balls 22626950 'Bad position, but we're not out of it' - de Villiers 22624826 Who is Sandeep Lamichhane? 22626159 WATCH - All the action from the Super Over 22616496 WATCH - Sammy's four-ball blitz 22601480 Shubman Gill's red-hot run streak 22611197 Should bowlers start wearing helmets? 22600498 Keshav Maharaj could be key - Graeme Smith 22605808 WATCH - Kevin Pietersen's match-winning 48 22602601 'It was emotional walking off the pitch' - Stokes 22602543 WATCH - India's gains from the South Africa tour 22594071 WATCH - Best of Kohli in South Africa 22595982 The Ashwin-Gibbs exchange: funny, or not? 22593725 Mayank Agarwal's incredible run of domestic form 22591441 'SA can't afford spicy pitches against Australia' 22553315 Ice Cricket: Legends play T20 in the Alps 22584758 Dhoni, Kohli and quirky on-field chatter
has comment: http://stackoverflow.com/comment/85170527
has comment: http://stackoverflow.com/comment/85171671
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85170541
downvote count: 0
has comment: http://stackoverflow.com/comment/85170715
has comment: http://stackoverflow.com/comment/85170635
has comment: http://stackoverflow.com/comment/85170879
has comment: http://stackoverflow.com/comment/85170894
has comment: http://stackoverflow.com/comment/85172547
type: Answer
has comment: http://stackoverflow.com/comment/85170514
has comment: http://stackoverflow.com/comment/85170614
has comment: http://stackoverflow.com/comment/85170301
has comment: http://stackoverflow.com/comment/85172809
upvote count: 3

http://stackoverflow.com/comment/85013294
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48998492
has text: But then you ask "[d]oes Windows send the location of a opened shortcut"? That's not the working directory. But you can get that information as well. Call [`GetStartupInfo`](https://msdn.microsoft.com/en-us/library/ms683230) to get the process startup info. If `dwFlags` includes `STARTF_TITLEISLINKNAME`, then the `lpTitle` field is the path to the .LNK shortcut file. Bear in mind your shortcut should directly run the executable of the process that calls `GetStartupInfo`. This may not be compatible with a frozen script if it unpacks and executes another program.

http://stackoverflow.com/q/49094970
favorite count: 0
has comment: http://stackoverflow.com/comment/85195782
answer count: 0
has body: I have discovered that this piece of code is taking up to 10s when under some load, and I don't get why. Using django 1.8 with python 2.7 from django.core.cache import cache from datetime import datetime class ActiveUserMiddleware: def process_request(self, request): current_user = request.user if request.user.is_authenticated(): now = datetime.now() if current_user.in_class: cache.set('seen_%s_%s' % (str(current_user.in_class.id), current_user.username.replace(" ", "_")), now, settings.USER_LASTSEEN_TIMEOUT) Using memcached django.core.cache.backends.memcached.MemcachedCache With settings USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 30 And I know that the database calls and memcache calls are just taking millisecs, it hangs here somewhere in django.
type: UnansweredQuestion
upvote count: 1
tagged with: django
tagged with: memcached
has title: Django middleware setting cache taking 10 seconds
score: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/85196471
tagged with: python

http://stackoverflow.com/q/49025790
answer count: 2
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/49025886
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49026158
accepted answer: http://stackoverflow.com/a/49026158
tagged with: python
has title: Is there better way to write such loops when I use dataframe?
has body: Is there better way to write such loops when I use dataframe? a,b are dataframes(4, 1096) c = pd.DataFrame(np.zeros((4, 1096))) for j in range(0, 4): for i in range(0, 1096): c[i][j]=abs((a[i][j]-b[i][j]))/(a[i][j]+b[i][j])
has answer: http://stackoverflow.com/a/49025886
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85057459
has comment: http://stackoverflow.com/comment/85056234
type: Question

http://stackoverflow.com/a/49113293
has comment: http://stackoverflow.com/comment/85236299
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Try omitting hostids from your request. The ns value is the nanosecond value in that second.
type: Answer
accepted answer of: http://stackoverflow.com/q/49113014
score: 1
answers question: http://stackoverflow.com/q/49113014
has comment: http://stackoverflow.com/comment/85234458

http://stackoverflow.com/a/49095723
answers question: http://stackoverflow.com/q/49095635
type: Answer
score: 2
downvote count: 0
has body: For decoding problems: a = "\\xce\\x97" print(a.encode().decode('unicode-escape').encode("latin-1").decode('utf-8')) 'Η'
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49095635

http://stackoverflow.com/a/61023741
score: 6
has body: Looks like bson.loads are supposed to load exactly one document. We can decode multiple documents present within a bson as below- with open('mybson.bson', 'rb') as f: content = f.read() base = 0 while base &lt; len(content): base, d = bson.decode_document(content, base) print(d)
downvote count: 0
answers question: http://stackoverflow.com/q/49003637
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/111355644

http://stackoverflow.com/comment/85070499
has text: this (11750, 100, 100, 1) (11750,) (5875, 100, 100, 1) (5875,) #x=x.reshape((-1,100,100,1)) # i reshaped to 4
score: 0
comment on: http://stackoverflow.com/a/49031961
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48994157
favorite count: 0
has comment: http://stackoverflow.com/comment/84993810
downvote count: 0
has answer: http://stackoverflow.com/a/48994516
has comment: http://stackoverflow.com/comment/84993854
has answer: http://stackoverflow.com/a/48995802
type: AnsweredQuestion
score: 1
type: Question
has body: I'm trying to get the number of outliers by group from a Pandas data frame. My data looks like this. df = pd.DataFrame({'group':list('aaaabbbb'), 'val':[1,3,3,2,5,6,6,2], 'id':[1,1,2,2,2,3,3,3], 'mydate':['01/01/2011 01:00:00', '01/01/2011 01:02:00', '01/01/2011 01:05:00', '01/01/2011 01:06:00', '01/01/2011 03:00:00', '01/01/2011 04:00:00', '01/01/2011 05:00:00', '01/01/2011 10:00:00']}) df To get the number of outliers, I'm using the following function that gets the IQR. def get_IQR(): q1 = df["val"].quantile(0.25) q3 = df["val"].quantile(0.75) iqr = (df["val"] &gt; q1) &amp; (df["val"] &lt; q3) return val.loc[iqr] df"group","val".agg([get_IQR]) This doesn't work and produced the following results ValueError: no results Does anyone have a better strategy for finding the number of outliers per group, such that... group num_outliers a ... b ... c ...
possible better answer: http://stackoverflow.com/a/48994516
has answer: http://stackoverflow.com/a/48994830
accepted answer: http://stackoverflow.com/a/48994830
has answer: http://stackoverflow.com/a/48994249
has title: Get the number of outliers by group in Pandas
tagged with: pandas
upvote count: 1
tagged with: python
answer count: 4

http://stackoverflow.com/q/48994798
tagged with: python
has body: I have a Spark dataframe which can be simplified as the following: Party CounterParty timestamp id_1 id_2 01/01/16 id_2 id_3 01/01/16 id_1 id_2 14/01/16 id_4 id_1 03/01/16 id_2 id_3 01/01/16 id_1 id_1 01/02/16 id_1 id_2 30/01/16 What I'm trying to do is to create a timeseries for every unique pair of Party and CounterParty. The goal is to plot and further analyse this time series data for each pair. In pseudo code: pairs = df.grouby(Party,CounterParty) list = [] for i in each pair: find all timestamps and append to list //DO OTHER STUFF The groupby is not a problem but I don't know how to proceed afterwards. Thanks in advance!
type: AnsweredQuestion
tagged with: pyspark
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48995388
accepted answer: http://stackoverflow.com/a/48995388
score: 0
tagged with: apache-spark
has title: Create timeseries from groupby result in Spark dataframe using PySpark

http://stackoverflow.com/comment/85242552
type: Comment
has text: do I not need parantheses around the function names in the dictionary for your first example, for example 'foo' : foo()
comment on: http://stackoverflow.com/a/49074661
score: 0
type: AnswerComment

http://stackoverflow.com/q/49013930
has title: Python print turtle.pos()
score: 0
answer count: 2
tagged with: printing
has answer: http://stackoverflow.com/a/49022899
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85032709
has answer: http://stackoverflow.com/a/49014100
upvote count: 1
downvote count: 1
has body: I'm trying to write a program that draws shapes based on user input. I want it to print where each corner of the shape is based on using the turtle.pos() function, however I'm trying to get the printed output as so: "The first corner is at: x, y, with a heading of: d." Currently the print I'm using is print("The first corner is at:", turtle.position(), "with a heading of:" turtle.heading() + ".") And this outputs as: "The first corner is at: (x, y,), with a heading of: d." So printing the turtle.pos() returns the coords as a tuple, and prints as (X, y). When I try to format as int, it gives me an error about needing str, not vec2d. How would I format that output? Or am I completely going about that the wrong way?
type: Question
tagged with: vector

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/49027447
tags question: http://stackoverflow.com/q/48997207
tags question: http://stackoverflow.com/q/49063703
tags question: http://stackoverflow.com/q/49038347
type: Tag

http://stackoverflow.com/comment/85034164
score: 1
comment on: http://stackoverflow.com/q/49014601
has text: The note you quoted has nothing to do with efficiency, so how is it relevant to your main question?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85410495
type: AnswerComment
has text: Typically your image is a 3d array, with each channel being represented in the last axis. For instance given `[[[1 1 1][2 2 2][3 3 3]]]`, your R would be `[1 1 1]`, your G would be `[2 2 2]` and your B would be `[3 3 3]`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49117047

http://stackoverflow.com/comment/85239685
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49116569
has text: It's not clear can you mention output as you want...
score: 0

http://stackoverflow.com/comment/85169891
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49082280
has text: Your code doesn’t make much sense. You are appending a space to the variable spaces, which is then immediately changed to the next character in word.

http://stackoverflow.com/q/48999007
tagged with: dataframe
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48999492
has answer: http://stackoverflow.com/a/48999492
downvote count: 0
has answer: http://stackoverflow.com/a/49001628
favorite count: 0
has answer: http://stackoverflow.com/a/48999958
accepted answer: http://stackoverflow.com/a/49001628
upvote count: 1
tagged with: python
tagged with: merge
has title: Merging dataframes based on ranges that are defined by columns
type: AnsweredQuestion
score: 1
has body: I have two dataframes. One has some probability brackets. df1 = pd.DataFrame({'ProbabilityBrackets' : [0,0.50,0.75,1.0,0.75,0.90,1.0,0],\ 'Group' : pd.Categorical(["test","test","test","test","train","train","train","train"]),'Destination' : pd.Categorical(["-","A","B","C","AA","BB","CC","-"])}) Destination Group ProbabilityBrackets 0 - test 0.00 1 A test 0.50 2 B test 0.75 3 C test 1.00 4 AA train 0.75 5 BB train 0.90 6 CC train 1.00 7 - train 0.00 The other dataframe has some random numbers and the group column. df2 = pd.DataFrame({'randomnumbers' : [0.2,0.15,0.78,0.35],\ 'Group' : pd.Categorical(["test","train","test","train"])}) Group randomnumbers 0 test 0.20 1 train 0.15 2 test 0.78 3 train 0.35 Now, I need to merge the two dataframes together by both group and based on the probability brackets. Merging by group is trivial. The challenging requirement is merging by based on probabilitybrackets and random numbers. A random number in df2 should be mapped to the smallest probability bracket that is larger than itself. E.g., test 0.2 in df2 is mapped to test 0.5 in df1. test 0.78 in df2 is mapped to test 1.0 in df1. I did it as follows, which works well and : for group in ['test','train']: brackets=df1[df1['Group']==group].sort_values(by='ProbabilityBrackets')['ProbabilityBrackets'].unique() bracketlabels = brackets[1:] #remove the first element of the list. (e.g., remove 0 from (0,0.5,1)) df2.loc[df2['Group']==group,'ProbabilityBrackets']=pd.cut(df2['randomnumbers'],brackets, labels=bracketlabels) #assign random numbers to the brackets so that we can easily merge them with df1 df3=df2.merge(df1,on=['Group','ProbabilityBrackets'],how='left') It generates the following output, which is what I want but it is slower than I want because I have thousands of groups in my dataset. Is there a way to do it faster in a pythonic way? Group randomnumbers ProbabilityBrackets Destination 0 test 0.20 0.50 A 1 train 0.15 0.75 AA 2 test 0.78 1.00 C 3 train 0.35 0.75 AA
type: Question

http://stackoverflow.com/comment/85165649
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49078602
has text: No problem, I also would have chosen his answer! I didn't know about `merge_asof`

http://stackoverflow.com/a/49049100
upvote count: 3
has body: The ab in the lambda definition is defined in the surrounding scope, thus changes with every iteration. Only the ab values of the last iteration are reflected into all the lambda funtions. One possible solution is to use a factory method for the creation of the lambda function: import numpy as np import matplotlib.pylab as pl def lambda_factory(ab): return lambda x:x*ab[0]+ab[1] def broken_line(x, x0, y0): cl = [] fl = [] for i in range(len(x0)-1): ab = np.polyfit(x0[i:i+2], y0[i:i+2], 1) # Compute and append a "condition" interval cl.append(np.logical_and(x &gt;= x0[i], x &lt;= x0[i+1])) # Create a line function for the interval fl.append(lambda_factory(ab)) return(np.piecewise(x, condlist=cl, funclist=fl)) x0 = np.array([1, 3, 5, 10]) y0 = np.array([2, 1, 5, 7]) x = np.linspace(1, 10, 30) pl.plot(x, broken_line(x, x0, y0)) pl.plot(x0, y0) pl.show() Another solution is to save ab in a variable local to the lambda, thus using fl.append(lambda x, ab=ab:x*ab[0]+ab[1]) within the loop. Here you create a local variable ab of the outer scope variable ab. In both cases the result looks like this: For further reference see the python faq
answers question: http://stackoverflow.com/q/49047279
has comment: http://stackoverflow.com/comment/85105290
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49047279
type: Answer
score: 3

http://stackoverflow.com/a/48997853
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85001612
has body: Use groupby/shift to shift rows within each group: df['next_days_close'] = df.groupby(level=1)['close'].shift(-1) For example, import numpy as np import pandas as pd np.random.seed([2,718]) index = pd.MultiIndex.from_product([['X','Y','Z'], [1,2,3]]) df = pd.DataFrame(np.random.randint(10, size=(9,2)), columns=list('AB'), index=index) df['C'] = df.groupby(level=1)['B'].shift(-1) print(df) prints A B C X 1 6 5 6.0 2 1 8 9.0 3 4 4 3.0 Y 1 9 6 7.0 2 7 9 7.0 3 4 3 5.0 Z 1 7 7 NaN 2 4 7 NaN 3 3 5 NaN
accepted answer of: http://stackoverflow.com/q/48997767
score: 0
answers question: http://stackoverflow.com/q/48997767

http://stackoverflow.com/q/49036021
has comment: http://stackoverflow.com/comment/85077267
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49036251
tagged with: tkinter
has body: This is probably a silly question, but I couldn't find an answer to it on here, so here goes. I'm setting up a Tkinter interface, and I'm only one button in. This button, when clicked should change the variable go to 1, I have done this by requiring it to call the function getGo(self) which is in the same class as the init function where the button was set up. My problem is that it doesn't run the whole goTime() function: ie, it doesn't update my variable go. init function: class New_Toplevel_1: go=0 def __init__(self, top=None): self.butGo = Button(top,command=lambda *args: goTime(self)) self.butGo.place(relx=0.48, rely=0.84, height=41, width=65) self.butGo.configure(activebackground="#7bd93b") self.butGo.configure(font=font12) self.butGo.configure(text='''Go!''') def goTime(self): print("It's go time!") self.go=1 print("go has been updated") The output looks like this (repeated the number of times I clicked the button): It's go time! It's go time! It's go time! It's go time! Why won't it update the variable? Or even show "go has been updated"? Thanks!
has title: Python/Tkinter : update class variable with a button
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49036251
type: Question
answer count: 1
tagged with: user-interface

http://stackoverflow.com/a/49016951
has comment: http://stackoverflow.com/comment/85040223
has comment: http://stackoverflow.com/comment/85039165
has body: Is there any good reason to use any? If you want an one-liner to find out which numbers are not evenly divisible : not_divisible = [i for i in range(1, 21) if product % i != 0] if len(not_divisible) &gt; 0: print(not_divisible) You can't really get all the non-divisible numbers with any, since it stops when it finds the first False in the iterable
answers question: http://stackoverflow.com/q/49016216
has comment: http://stackoverflow.com/comment/85039108
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85039273
has comment: http://stackoverflow.com/comment/85039338
accepted answer of: http://stackoverflow.com/q/49016216
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/59517621
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49015957
upvote count: 7
has body: The best way to export matplotlib charts to the web browser is to Use mpld3 library. Here is the example. import matplotlib.pyplot as plt import numpy as np import pandas as pd import mpld3 from mpld3 import plugins np.random.seed(9615) # generate df N = 100 df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0), columns=['a', 'b', 'c', 'd', 'e'],) # plot line + confidence interval fig, ax = plt.subplots() ax.grid(True, alpha=0.3) for key, val in df.iteritems(): l, = ax.plot(val.index, val.values, label=key) ax.fill_between(val.index, val.values * .5, val.values * 1.5, color=l.get_color(), alpha=.4) # define interactive legend handles, labels = ax.get_legend_handles_labels() # return lines and labels interactive_legend = plugins.InteractiveLegendPlugin(zip(handles, ax.collections), labels, alpha_unsel=0.5, alpha_over=1.5, start_visible=True) plugins.connect(fig, interactive_legend) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('Interactive legend', size=20) mpld3.show() https://mpld3.github.io/quickstart.html
score: 7

http://stackoverflow.com/comment/85263264
has text: @supersam654 I HAVE MSVCP140.DLL, and mine is CPU only version..
comment on: http://stackoverflow.com/q/49093774
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85041944
type: Comment
score: 0
has text: Latest discord.py, Python 3, Should i import from discord client?
comment on: http://stackoverflow.com/a/49018313
type: AnswerComment

http://stackoverflow.com/q/49091621
has comment: http://stackoverflow.com/comment/85188873
has comment: http://stackoverflow.com/comment/85188700
has title: AutoSolve Tower Of Hanoi
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85188617
has comment: http://stackoverflow.com/comment/85188791
has comment: http://stackoverflow.com/comment/85189336
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85188802
tagged with: python-2.7
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85188706
has comment: http://stackoverflow.com/comment/85188684
type: Question
has comment: http://stackoverflow.com/comment/85188572
has body: I am trying to make a function where user can autosolve the game at the current state. I got this error. Anyone who helps me is gladly appreciated. #main method def main(self): for i in range(self.iniNumTower): tempStack = MyStack("Tower" + str(i + 1)) self.TowerList.append(tempStack) #User to choose their diffculty self.options = raw_input("Select your Difficulty: ") if self.options == "Beginner": self.numDisk = 3 elif self.options == "Advance": self.numDisk = 6 else: self.numDisk = 10 for i in range(self.numDisk, 0, -1): self.endGameList.append(i) self.TowerList[0].push(i) print("[1] - Continue Steps") print("[2] - Auto Solve") print("[0=9] - Quit") choice = int(raw_input("Enter choice: ")) while choice != 9: if choice == 0: break elif choice == 1: # while checkEndGame(endGameList,targetTower._data,helperTower._data) != 1: moveFrom = 0 moveTo = 0 a.printAllTowers() a.printTowerOptions() moveFrom = int(raw_input("Move from: ")) # if(moveFrom!=9): moveTo = int(raw_input("Move to : ")) if a.checkDiskMove(a.TowerList[moveFrom - 1], a.TowerList[moveTo - 1]) == 1: a.moveDisk(a.TowerList[moveFrom - 1], a.TowerList[moveTo - 1]) else: print "Unable to move from " + a.TowerList[moveFrom - 1].name + " to " + a.TowerList[ moveTo - 1].name if a.checkEndGame() == 1: a.printAllTowers() print "You've Win!" print "Game End" break elif choice == 2: a.autoSolve(a.numDisk, a.TowerList[0], a.TowerList[2], a.TowerList[1]) if a.checkEndGame() == 1: a.printAllTowers() print "You've Win!" print "Game End" break def autoSolve(self,n, from_rod, to_rod, aux_rod): if n == 1: print "Move disk 1 from rod", from_rod.name, "to rod", to_rod.name cap = CurrentCapture() to_rod.push(from_rod.pop()) cap.capture(self.TowerList[0], self.TowerList[2], self.TowerList[1]) self.answerKey.append(cap) return TowerOfHanoi().autoSolve(n - 1, from_rod, aux_rod, to_rod) print "Move disk", n, "from rod", from_rod.name, "to rod", to_rod.name to_rod.push(from_rod.pop()) TowerOfHanoi().autoSolve(n - 1, aux_rod, to_ro…
tagged with: python
has answer: http://stackoverflow.com/a/49091643
has comment: http://stackoverflow.com/comment/85188602
has comment: http://stackoverflow.com/comment/85188723
score: -1

http://stackoverflow.com/q/49068425
has comment: http://stackoverflow.com/comment/85202914
has body: Is it normal that I get lower accuracy when training on multi GPU? For example, when I train on single GPU with n batch size, I got 63% accuracy. However, when I train with 4 GPUs with n batch size for each GPU, I got only 58% accuracy. Both cases were trained with 100 epochs I guess the averaging of gradient somehow makes it difficult for the optimizer. Anybody experienced the same thing ?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49547095
downvote count: 1
has comment: http://stackoverflow.com/comment/85160753
has title: Tensorflow low accuracy when training with multi GPU
has comment: http://stackoverflow.com/comment/85146202
score: -1
has comment: http://stackoverflow.com/comment/85148596
tagged with: tensorflow
type: Question
upvote count: 0
tagged with: deep-learning
answer count: 1
has comment: http://stackoverflow.com/comment/85143227
has comment: http://stackoverflow.com/comment/85203365
favorite count: 0

javascript
tags question: http://stackoverflow.com/q/49028567
tags question: http://stackoverflow.com/q/48997100
tags question: http://stackoverflow.com/q/49034536
tags question: http://stackoverflow.com/q/48969332
tags question: http://stackoverflow.com/q/49036162
tags question: http://stackoverflow.com/q/49033714
tags question: http://stackoverflow.com/q/49045755
tags question: http://stackoverflow.com/q/49090165
tags question: http://stackoverflow.com/q/49019202
tags question: http://stackoverflow.com/q/48996797
tag name: javascript
tags question: http://stackoverflow.com/q/48968852
tags question: http://stackoverflow.com/q/49063586
tags question: http://stackoverflow.com/q/48999626
tags question: http://stackoverflow.com/q/49051457
tags question: http://stackoverflow.com/q/48993988
tags question: http://stackoverflow.com/q/49037998
tags question: http://stackoverflow.com/q/48993316
type: Tag
tags question: http://stackoverflow.com/q/49040807
tags question: http://stackoverflow.com/q/49060790
tags question: http://stackoverflow.com/q/49072664
tags question: http://stackoverflow.com/q/49109884
tags question: http://stackoverflow.com/q/48964373
tags question: http://stackoverflow.com/q/49022274
tags question: http://stackoverflow.com/q/49069071
tags question: http://stackoverflow.com/q/49103628
tags question: http://stackoverflow.com/q/49107734
tags question: http://stackoverflow.com/q/48968536
tags question: http://stackoverflow.com/q/49069683
tags question: http://stackoverflow.com/q/49006795
tags question: http://stackoverflow.com/q/48985758
tags question: http://stackoverflow.com/q/48994936
tags question: http://stackoverflow.com/q/49094724
tags question: http://stackoverflow.com/q/48990631
tags question: http://stackoverflow.com/q/49102430
tags question: http://stackoverflow.com/q/49018512
tags question: http://stackoverflow.com/q/49036297
tags question: http://stackoverflow.com/q/48981746
tags question: http://stackoverflow.com/q/49010415
tags question: http://stackoverflow.com/q/49075975
tags question: http://stackoverflow.com/q/49090456
tags question: http://stackoverflow.com/q/49057247
tags question: http://stackoverflow.com/q/49036546

http://stackoverflow.com/comment/85083497
type: AnswerComment
score: 0
type: Comment
has text: I would guess the formatting is not the same. Can you pastebin the file?
comment on: http://stackoverflow.com/a/49036562

http://stackoverflow.com/comment/85088938
comment on: http://stackoverflow.com/q/49041512
score: 0
has text: By limiting put, I mean that you manipulate the entire array in memory. Build up a matrix of colors the same size as your image. Change the elements of the matrix in any order you want, and then do a single put to refresh the entire image in one shot.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85168523
type: Comment
type: QuestionComment
score: 0
has text: Using threading, my url call is now asynchronous it looks like the problem is gone. So problem seem to be solved but i still don't understand why
comment on: http://stackoverflow.com/q/49081092

http://stackoverflow.com/q/49031878
tagged with: package
tagged with: pip
accepted answer: http://stackoverflow.com/a/49032549
has comment: http://stackoverflow.com/comment/85068771
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85068855
has title: Download own module with pip, "No module named ..."
has body: I am in the process of building my own Python module, just to get a hang of how it works. My Python is decent, but I have never build or submitted any packages before. I followed a guide on Python Hosted as well as the official setuptools documentation and this article on python.org. However, I still can't get this to work. The package structure, with three modules (FileHelpers, TypeHelpers, XmlHelpers), looks like this: PyLT3/ |- .git/ |- .idea/ |- setup.py |- __init__.py |- README.rst |- LICENSE.txt |- .gitignore |- FileHelpers.py |- TypeHelpers.py |- XmlHelpers.py Contents of setup.py: from setuptools import setup, find_packages setup( name='PyLT3', version='0.1.3', description='A collection of helper functions and NLP scripts', long_description='During my time working on the PhD project PreDict, I have written and gathered a bunch of useful functions. They are collected here as part of the PyLT3 package.', keywords='nlp xml file-handling helpers', packages=find_packages(), url='https://github.com/BramVanroy/PyLT3', author='Bram Vanroy', author_email='bramvanroy@hotmail.com', license='MIT', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], project_urls = { 'Bug Reports': 'https://github.com/BramVanroy/PyLT3/issues', 'Source': 'https://github.com/BramVanroy/PyLT3', }, python_requires='&gt;=3.6', ) Contents of MANIFEST.in: prune .idea/* With this data, I create a distribution: python setup.py sdist And a wheel: python setup.py bdist_wheel And the distribution is then uploaded to PyPi: twine upload dist/* To test this out, I download the package with pip: pip install PyLT3 (Also used pip3.) It successfully installs. But when I then try a simple import PyLT3, I get an error import PyLT3 ModuleNotFoundError: No module named 'PyLT3' This is odd, …
has comment: http://stackoverflow.com/comment/85068391
score: 4
tagged with: pypi
has comment: http://stackoverflow.com/comment/85069290
upvote count: 4
has comment: http://stackoverflow.com/comment/85069332
has comment: http://stackoverflow.com/comment/85068576
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49032549
favorite count: 0
tagged with: python
tagged with: setup.py

http://stackoverflow.com/q/48986917
has comment: http://stackoverflow.com/comment/84980918
has comment: http://stackoverflow.com/comment/84980672
accepted answer: http://stackoverflow.com/a/48991071
has comment: http://stackoverflow.com/comment/84978951
has title: pyspark dataframe foreach to fill a list
tagged with: python
tagged with: foreach
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30882268
has comment: http://stackoverflow.com/comment/84981223
has answer: http://stackoverflow.com/a/48991071
has comment: http://stackoverflow.com/comment/84981635
has comment: http://stackoverflow.com/comment/84982163
has comment: http://stackoverflow.com/comment/84978648
has comment: http://stackoverflow.com/comment/84981423
type: Question
has comment: http://stackoverflow.com/comment/84986864
tagged with: apache-spark-sql
tagged with: pyspark
answer count: 1
has comment: http://stackoverflow.com/comment/84980199
has comment: http://stackoverflow.com/comment/84983557
linked to: http://stackoverflow.com/q/46304475
has comment: http://stackoverflow.com/comment/84982516
score: 0
tagged with: apache-spark
has body: I'm working in Spark 1.6.1 and Python 2.7 and I have this thing to solve: Get a dataframe A with X rows For each row in A, depending on a field, create one or more rows of a new dataframe B Save that new dataframe B The solution that I've come up right now, is to collect dataframe A, go over it, append to a list the row(s) of B and then create the dataframe B from that list. With this solution i obviously lose all the perks of working with dataframes and I would like to use foreach, but I can't find a way to make this work. I've tried this so far: Pass an empty list to the foreach function (this just ignores the foreach function and doesn't do anything) Create a global variable to be use in the foreach function (complains that it can't find the list) Does anyone has any ideas? Thank you ----------------------EDIT: Examples of the things I've tried: def f(row, list): if row.one: list += [Row(type='one', field='ok')] else: list += [Row(type='one', field='ok')] list += [Row(type='two', field='nok')] list = [] dfA.foreach(lambda x : f(x, list)) As I mention, this does nothing, it doesn't execute the function And I've also tried (which list defined at the beginning of the class): global list def f(row): if row.one: list += [Row(type='one', field='ok')] else: list += [Row(type='one', field='ok')] list += [Row(type='two', field='nok')] dfA.foreach(list) ---------EDIT 2: What I'm doing right now is: list = [] for row in dfA.collect(): string = re.search(a_regex, row['raw']) if string: dates = re.findall(date_regex, string.group()) for date in dates: date_string = datetime.strptime(date, '%Y-%m-%d').date() list += [Row(event_type='1', event_date=date_string)] b_string = re.search(b_regex, row['raw']) if b_string: dates = re.findall(date_regex, b_string.group()) for date in dates: scheduled_to = datetime.strptime(date, '%Y-%m-%d').date() list += [Row(event_type='2', event_date= date_string)] and then: dfB = self._sql_context.createDataFrame(list) dfA is given by other process…

http://stackoverflow.com/comment/85143141
type: QuestionComment
comment on: http://stackoverflow.com/q/49067738
score: 0
has text: Does it work if you explicitly point to the key file of the service account with `export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json"` prior to running the Python script?
type: Comment

http://stackoverflow.com/comment/84983534
comment on: http://stackoverflow.com/q/48989472
has text: The output is `0`?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48976237
score: 1
has comment: http://stackoverflow.com/comment/84958002
type: Question
tagged with: raspberry-pi
downvote count: 0
tagged with: rfid
favorite count: 0
has comment: http://stackoverflow.com/comment/115739959
answer count: 0
type: UnansweredQuestion
tagged with: gpio
upvote count: 1
tagged with: python
has body: I have an RFID scanner connected to my Raspberry Pi and I am trying to read the input through python. I am reading the input through UART and currently have this as my base reading script: import serial port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=0.2) print("Reading RFID Tags now!") while True: rcv = port.readling() if len(rcv) > 10: print("Tag Detected: " + rcv) Currently, this is the string that I am getting: 070080BB5B67 (Pastebin as StackOverflow is removing the special characters STX and ETX preceding and following those shown (Start of TeXt and End, resp.)) and it should be: 0008436571 I can't work out the method of decoding the value. I have been trying for several days now and have had no luck. If any of you could help that would be amazing. (sorry if I missed anything out. I'm new to StackOverflow, writing questions that is)
has title: Decoding Unknown String in Python

http://stackoverflow.com/a/49071825
has comment: http://stackoverflow.com/comment/85217245
has comment: http://stackoverflow.com/comment/85149145
has comment: http://stackoverflow.com/comment/85149291
has comment: http://stackoverflow.com/comment/85149770
score: 0
has comment: http://stackoverflow.com/comment/85149540
type: Answer
answers question: http://stackoverflow.com/q/49071248
has comment: http://stackoverflow.com/comment/85149720
has comment: http://stackoverflow.com/comment/85272606
has comment: http://stackoverflow.com/comment/85152278
has comment: http://stackoverflow.com/comment/85149217
has comment: http://stackoverflow.com/comment/85149342
has body: Okay since I don't have the module you're using I can't really test the code but here is my idea: def remove(self, idx): elem = self._theArray[idx] new_array = Array(self._capacity-1) for i in range(0, self._numItems): if i != idx: new_array.append(self._theArray[i]) self._theArray = new_array return elem def insert(self, index, element) : assert index &gt;= 0 and index &lt;= self._numItems, "Index out of range." if self._numItems == self._capacity: self._expandArray() for i in reversed(range(index, self._numItems)): self._theArray[i+1] = self._theArray[i] self._theArray[index] = element
has comment: http://stackoverflow.com/comment/85149247
has comment: http://stackoverflow.com/comment/85149309

http://stackoverflow.com/comment/84961206
type: QuestionComment
comment on: http://stackoverflow.com/q/48978063
score: 0
type: Comment
has text: "I am overwriting the prior keys vs. appending the dictionary entry." yes, of course. `dict` objects have unique keys, you cannot "append" to dicts, you assign a value to a key. If you assign to the same key, it overwrites. Not sure exactly what you are trying to accopmlish, what would be an example input/output?

http://stackoverflow.com/a/49049400
accepted answer of: http://stackoverflow.com/q/49048370
has body: From 6.15 of python documentation Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. In the following lines, expressions will be evaluated in the arithmetic order of their suffixes: expr1, expr2, expr3, expr4 (expr1, expr2, expr3, expr4) {expr1: expr2, expr3: expr4} expr1 + expr2 * (expr3 - expr4) &lt;----- This is of importance to us. expr1(expr2, expr3, *expr4, **expr5) expr3, expr4 = expr1, expr2 So here the functions will be called in order from left to right. So any of the changes you will see will be due to the functions called from left to right. And yes in python function calls are expressions.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49048370
type: Answer
upvote count: 10
score: 10

http://stackoverflow.com/q/49084535
has comment: http://stackoverflow.com/comment/85175507
score: -1
has comment: http://stackoverflow.com/comment/85174370
has body: A digital image consists of multiple pixels, each of them has some values which indicate the intensity of the corresponding colors. If I want to work with images I can simply read or change pixels. For scientific purposes there is for example the PPM-Format, which encodes each pixel one by one in readable ASCII format. Is there a similar way to read or modify audio files? How is audio edited? What are the building blocks, the smallest parts, the “pixels” of audio recordings? Is there an ASCII sound file format?
has answer: http://stackoverflow.com/a/49084672
answer count: 1
has title: How to work with audio files?
favorite count: 0
has comment: http://stackoverflow.com/comment/85174344
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: audio
has comment: http://stackoverflow.com/comment/85174614
has comment: http://stackoverflow.com/comment/85174325
upvote count: 1
type: Question

http://stackoverflow.com/q/49032259
has comment: http://stackoverflow.com/comment/85070335
score: 1
has body: I would like to measure time a user needs to take a decision (or just pressing the "submit" button in this case). In the python itself I normally measure the time of code with start_time = time.clock() time_diff = start_time - time.clock() However, in the web application I can't wrap my head around how it should work. @app.route('/survey') def main(): user = request.cookies.get('user') if not user: return redirect(url_for('login')) msg = '' word = request.args.get('word') score = request.args.get('score') start_time = time.clock() if score: time_diff = start_time - time.clock() record_to_csv(user, word, score, time_diff) return render_template( 'main.html', self_url=url_for('main'), word=choice(words), msg=msg, ) My first idea was just to put start_time before "if score" and then measure the time right after. But somehow I always get the same time of -4.10546782348e-07. So I wonder if the problem is that I fail to put the time measurement on the right place in the loop or if it is a completely wrong approach. Any comments are very appreciated.
upvote count: 1
has answer: http://stackoverflow.com/a/49073475
type: Question
answer count: 2
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/85069203
has answer: http://stackoverflow.com/a/49053708
favorite count: 0
has title: Measure time between submits in Flask
type: UnansweredQuestion
tagged with: time
tagged with: python

http://stackoverflow.com/q/49040025
has comment: http://stackoverflow.com/comment/85087993
upvote count: 3
type: UnansweredQuestion
type: Question
score: 3
has comment: http://stackoverflow.com/comment/85109695
has title: Error reading shapefiles using geopandas in Python
has comment: http://stackoverflow.com/comment/85153325
has comment: http://stackoverflow.com/comment/85160328
downvote count: 0
has comment: http://stackoverflow.com/comment/85153435
favorite count: 0
tagged with: shapefile
tagged with: geopandas
has body: I have a line shapefile file and I'm using the following code to read in it. import geopandas as gpd line = gpd.read_file(r"./line_UTM16.shp") GeoDataframe 'line' exist though with the following errors: INFO model.py:56 Reading line shapefile. WARNING collection.py:145 GDAL data files not located, GDAL_DATA not set WARNING collection.py:145 PROJ data files not located, PROJ_LIB not set DEBUG collection.py:203 Got coordinate system DEBUG collection.py:247 Index: 0 DEBUG collection.py:210 Got coordinate system DEBUG collection.py:404 Flushed buffer DEBUG collection.py:406 Stopped session I'm using Python 3.6, I checked my package version: geopandas 0.3.0 fiona 1.7.10 gdal 2.2.3 proj4 4.9.3 How can I solve it, I think it is a data installation problem? The code runs fine for many days, and suddenly it is reporting the errors. Thanks! UPDATE: I did some research and it says that gdal only works with Python3.5, so I created a separate environment with Python3.5 and all the packages. The problem still exists! GDAL_DATA not set and PROJ_LIB not set. Not sure if this is a software bug?
tagged with: python
answer count: 0

http://stackoverflow.com/a/49060515
answers question: http://stackoverflow.com/q/49060351
has body: You have small error in your code. On line 102 you call: matrice_similarite = calculer_scores_similarite(reseau) and function calculer_scores_similarite doesn't have return value you need to add in that function return matrice_similarite as last line of function.
has comment: http://stackoverflow.com/comment/85126446
score: 0
type: Answer

http://stackoverflow.com/comment/86605864
type: QuestionComment
has text: I am having similar confusion, however, I guess you can try: mod = PanelOLS(df.y, df['rid'], entity_effects=True) and then df['pid'] not sure if that correct or not, I am brainstorming here.
comment on: http://stackoverflow.com/q/49067495
score: 0
type: Comment

http://stackoverflow.com/a/48970499
type: Answer
has body: It sounds like you just need to be a little more careful about filtering out the parentheses and commas. You could use something like this, which should be pretty robust: line = "(1,1) (1,7)\n" for tup in line.split(): print(tup) # drop parentheses and split at the comma vals = tup[1:-1].split(',') r = int(vals[0]) c = int(vals[1]) print(r) print(c) Result: (1,1) 1 1 (1,7) 1 7 But actually, your code should work fine too if all the values are single digits: line = "(1,1) (1,7)\n" for word in line.split(): print(word) r = int(word[1]) c = int(word[3]) print(r) print(c) # gives same result
score: 4
accepted answer of: http://stackoverflow.com/q/48970391
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48970391

http://stackoverflow.com/q/49087864
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/49088298
has title: Plotting 6D in python. Plot the rotational angles(Roll, pitch and yaw)
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am currently trying to plot 6D in python using matplotlib. The only problem is I do not know how to plot 6D. I am able to plot in 3D, but I am working with quadcopters and it would be best if I can plot also the roll, pitch and yaw. I am able to receive its roll, pitch and yaw from the camera. The only problem I have now is to graph the received rotational angles(roll, pitch and yaw).
tagged with: matplotlib
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/85181738

http://stackoverflow.com/q/49035093
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85077535
has comment: http://stackoverflow.com/comment/85075484
score: 0
upvote count: 1
has body: I have a custom python module I'm working on and am confused how I should import modules into other modules. I want to use bits and pieces of some modules within others and keep getting an error: ImportError: cannot import name NameOfModule I'm assuming there's some sort of circular reference that's causing the issue but I'm not sure if I need to add something to __init__.py, or if there's a specific way of importing the modules into each other, or if I should change my folder structure? If I want to be able to use some function from mod1.py within mod2.py how should I go about setting up the import statements? My current folder structure is: FolderName -__init__.py -mod1.py -mod2.py -mod3.py -mod4.py Sample code: __init__.py is empty mod1.py: from . import mod2 mod2.py: from . import mod1
has answer: http://stackoverflow.com/a/49035369
downvote count: 1
type: Question
has title: How to Correctly Import Python Modules and Avoid Import Errors
has comment: http://stackoverflow.com/comment/85075193
tagged with: python-2.7
tagged with: python-import
has comment: http://stackoverflow.com/comment/85075158

http://stackoverflow.com/q/48975310
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/48975450
tagged with: http://stackoverflow.com/tag/html
has body: In Python 3 I need to scrape a lot of information on sites that are in tables (The first site is: http://www.portaltransparencia.gov.br/ceis?pagina=1) from bs4 import BeautifulSoup import requests from time import sleep def sopa(link): res = requests.get(link) sopa = BeautifulSoup(res.text, "lxml") blocos = sopa.findAll("tr", {"class": "nome-divergente"}) return blocos planilha = [] for i in range(1,819): link = "http://www.portaltransparencia.gov.br/ceis?pagina=" link = link + str(i) print(link) blocos = sopa(link) sleep(random.uniform(0.2, 10)) conta = 0 print(blocos) input("# This is the content of blocos") for linha in blocos: if conta > 0: cnpj = linha.find("a").text.strip() link = linha.find("href") nome = linha.find("td")[1].text.strip() tipo = linha.find("td")[2].text.strip() data = linha.find("td")[3].text.strip() nome_orgao = linha.find("td")[4].text.strip() uf = linha.find("td")[5].text.strip() dicionario = {"cnpj": cnpj, "link": link, "nome": nome, "tipo": tipo, "data": data, "nome_orgao": nome_orgao, "uf": uf} print(dicionario) planilha.append(dicionario) conta = conta + 1 What is shown: http://www.portaltransparencia.gov.br/ceis?pagina=1 [ 08.307.727/0001-28 TECK SHOCK COMERCIO E SERVICO EIRELI - ME ** Suspensão - Lei de Licitações 16/05/2018 Governo do Estado do Espírito Santo (ES) ES , 05.236.586/0001-01 META TERCEIRIZACOES E SERVICOS LTDA ** Suspensão - Legislação Estadual 26/12/2018 Governo do Estado da Bahia BA , 05.236.586/0001-01 META TERCEIRIZACOES E SERVICOS LTDA ** Suspensão - Legislação Estadual 22/08/2018 Governo do Estado da Bahia (BA) BA , 05.236.586/0001-01 META TERCEIRIZACOES E SERVICOS LTDA ** Inidoneidade - Legislação Estadual Governo do Estado da Bahia (BA) BA , 04.125.082/0001-51 PRIMEIRA OPCAO LOCACAO TRANSPORTE E TURISMO LTDA - ME ** Inidoneidade - Lei da ANTT e ANTAQ 16/01/2021 AGÊNCIA NACIONAL DE TRANSPORTES TERRESTRES DF ] # This is the content of blocos --------------------------------------------------------------------------…
tagged with: beautifulsoup
has title: In Python how do I scrape tables with multiple ?
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48975450
type: Question

http://stackoverflow.com/comment/84954732
score: 1
has text: Is it neccesary to cythonize the function? If you are using NumPy you should vectorize your code. I think that ```results = a[:,:,np.newaxis]-b``` gets the same output.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48974747

http://stackoverflow.com/q/49014601
favorite count: 0
has comment: http://stackoverflow.com/comment/85034042
tagged with: python-3.x
has title: Python 3: How to best iterate over all lines in a big file (+1 million lines) in a random order
has answer: http://stackoverflow.com/a/49014801
has comment: http://stackoverflow.com/comment/85034469
linked to: http://stackoverflow.com/q/9371079
has comment: http://stackoverflow.com/comment/85035638
accepted answer: http://stackoverflow.com/a/49015723
has body: Ok, so I have multiple textfiles, each containing well over 500.000 or even 1.000.000 lines. Currently I do something like this: import random def line_function(line): # Do something with given line def random_itteration(filepath): with open(filepath) as f: lines = f.readlines() random.shuffle(lines) for line in lines: result = line_function(line) The thing is that the Python Docs on random.shuffle() clearly state (emphasis added by me): Note that even for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator. So the question is: What would be the fastest and most efficient way to make my setup work as intended? Further info: There is a reason why I want to apply line_function() to a random line and not simply iterate over them in the sequence they are in. Also note that I highly prefer to only process each line once. Finally, shuffling the textfile up front, or dividing it into smaller files unfortunately isn't an option. And isn't what I am asking. Any insights are more then welcome! Thnx in advance guys.
tagged with: python
type: AnsweredQuestion
tagged with: shuffle
has comment: http://stackoverflow.com/comment/85034044
downvote count: 3
tagged with: loops
upvote count: 7
has comment: http://stackoverflow.com/comment/85034417
type: Question
has comment: http://stackoverflow.com/comment/85035452
has answer: http://stackoverflow.com/a/49015723
possible better answer: http://stackoverflow.com/a/49014742
score: 4
has comment: http://stackoverflow.com/comment/85034912
has comment: http://stackoverflow.com/comment/85034099
has answer: http://stackoverflow.com/a/49014742
has comment: http://stackoverflow.com/comment/85034164
tagged with: random
answer count: 3
has comment: http://stackoverflow.com/comment/85034379
has comment: http://stackoverflow.com/comment/85035595
has comment: http://stackoverflow.com/comment/85034471

http://stackoverflow.com/comment/84971797
type: QuestionComment
comment on: http://stackoverflow.com/q/48983557
score: 3
has text: Show the attempts that you have done.
type: Comment

http://stackoverflow.com/q/48968302
accepted answer: http://stackoverflow.com/a/48969276
linked to: http://stackoverflow.com/q/406121
upvote count: 2
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48968711
favorite count: 0
tagged with: python
has body: I have my first serious question in python. I have a few nested lists that I need to convert to pandas DataFrame. Seems easy, but what makes it challenging for me: - the lists are huge (so the code needs to be fast) - they are nested - when they are nested, I need combinations. So having this input: la = ['a', 'b', 'c', 'd', 'e'] lb = [[1], [2], [3, 33], [11,12,13], [4]] lc = [[1], [2, 22], [3], [11,12,13], [4]] I need the below as output la lb lc a 1 1 b 2 2 b 2 22 c 3 3 c 33 3 d 11 11 d 11 12 d 11 13 d 12 11 d 12 12 d 12 13 d 13 11 d 13 12 d 13 13 e 4 4 Note that I need all permutations whenever I have a nested list. At first I tried simply: import pandas as pd pd.DataFrame({'la' : [x for x in la], 'lb' : [x for x in lb], 'lc' : [x for x in lc]}) But looking for rows that need expanding and actually expanding (a huge) DataFrame seemed harder than tinkering around the way I create the DataFrame. I looked at some great posts about itertools (Flattening a shallow list in Python ), the documentation (https://docs.python.org/3.6/library/itertools.html) and generators (What does the "yield" keyword do?), and came up with something like this: import itertools def f(la, lb, lc): tmp = len(la) == len(lb) == len(lc) if tmp: for item in range(len(la)): len_b = len(lb[item]) len_c = len(lc[item]) if ((len_b>1) or (len_c>1)): yield list(itertools.product(la[item], lb[item], lc[item])) ## above: list is not the result I need, ## without it it breaks (not an iterable) else: yield (la[item], lb[item], lc[item]) else: print('error: unequal length') which I test my_gen =f(lit1, lit2, lit3) pd.DataFrame.from_records(my_gen) which... well... breaks when i yield itertools (it has no length), and creates a wrong data structure after I cast itertools to an iterable. My questions are as follow: how can I fix that issue with yielding itertools? is this efficient? In real application I will be creating the lists by parsing a file and they will be huge... Any performance tips or better solu…
score: 2
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/231767
downvote count: 0
type: Question
has title: multiple nested lists with permutations to pandas
tagged with: python-itertools
has answer: http://stackoverflow.com/a/48968711
has answer: http://stackoverflow.com/a/48969276

http://stackoverflow.com/q/48974903
has comment: http://stackoverflow.com/comment/84957188
has body: So i have a problem. I'm trying to make my imports faster, so i started using multiprocessing module to split a group of imports into two functions, and then run each on separate core, thus speeding the imports up. But now the code will not recognize the modules at all. What am I doing wrong ? import multiprocessing def core1(): import wikipedia import subprocess import random return wikipedia, subprocess, random def core2(): from urllib import request import json import webbrowser return request, json, webbrowser if __name__ == "__main__": start_core_1 = multiprocessing.Process(name='worker 1', target=core1, args = core2()) start_core_2 = multiprocessing.Process(name='worker 2', target=core2, args = core1()) start_core_1.start() start_core_2.start() while True: user = input('[!] ') with request.urlopen('https://api.wit.ai/message?v=20160511&amp;q=%s&amp;access_token=Z55PIVTSSFOETKSBPWMNPE6YL6HVK4YP' % request.quote(user)) as wit_api: # call to wit.ai api wit_api_html = wit_api.read() wit_api_html = wit_api_html.decode() wit_api_data = json.loads(wit_api_html) intent = wit_api_data['entities']['Intent'][0]['value'] term = wit_api_data['entities']['search_term'][0]['value'] if intent == 'info_on': with request.urlopen('https://kgsearch.googleapis.com/v1/entities:search?query=%s&amp;key=AIzaSyCvgNV4G7mbnu01xai0f0k9NL2ito8vY6s&amp;limit=1&amp;indent=True' % term.replace(' ', '%20')) as response: google_knowledge_base_html = response.read() google_knowledge_base_html = google_knowledge_base_html.decode() google_knowledge_base_data = json.loads(google_knowledge_base_html) print(google_knowledge_base_data['itemListElement'][0]['result']['detailedDescription']['articleBody']) else: print('Something')
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/84958801
has comment: http://stackoverflow.com/comment/84957606
has answer: http://stackoverflow.com/a/48978968
has comment: http://stackoverflow.com/comment/84958915
has comment: http://stackoverflow.com/comment/84958339
has title: Transferring modules between two processes with python multiprocessing
linked to: http://stackoverflow.com/q/48835700
linked to: http://stackoverflow.com/q/2790828
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84957641
has comment: http://stackoverflow.com/comment/84958842
has comment: http://stackoverflow.com/comment/84958804
has comment: http://stackoverflow.com/comment/84957888
favorite count: 0
accepted answer: http://stackoverflow.com/a/48978968
has comment: http://stackoverflow.com/comment/84957869
tagged with: python
has comment: http://stackoverflow.com/comment/84957566
type: AnsweredQuestion
score: 2
upvote count: 2

http://stackoverflow.com/comment/84942322
score: 0
type: AnswerComment
type: Comment
has text: It's really worth noting when you suggest this kind of thing that order isn't guaranteed.
comment on: http://stackoverflow.com/a/48968391

http://stackoverflow.com/a/49034370
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49028675
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49028675
type: Answer
score: 1
upvote count: 1
has body: Here is a solution to your refined question: from collections import defaultdict from itertools import combinations data = {'Company':['A','A','A','A','B','B','B','B','C','C','C','C','D','D','D','D'], 'Individual': [1,2,3,4,1,5,6,7,1,8,9,10,10,11,12,13]} d = defaultdict(set) for i, j in zip(data['Individual'], data['Company']): d[i].add(j) res = {k: sorted(map(sorted, combinations(v, 2))) for k, v in d.items()} # {1: [['A', 'B'], ['A', 'C'], ['B', 'C']], # 2: [], # 3: [], # 4: [], # 5: [], # 6: [], # 7: [], # 8: [], # 9: [], # 10: 'C', 'D', # 11: [], # 12: [], # 13: []}

http://stackoverflow.com/comment/85213070
comment on: http://stackoverflow.com/a/49103013
score: 1
has text: Kudos for your effort and explanation. This works without any issues.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85126281
has text: Whar error are you getting?
comment on: http://stackoverflow.com/q/49060671
score: 5
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48988470
type: AcceptedAnswer
score: 0
type: Answer
has body: You can use pickle for this, e.g : import pickle my_list = [1,2,3] pickle.dump( my_list, open( "save.p", "wb" ) ) my_list = pickle.load( open( "save.p", "rb" ) ) This will save the type and value of your object. More information about pickle usage can be found here : https://docs.python.org/3/library/pickle.html
accepted answer of: http://stackoverflow.com/q/48988428
answers question: http://stackoverflow.com/q/48988428

http://stackoverflow.com/comment/85020845
score: 1
comment on: http://stackoverflow.com/q/49000463
has text: Don't use pygtk and Gtk2. It will be obsolete in a few more years. [Here](http://python-gtk-3-tutorial.readthedocs.io/en/latest/layout.html#id1) is a Gtk3 tutorial using GtkGrid.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85080137
type: Comment
has text: Welcome to SO. I formatted your code so that it can be read more easily. Since this is python and your code did not contain any indentation please check that I guessed correctly. Additionally, please add the complete error message you get to your question using the edit function.
type: QuestionComment
comment on: http://stackoverflow.com/q/49034826
score: 0

http://stackoverflow.com/comment/85020882
type: AnswerComment
has text: Thanks a lot! I think I made a mistake in selecting the test set index in my example. And your solution did help a lot.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49006255

http://stackoverflow.com/comment/85948703
type: QuestionComment
type: Comment
has text: Just an update: I have achieved this using a ColumnDataSource, the stream function and an automatic callback.
score: 0
comment on: http://stackoverflow.com/q/49100810

http://stackoverflow.com/q/49085503
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49085720
tagged with: pip
downvote count: 1
tagged with: scipy
has body: PS C:\Users\Marko&gt; pip install scipy Collecting scipy Downloading scipy-1.0.8-cp36-none-win32.whl (26.0MB) 22% |? | 5.8MB 936kB/s eta 0:00:22Exception: Traceback (most recent call last): File "c:\python\lib\site-packages\pip\_vendor\requests\packages\urllib3\response.py", line 232, in _error_catcher yield File "c:\python\lib\site-packages\pip\_vendor\requests\packages\urllib3\response.py", line 314, in read data = self._fp.read(amt) File "c:\python\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 60, in read data = self.__fp.read(amt) File "c:\python\lib\http\client.py", line 449, in read n = self.readinto(b) File "c:\python\lib\http\client.py", line 493, in readinto n = self.fp.readinto(b) File "c:\python\lib\socket.py”, line 586, in readinto return self._sock.recv_into(b) File "c:\python\lib\ssl.py", line 1009, in recv_into return self.read(nbytes, buffer) File "c:\python\lib\ssl.py", line 871, in read return self._sslobj.read(len, buffer) File "c:\python\lih\ssl.py”, line 631, in read v = self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python\lio\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\python\lib\site-packages\pip\commands\install.py”, line 324, in run requirement_set.prepare_files(finder) File “c:\python\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=seif.ignore_dependencies)) File "c:\python\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hasnes=hashes) File ”c:\python\lib\site-packages\pip\download .py", line 821, in unpack_url hashes=hashes File "c:\python\lib\site-packages\pip\download.py", line 659, in unpack_http_url hashes) File "c:\python\lib\site-packages\pip\download.py", line 882, in _download_http_url _download_url(resp, link, content_file, hashes) File "c:\pytho…
type: Question
linked to: http://stackoverflow.com/q/43298872
has title: Cant install scipy through pip
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85176911
has comment: http://stackoverflow.com/comment/85176755
tagged with: python
has answer: http://stackoverflow.com/a/49085720
has comment: http://stackoverflow.com/comment/85176381

http://stackoverflow.com/comment/85235928
comment on: http://stackoverflow.com/q/49099049
score: 0
type: Comment
type: QuestionComment
has text: gonna be really hard to help you with this if you don't provide the geometries that are causing the issue.

http://stackoverflow.com/comment/85110605
has text: @Steven My mistake, your original suggestion works fine. And the problem is resolved for most part but is it possible to know why I'm getting an error while adding the column directly to dataframe?
type: QuestionComment
comment on: http://stackoverflow.com/q/49051910
score: 0
type: Comment

http://stackoverflow.com/comment/84992288
type: QuestionComment
has text: Seems to be the same as [this question](https://stackoverflow.com/questions/44078409/matplotlib-semi-log-plot-minor-tick-marks-are-gone-when-range-is-large).
score: 1
comment on: http://stackoverflow.com/q/48985874
type: Comment

http://stackoverflow.com/a/51116910
has comment: http://stackoverflow.com/comment/117237791
has comment: http://stackoverflow.com/comment/110423898
upvote count: 694
has comment: http://stackoverflow.com/comment/106600497
has comment: http://stackoverflow.com/comment/89254764
has comment: http://stackoverflow.com/comment/120701446
has body: How does asyncio work? Before answering this question we need to understand a few base terms, skip these if you already know any of them. Generators Generators are objects that allow us to suspend the execution of a python function. User curated generators are implemented using the keyword yield. By creating a normal function containing the yield keyword, we turn that function into a generator: >>> def test(): ... yield 1 ... yield 2 ... >>> gen = test() >>> next(gen) 1 >>> next(gen) 2 >>> next(gen) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration As you can see, calling next() on the generator causes the interpreter to load the test's frame, and return the yielded value. Calling next() again, causes the frame to load again into the interpreter stack, and continues on yielding another value. By the third time next() is called, our generator was finished, and StopIteration was thrown. Communicating with a generator A less-known feature of generators is the fact that you can communicate with them using two methods: send() and throw(). >>> def test(): ... val = yield 1 ... print(val) ... yield 2 ... yield 3 ... >>> gen = test() >>> next(gen) 1 >>> gen.send("abc") abc 2 >>> gen.throw(Exception()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in test Exception Upon calling gen.send(), the value is passed as a return value from the yield keyword. gen.throw() on the other hand, allows throwing Exceptions inside generators, with the exception raised at the same spot yield was called. Returning values from generators Returning a value from a generator, results in the value being put inside the StopIteration exception. We can later on recover the value from the exception and use it to our needs. >>> def test(): ... yield 1 ... return "abc" ... >>> gen = test() >>> next(gen) 1 >>> try: ... next(gen) ... except StopIteration as exc: ... print(exc.value) ... abc Behold, a new keyword: yield from…
has comment: http://stackoverflow.com/comment/89298225
downvote count: 1
has comment: http://stackoverflow.com/comment/117248692
has comment: http://stackoverflow.com/comment/91655714
has comment: http://stackoverflow.com/comment/106628531
has comment: http://stackoverflow.com/comment/89221287
has comment: http://stackoverflow.com/comment/120749064
has comment: http://stackoverflow.com/comment/106601812
has comment: http://stackoverflow.com/comment/89269465
has comment: http://stackoverflow.com/comment/89228516
has comment: http://stackoverflow.com/comment/89228413
has comment: http://stackoverflow.com/comment/110409802
has comment: http://stackoverflow.com/comment/89328279
has comment: http://stackoverflow.com/comment/107976664
has comment: http://stackoverflow.com/comment/117244498
has comment: http://stackoverflow.com/comment/110421652
has comment: http://stackoverflow.com/comment/106600923
type: Answer
has comment: http://stackoverflow.com/comment/106601079
has comment: http://stackoverflow.com/comment/139198185
score: 693
answers question: http://stackoverflow.com/q/49005651
has comment: http://stackoverflow.com/comment/108004981

http://stackoverflow.com/comment/85196828
type: QuestionComment
has text: Sorry for typo in question. Can you tell now
comment on: http://stackoverflow.com/q/49095889
score: 0
type: Comment

http://stackoverflow.com/a/48965322
has comment: http://stackoverflow.com/comment/84937514
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48965229
type: Answer
answers question: http://stackoverflow.com/q/48965229
score: 2
has body: [EDIT after question was updated with picture] So your top-level app is called a you can see this in the picture just under "Information" on the left in the picture. Then you have a module called A, which you can see the file A.py just under the folder a. This module A has the class called A so when you do from a import A you are importing the file A.py That file has a class A() which has def method(p1, p2) You say A.A.method() is working... and that would be correct It now becomes from a import A print(A.A.method(p1,p2) Alternatively import a print(a.A.A.method(p1,p2) Or from a.A import A print(A.method(p1, p2) My advice: start using some more descriptive names, not a for top level package and A for module and A for class
downvote count: 0
has comment: http://stackoverflow.com/comment/84936700

http://stackoverflow.com/comment/84978531
comment on: http://stackoverflow.com/a/48984975
has text: thankyou do you have any advice about the model fields ? for example do you prefer productAllTags or product_all_tags or something else it will become our tables name in db
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85059909
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49026963
score: 0
has text: There are a few things I wanted but mainly I find the seaborn call much more obvious than going through the np.meshgrid preparation for pcolormesh, which I find confusing (I tend to end up with reversed axes)

http://stackoverflow.com/a/48978505
type: Answer
has body: A pythonic solution would be if not item['business_name']: Do something Because both None and an empty list have boolean value of false
upvote count: 1
answers question: http://stackoverflow.com/q/48978451
score: 1
downvote count: 0

http://stackoverflow.com/q/49091455
has title: How String format() to format the output
answer count: 2
has body: I plan to use the string.format() to make the output more readable. I have 'Name' and 'BirthDate' and 'Salary' columns. I got the widest string 'Name' (widest_name = 5) and widest string 'BirthDate' (widest_birthDate = 16). My date set: data_set = [["Dan", "August 8 1954", "50k"], ["Jason", "December 26 1984", "90k"], ...] I want to have the string formatting (.format() method) with you widest Name and BirthDate. Output: Name BirthDate Salary Dan August 8 1954 50k Jason December 26 1984 90k My code: print("{0: &lt;widest_name }, {1: &lt;widest_birthDate }, 'Salary'".format("Name", "BirthDate")) for lists in data_set : print(lists[0], lists[1], lists[2]) But I got the error: builtins.ValueError: Invalid format specifier
possible better answer: http://stackoverflow.com/a/49091849
has answer: http://stackoverflow.com/a/49091849
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49091573
type: AnsweredQuestion
downvote count: 1
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/49091573
score: -1

http://stackoverflow.com/comment/85027211
score: 0
type: Comment
type: QuestionComment
has text: You can't remove them, and even if you are currently under the impression that you don't need them (there is valuable debugging information in the context object), it's still unclear why you would try to remove them, rather than declare and then disregard them. Can you explain this?
comment on: http://stackoverflow.com/q/49008120

http://stackoverflow.com/comment/84990549
comment on: http://stackoverflow.com/q/48992644
score: 0
has text: I am new to the regular expressions so I have only managed to catch the whole table. And then I wondered if I can grout it and apply another regular expression in order to catch the index of the last row
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85141494
comment on: http://stackoverflow.com/q/49067980
has text: @Graipher I simply want to bind the list after the @ to `l`. And to motivate this I said "assume that list is the result of some other computation, like a list comprehension".
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84973344
has text: It really was that simple.. Now I see why even if I had written my question correctly, it was still simple.. Thank you. - The Keys are the KEY!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48984303
type: Comment

http://stackoverflow.com/q/48969221
upvote count: 1
tagged with: windows
has title: Error Running f2py, Symbol table not found
has body: I have been trying to get f2py to work on my windows 10 64-bit machine. I am using mingw32 and gnu95 compiler. When I run this command in command prompt python f2py.py -c -m Test2 Test2.f95 --fcompiler=gnu95 --compiler=mingw32 I get the following message produced running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building extension "Test2" sources f2py options: [] f2py:&gt; C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6\Test2module.c creating C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6 Reading fortran codes... Reading file 'Test2.f95' (format:free) Post-processing... Block: Test2 Block: test Post-processing (stage 2)... Building modules... Building module "Test2"... Wrote C/API module "Test2" to file "C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6\Test2module.c" adding 'C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6\fortranobject.c' to sources. adding 'C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6' to include_dirs. copying C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\f2py\src\fortranobject.c -&gt; C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6 copying C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\f2py\src\fortranobject.h -&gt; C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6 build_src: building npy-pkg config files running build_ext Building msvcr library: "C:\Users\heele\AppData\Local\Programs\Python\Python36\libs\libvcruntime140.a" (from C:\Users\heele\AppData\Local\Programs\Python\Python36\vcruntime140.dll) objdump.exe: C:\Users\heele\AppData\Local\Programs\Python\Python36\vcruntime140.dll: File format not recognized Traceback (most recent call last): File "f2py.py", line 28, in &lt;modul…
favorite count: 0
answer count: 0
downvote count: 0
tagged with: fortran
type: UnansweredQuestion
tagged with: python
score: 1
type: Question
tagged with: f2py

http://stackoverflow.com/comment/85040814
score: 1
type: AnswerComment
type: Comment
has text: @Teja Do you understand the *meaning* of the information you are getting back in the json?
comment on: http://stackoverflow.com/a/49017761

http://stackoverflow.com/comment/126908370
score: 0
type: AnswerComment
type: Comment
has text: This is helpful! It is very easy to ignore the difference!
comment on: http://stackoverflow.com/a/59681531

http://stackoverflow.com/q/48966834
has comment: http://stackoverflow.com/comment/84942146
tagged with: scipy
type: Question
tagged with: numpy
has body: I am not sure why stats.multivariate_normal.pdf is not working. At the moment I have from scipy import stats stats.multivariate_normal.pdf(X, meanX, covX) where X.shape = (150, 2) meanX.shape = () # just a float covX.shape = (150,) The error I get is: "total size of new array must be unchanged" Now I tried to follow the answer: meanL = np.float(np.mean(xL)) covL = np.cov(xL) stats.multivariate_normal.pdf(xL.T, np.full((150,), meanL), covL) I get the following error: LinAlgError Traceback (most recent call last) &lt;ipython-input-77-4c0280512087&gt; in &lt;module&gt;() 2 meanL = np.full((150,), meanL) 3 covL = np.cov(xL) ----&gt; 4 stats.multivariate_normal.pdf(xL.T, meanL, covL) 5 /Users/laura/anaconda/lib/python3.5/site-packages/scipy/stats/_multivariate.py in pdf(self, x, mean, cov, allow_singular) 497 dim, mean, cov = self._process_parameters(None, mean, cov) 498 x = self._process_quantiles(x, dim) --&gt; 499 psd = _PSD(cov, allow_singular=allow_singular) 500 out = np.exp(self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank)) 501 return _squeeze_output(out) /Users/laura/anaconda/lib/python3.5/site-packages/scipy/stats/_multivariate.py in __init__(self, M, cond, rcond, lower, check_finite, allow_singular) 148 d = s[s &gt; eps] 149 if len(d) &lt; len(s) and not allow_singular: --&gt; 150 raise np.linalg.LinAlgError('singular matrix') 151 s_pinv = _pinv_1d(s, eps) 152 U = np.multiply(u, np.sqrt(s_pinv)) LinAlgError: singular matrix
has title: stats.multivariate_normal.pdf - total size of new array must be unchanged
score: 0
answer count: 1
tagged with: covariance
has answer: http://stackoverflow.com/a/48970356
has comment: http://stackoverflow.com/comment/84941273
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84942389
has comment: http://stackoverflow.com/comment/84941790
tagged with: python
has comment: http://stackoverflow.com/comment/84942354

http://stackoverflow.com/a/48984158
score: 0
has body: I found the error is from with tf.Session() as sess: Before for()y loop and removing that, making separate declaration of the session. It worked Here is the code which will work. main.py import tensorflow as tf import numpy as np import matplotlib.pyplot as plt learning_rate = 0.001 training_epochs = 1000 display_step = 50 # taking input as array from numpy package and converting it into tensor # X must be 1X5 # Y must be 1X3 # w must be 5X1 # B must be 1X3 train_X = np.random.rand(1,5) train_Y = np.random.rand(1,3) # X = tf.placeholder(tf.float32, [1, 5]) Y = tf.placeholder(tf.float32, [1, 3]) W = tf.Variable([[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]]) b = tf.Variable([0.0 ,0.0,0.0]) pred = tf.add(tf.matmul(X, W), b) cost = tf.reduce_sum(tf.pow(pred-Y,2)) optimizer =tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost) init = tf.global_variables_initializer() avg_set = [] epoch_set = [] sess = tf.Session() sess.run(init) for i in range(training_epochs): sess.run(optimizer, feed_dict={X: train_X, Y: train_Y}) if (i+1) % display_step == 0: cc = sess.run(cost, feed_dict={X: train_X, Y: train_Y}) #check what it thinks when you give it the input data print("Epoch:", '%04d' % (i + 1), "cost=", "{:.9f}".format(cc), \ "W=", sess.run(W), "b=", sess.run(b)) avg_set.append(cc) epoch_set.append(i + 1) print("Optimization Finished!") training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y}) print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n') plt.plot(epoch_set,avg_set,'o',label = 'SLP Training phase') plt.ylabel('cost') plt.xlabel('epochs') plt.legend() plt.show()
answers question: http://stackoverflow.com/q/48983468
has comment: http://stackoverflow.com/comment/84973006
type: Answer

http://stackoverflow.com/q/49107594
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85220339
has title: Browse a list of dict in python
has body: I need to browse a list of python dictionary my list is as follows { "type" : "record", "name" : "warranty", "doc" : "Schema generated by Kite", "fields" : [ { "name" : "id", "type" : "long", "doc" : "Type inferred from '1'" }, { "name" : "train_id", "type" : "long", "doc" : "Type inferred from '21691'" }, { "name" : "siemens_nr", "type" : "string", "doc" : "Type inferred from 'Loco-001'" }, { "name" : "uic_nr", "type" : "long", "doc" : "Type inferred from '193901'" }, { "name" : "Configuration", "type" : "string", "doc" : "Type inferred from 'ZP28'" }, { "name" : "Warranty_Status", "type" : "string", "doc" : "Type inferred from 'Out_of_Warranty'" }] How can I get only the name and type of the fields entity thanks (ps: it's a JSON file) i wrote this code : with open('/data/my-data/archive/in/test_warranty_data.csv.txt.avro.txt', 'r') as f: i=0 data = json.load(f) for ele in data["fields"]: print ele.[i].["name"] print ele.[i].["type"] i++ May be you can suggest me something more efficient :) thank you
favorite count: 0
accepted answer: http://stackoverflow.com/a/49107766
type: Question
has comment: http://stackoverflow.com/comment/85220217
tagged with: python
tagged with: dictionary
answer count: 1
tagged with: list
score: 0
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49107766
has comment: http://stackoverflow.com/comment/85220258
has comment: http://stackoverflow.com/comment/85222185

http://stackoverflow.com/q/49073513
score: 1
has answer: http://stackoverflow.com/a/49073830
upvote count: 1
accepted answer: http://stackoverflow.com/a/49073830
type: Question
tagged with: mongodb
has title: Bulk store a dictionary in redis without iteration
answer count: 1
downvote count: 0
has body: I have a large dictionary and I would like to store it in redis. I can do this by iterating through it but this will take a long time. for k,v in my_dict.iteritems(): r.hset('my_dict', k, v) Is there a way to bulk store it (similar to how I can do it in Mongodb, simply by uploading the dictionary)?
favorite count: 0
tagged with: redis
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84997213
has text: Yes `'hunter2'` can come from another script or a permissioned file if necessary. My point here is not to try and defeat `getpass` (difficult), but to just patch it out in the first place (easy).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48995808
score: 1

http://stackoverflow.com/comment/85186875
type: Comment
has text: The reference to C++ 9.0 suggests that you are running Python 2.7.x under Windows. So, you could take a guess and try the [64-bit wheel for that platform](https://pypi.python.org/packages/40/43/643870fdad2665671c2adc31a6477cae916e7856710bc0f7ffc1619e13d8/pyodbc-4.0.21-cp27-cp27m-win_amd64.whl#md5=6bc9c95c14304360f0a0b19c03000112) and if that doesn't work then you could try the [32-bit wheel](https://pypi.python.org/packages/27/a0/fc42f78ffaf94871f67de3e499158ff382eb7159a361fa4c7f7edfa71e70/pyodbc-4.0.21-cp27-cp27m-win32.whl#md5=5aff0d160a23894281e4b568874e7558).
score: 0
comment on: http://stackoverflow.com/q/49087407
type: QuestionComment

http://stackoverflow.com/comment/85120273
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49057674
type: AnswerComment
has text: Thanks @Wen. I have corrected the input. Also, could you please provide me a little bit of explanations on your solutions? In particular, what the len() is doing...

http://stackoverflow.com/comment/84969872
score: 0
type: Comment
has text: I was unaware of that function, thank you. I should have seen it in the documentation but I guess I got tunnel vision. https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.get
type: AnswerComment
comment on: http://stackoverflow.com/a/48982339

http://stackoverflow.com/comment/85083169
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49038635
has text: Really, just using `format` is _not_ the way to create SQL queries. Use parameterization; `cursor.execute("SELECT user_id, created_at FROM cookies WHERE cookie_id = %s ORDER BY created_at DESC;", (cookie,))`. I don't know if that fixes the error but you're open to SQL injection and using string formatting is causing you hassle in trying to escape things.
type: Comment

http://stackoverflow.com/a/48971352
score: 2
answers question: http://stackoverflow.com/q/48971221
has body: I am afraid you will have to do it in separate instances. Think about what is happening here - checkpointer = ModelCheckpoint(filepath='checkpoints/weights-{epoch:02d}.hdf5', monitor='val_O1_categorical_accuracy' , verbose=1, save_best_only=True, mode='max') When you are saving a model by monitoring val_O1_categorical_accuracy, here is what it will do in pseudocode - for each epoch: check the val_O1_categorical_accuracy after updating weights if this metric is better in this epoch than the previous ones: save the model else pass So really specifying multiple monitor is out of scope. In this case it has to be an either/or choice as based on a monitor metric only one model among other conflicting models can be the best one.
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84947928
type: Answer
has comment: http://stackoverflow.com/comment/84947908

mininet
tags question: http://stackoverflow.com/q/49067910
tag name: mininet
tags question: http://stackoverflow.com/q/49054734
tags question: http://stackoverflow.com/q/49119768
type: Tag

http://stackoverflow.com/comment/85216194
type: Comment
comment on: http://stackoverflow.com/q/49105282
score: 0
has text: I can't reproduce your issue: I just tried installing and importing, and I have no problems.
type: QuestionComment

http://stackoverflow.com/q/49074580
has title: Get Python 2.7.14 to use updated OpenSSL on Mac Sierra
has body: Python is using old SSL lib and throws an error when trying to connect to newer TLD protocol. Error from python ssl.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) Python shows old version of OpenSSL even though I've upgraded: python -c "import ssl; print ssl.OPENSSL_VERSION" OpenSSL 0.9.8zh 14 Jan 2016 OpenSSL version openssl version -a (master✱) OpenSSL 1.0.2d 9 Jul 2015 built on: reproducible build, date unspecified platform: darwin64-x86_64-cc options: bn(64,64) rc4(ptr,int) des(idx,cisc,16,int) idea(int) blowfish(idx) compiler: /usr/bin/clang -I. -I.. -I../include -fPIC -fno-common -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -arch x86_64 -O3 -DL_ENDIAN -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM OPENSSLDIR: "/opt/local/etc/openssl" I've tried all the things on Stackoverflow regarding upgrading python, installing python from python.org, upgrading OpenSSL via brew, relinking OpenSSL via brew (doesn't work, not allowed), symlinking/updating ssl libs and binaries, restarting terminal. Python path python -c "import sys; print sys.path" ['', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Users/matt/Library/Python/2.7/lib/python/site-packages', '/usr/local/lib/p…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85164839
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85158070
linked to: http://stackoverflow.com/q/24323858
has comment: http://stackoverflow.com/comment/85164801
tagged with: openssl
score: 0

http://stackoverflow.com/q/48975490
tagged with: python
has comment: http://stackoverflow.com/comment/84956008
type: AnsweredQuestion
upvote count: 2
downvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/48975576
has comment: http://stackoverflow.com/comment/84955913
score: -1
answer count: 2
has title: how to convert list type into float in python
has body: I am trying convert list data type into float. I have tried following code but its not working, listf still showing data type as list for x in range(0,5): timeVar.append((matchedLine4[x]).replace(stringToMatch4,'').rstrip()) listf=map(float,timeVar) #list1 = [float(i) for i in timeVar] print(type(listf))
possible better answer: http://stackoverflow.com/a/48976380
has answer: http://stackoverflow.com/a/48976380
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1614236
has answer: http://stackoverflow.com/a/48975576

http://stackoverflow.com/comment/85205919
type: QuestionComment
has text: Wouldn't `sorted(os.listdir(path), key=len)[-1]` suffice? Nevermind I didn't read your question thoroughly.
score: 0
comment on: http://stackoverflow.com/q/49099816
type: Comment

http://stackoverflow.com/comment/85231722
comment on: http://stackoverflow.com/q/49113278
has text: how your output should looks like??
score: 0
type: QuestionComment
type: Comment

sympy
tags question: http://stackoverflow.com/q/49037294
tags question: http://stackoverflow.com/q/49084526
tag name: sympy
tags question: http://stackoverflow.com/q/49006951
tags question: http://stackoverflow.com/q/49093504
tags question: http://stackoverflow.com/q/48966934
tags question: http://stackoverflow.com/q/49016294
type: Tag
tags question: http://stackoverflow.com/q/48967664
tags question: http://stackoverflow.com/q/49012245
tags question: http://stackoverflow.com/q/48999613
tags question: http://stackoverflow.com/q/49016250

http://stackoverflow.com/q/49000217
has comment: http://stackoverflow.com/comment/85005805
tagged with: python
has body: I'm looking for a Pythonic way to validate arguments when their validation logically depends on the value(s) parsed from other argument(s). Here's a simple example: parser.add_argument( '--animal', choices=['raccoon', 'giraffe', 'snake'], default='raccoon', ) parser.add_argument( '--with-shoes', action='store_true', ) In this case, parsing this command should cause an error: my_script.py --animal snake --with-shoes Adding a mutually exclusive group doesn't seem to help here, as the other combos are OK: my_script.py --animal raccoon --with-shoes my_script.py --animal raccoon my_script.py --animal snake my_script.py --animal giraffe --with-shoes my_script.py --animal giraffe The validation error should ideally not be tied to --animal argument nor to --with-shoes argument, since the interface can not tell you which value needs to change here. Each value is valid, yet they can't be used in combination. We can do this with post-processing the args namespace, but I'm looking for a solution which would cause the parser.parse_args() call to fail, i.e. we actually fail during argument parsing, not afterwards.
type: AnsweredQuestion
score: 21
accepted answer: http://stackoverflow.com/a/49001995
upvote count: 21
type: Question
linked to: http://stackoverflow.com/q/44247099
has title: Cross-argument validation in argparse
tagged with: argparse
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49001995
favorite count: 0
has comment: http://stackoverflow.com/comment/85006136
linked to: http://stackoverflow.com/q/39437461

http://stackoverflow.com/comment/85185792
type: AnswerComment
comment on: http://stackoverflow.com/a/49088024
type: Comment
has text: Now I get watch you said, so it might end up getting more complex.
score: 0

http://stackoverflow.com/comment/85147273
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49069992
type: Comment
has text: This approach works great. Thank you. It takes 1,558 seconds on a table with 25042 rows (before resampled).

http://stackoverflow.com/q/49072148
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85152781
has comment: http://stackoverflow.com/comment/85152518
has comment: http://stackoverflow.com/comment/85150249
linked to: http://stackoverflow.com/q/9111711
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49074038
answer count: 1
tagged with: arrays
downvote count: 0
has title: Finding local maxima in large 3D Numpy arrays
has comment: http://stackoverflow.com/comment/85152898
favorite count: 0
has comment: http://stackoverflow.com/comment/85150402
has body: I'm processing some large volumetric image data that are present in three dimensional numpy arrays. I'll explain my task with two small 1D arrays. I have one image: img = [5, 6, 70, 80, 3, 4, 80, 90] and one segmented and labeled version of that image: labels = [0, 0, 1, 1, 0, 0, 2, 2] Each number in labels represents an object in img. Both arrays have the same dimensions. So in this example there's two objects in img: [5, 6, 70, 80, 3, 4, 80, 90] and what I'm trying to do now is finding the location of the maximum value of each object, which in this case would be the 3 and 7. Currently I loop over all labels, create a version of img which contains only the object corresponding to the current label, and look for the maximum value: for label in range(1, num_labels + 1): imgcp = np.copy(img) imgcp[labels != label] = 0 max_pos = np.argmax(imgcp) max_coords = np.unravel_index(pos, imgcp.shape) One problem with this approach is that copying img in every step tends to create memory errors. I feel like memory management should prevent this, but is there a more memory efficient and possibly faster way to to this task?
tagged with: python
accepted answer: http://stackoverflow.com/a/49074038
has comment: http://stackoverflow.com/comment/85149914
score: 1
upvote count: 1

http://stackoverflow.com/comment/85215566
type: QuestionComment
has text: Paste an example of your `csv` file.. your question is not making any sense
comment on: http://stackoverflow.com/q/49105159
score: 0
type: Comment

http://stackoverflow.com/comment/85029516
comment on: http://stackoverflow.com/q/49009148
type: QuestionComment
has text: @Wright oh mannn, it`s helping! THX, I wasted all day on this problem ^^
score: 0
type: Comment

python-imaging-library
tags question: http://stackoverflow.com/q/49110560
tags question: http://stackoverflow.com/q/49094318
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/49064705
tags question: http://stackoverflow.com/q/48966117
type: Tag
tags question: http://stackoverflow.com/q/49110328
tags question: http://stackoverflow.com/q/48995175
tags question: http://stackoverflow.com/q/48984583
tags question: http://stackoverflow.com/q/49071176
tags question: http://stackoverflow.com/q/49084846

http://stackoverflow.com/q/49030147
has comment: http://stackoverflow.com/comment/85067889
has comment: http://stackoverflow.com/comment/85064922
tagged with: mongoengine
type: Question
has body: Link to similar problem (assuming above link provides context) For a very limited duration, Mongodb in my case, receives a lot of connections. During this time-span if any insert happens, multiple duplicate documents get created. Please note that, from code, I'm saving only one document. However, mongodb stores duplicates with different _ids. Many solutions suggest adding unique index on collection, but it isn't possible in my case. What could be the best way of making sure that for one insert operation, there is only one entry in the database? Also, what is the reason it creates duplicate documents? I use mongoengine. Is it mongodb, mongoengine or webserver (apache) that is making retry insert calls and why? Versions used: mongoengine 0.8.7 pymongo 2.8.1 mongodb 2.6.12 Python 2.7.12
tagged with: mongodb
has answer: http://stackoverflow.com/a/49030352
score: 0
has comment: http://stackoverflow.com/comment/85065793
has comment: http://stackoverflow.com/comment/85066807
answer count: 1
has comment: http://stackoverflow.com/comment/85068409
has title: Avoid mongodb duplicate documents without using unique index
tagged with: mongodb-query
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/24122981
tagged with: python

http://stackoverflow.com/q/49034576
score: 1
possible better answer: http://stackoverflow.com/a/49034857
has comment: http://stackoverflow.com/comment/85074051
type: Question
has comment: http://stackoverflow.com/comment/85073969
has answer: http://stackoverflow.com/a/53436911
downvote count: 0
has answer: http://stackoverflow.com/a/60086352
has title: Move up directory until folder found python
has answer: http://stackoverflow.com/a/49034857
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/77667428
accepted answer: http://stackoverflow.com/a/49034944
has answer: http://stackoverflow.com/a/49035544
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49035483
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49034944
has body: I have a package of the following format: Electricity |___ __main__.py | |__ Electricity | |___ general_functions | |___ regression_calcs | | |___ create_calcs.py | | | |____ run_calcs.py | | | |__ Data_Input |___ regression_vals |__ regression_vals.csv run_calcs.py runs the code in regression_calcs, which requires data from Data_Input/Regression_vals. What is the most pythonic way to find the number of ../ (number of times to go up a folder), until Data_Input is found? This is because right now I'm running the scripts in Electricity/Electricity/run_calcs.py (for testing). Eventually I will be running in Electricity/__main__.py. it will be for df = pd.read_csv(f'{filepath}Data_Input/regression_vals/regression_vals.csv') where filepath = '../'*n

http://stackoverflow.com/comment/85159321
score: 0
comment on: http://stackoverflow.com/a/49076498
type: Comment
type: AnswerComment
has text: Thanks, this makes sense and is helpful however the other solution solved the issue with less code adjustment.

http://stackoverflow.com/comment/84951351
type: AnswerComment
has text: don't open another thread. Just _create_ a python `thread` and run the `subprocess.check_call` from the thread.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48973023

http://stackoverflow.com/a/49121745
accepted answer of: http://stackoverflow.com/q/49117914
type: AcceptedAnswer
type: Answer
score: 1
upvote count: 1
has body: I'm going to put my money on a Tensorflow version mismatch. Based on the following error text: NodeDef mentions attr 'dilations' not in Op Dilated convolutions are a rather newish concept, and likely to be changing from minor version to minor version, and it sounds like your code is utilizing it in a function, perhaps in the layers api. Check that you're running the same tensorflow version on both systems. If they're not the same version, look for the term dilations in your code as the likely culprit of change.
downvote count: 0
answers question: http://stackoverflow.com/q/49117914
has comment: http://stackoverflow.com/comment/85318606

http://stackoverflow.com/a/48993416
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/48992868
upvote count: 1
has comment: http://stackoverflow.com/comment/85000263
answers question: http://stackoverflow.com/q/48992868
has body: I break down the steps df['New']=df.value.diff().fillna(0).ne(0).cumsum() df1=df.loc[df.value.eq(0)] s1=df1.groupby(['id','New']).filter(lambda x : len(x)&gt;=5 ).groupby('id').apply(lambda x : x.iloc[len(x)//2-1:len(x)//2+1] if len(x)%2==0 else x.iloc[[(len(x)+1)//2],:] ).reset_index(level=0,drop=True) s2=df1.groupby(['id','New']).filter(lambda x : len(x)&gt;=5 ) pd.concat([df.loc[s2.drop_duplicates(['id'],keep='last').index+1],s1]).sort_index() Out[1995]: id name value New 5 1 f 0 2 6 1 g 0 2 9 1 j 1 3 14 2 o 0 4 16 2 q 1 5
has comment: http://stackoverflow.com/comment/85000803
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/128800674
comment on: http://stackoverflow.com/q/48977468
score: 0
type: Comment
type: QuestionComment
has text: If only you provided a link then I could test for it otherwise, I am not sure. Although, if its on the networks tab, then I am convinced scrapy playwright can grab all the information that you need and save it as a file.

http://stackoverflow.com/a/49135740
has comment: http://stackoverflow.com/comment/85276487
type: Answer
has body: Once you add the text to the canvas, you need to update the scrollregion attribute so that the canvas knows how much of its virtual space should be scrollable. def getURL(): ... canvas.create_text(10,0,text=received_html, anchor=NW, width=700) canvas.configure(scrollregion=canvas.bbox("all"))
downvote count: 0
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/49116857
accepted answer of: http://stackoverflow.com/q/49116857

http://stackoverflow.com/comment/85093851
type: QuestionComment
has text: did you scrap reddit post? please post data after scraping or post a code how did you scrap? so that it will be easy to answer to the members.
comment on: http://stackoverflow.com/q/49044379
score: 0
type: Comment

http://stackoverflow.com/q/49092307
tagged with: python
score: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/49092356
type: Question
has body: I am reading a set of JSON files using glob and storing them in a list. The length of the list is 1046. When I am reading the JSON file one by one and loading it to run further code, it just runs on 595 files and gives the following error: Traceback (most recent call last): File "removeDeleted.py", line 38, in &lt;module&gt; d = json.load(open(fn)) File "/usr/lib/python2.7/json/__init__.py", line 291, in load **kw) File "/usr/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I am loading the json files like this: json_file_names = sorted(glob.glob("./Intel_Shared_Data/gtFine/train/*/*.json")) for fn in json_file_names: #print fn #temp = temp + 1 #count = 0 d = json.load(open(fn)) objects = d["objects"] for j in range(len(objects)): Can anybody suggest me way out of this error?
has comment: http://stackoverflow.com/comment/85189880
has comment: http://stackoverflow.com/comment/85189873
has title: Error in reading JSON: No JSON object could be decoded
answer count: 2
has answer: http://stackoverflow.com/a/49092367
tagged with: glob
type: UnansweredQuestion

http://stackoverflow.com/comment/87081628
comment on: http://stackoverflow.com/a/49016481
score: 0
type: AnswerComment
has text: @YannicHamann when i added `{% debug %}` i get this error . `{'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'ERROR': 40, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30}, 'csrf_token': ._get_val at 0x10dd11268>>, `
type: Comment

http://stackoverflow.com/comment/84983251
type: Comment
has text: @Universalis how did you get 10x15 lists? Did you run that very code? Give it a try in the python command line and see for yourself.
comment on: http://stackoverflow.com/a/48988659
type: AnswerComment
score: 0

http://stackoverflow.com/comment/108614999
type: Comment
comment on: http://stackoverflow.com/a/49119776
type: AnswerComment
has text: parfait merci !
score: 0

http://stackoverflow.com/comment/85119353
has text: Thanks so much. i was defining the db variable again at the end of the db.py file so only the tables i defined was getting created. the once the came by default wasn't created and was not desplaying in the appadmin. Thanks very much for the help
type: Comment
comment on: http://stackoverflow.com/a/49057211
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84999224
comment on: http://stackoverflow.com/a/48996799
score: 0
type: AnswerComment
type: Comment
has text: What about the symbols in the character list? @jpp

http://stackoverflow.com/comment/84960510
has text: No, because internally Excel stores that as a number. It is just formatted that way. You can multiply by 100, add a percentage sign after reading the file.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48977649

http://stackoverflow.com/q/49073252
accepted answer: http://stackoverflow.com/a/49073540
favorite count: 0
has answer: http://stackoverflow.com/a/49073347
tagged with: python
tagged with: regex
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49073347
type: Question
has answer: http://stackoverflow.com/a/49073540
score: 4
has title: Pandas: how to select row with certain word
upvote count: 4
has body: How can I display only the row where the text contains the word like * AV * e.g 'AV Snow' or 'AV (Some)' or 'Me AV' # Select Structural status = 'AVAILABLE' or like *AV* value_list = ['AVAILABLE', '[AV]'] '[AV]' doesnt seem correct # Grab DataFrame rows where column has certain values new_df = df[df.STRUCTURALSTATUS.isin(value_list)] new_df.shape
answer count: 2
tagged with: pandas
downvote count: 0
tagged with: string

http://stackoverflow.com/comment/84946501
type: AnswerComment
score: 0
type: Comment
has text: I'll be honest, not 100% sure what you mean in points 1 and 3. I'm still trying to get a grasp of the descriptive language in OOP, so I want to understand what you're getting at here. Where should I first reference `quit` so that it can be a part of `actions`? For problem 3, what would be the better way to do this? I just python to pull up the entry for the key defined in the input, and then point that to another room.
comment on: http://stackoverflow.com/a/48969635

http://stackoverflow.com/a/49013377
score: 0
has body: Generally, it is a bad idea to use a subprocess when an API is available. The psutil module can be used to get the information you're looking for. It's much better to do this than to launch a separate process and parse the output because: It'll save you the parsing logic, which is usually hard to maintain. It avoids the additional possibilities for failure introduced by launching another process. It's faster. However, to answer your first question, if you just want to write a variable into a string: cmd = "ps -l | grep %s" % (pid) data = subprocess.getoutput(cmd)
type: Answer
answers question: http://stackoverflow.com/q/49013269

http://stackoverflow.com/comment/84954414
comment on: http://stackoverflow.com/a/48972055
type: Comment
has text: might be for using `(Object)` in class definition. New syntax in python3 done away with that.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49076020
has comment: http://stackoverflow.com/comment/85158244
type: Question
has comment: http://stackoverflow.com/comment/85158960
score: 0
answer count: 1
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/85170436
has body: I'm very new to sockets, so I was just trying to get a simple server/client system running. My server.py: import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('', 5555)) serversocket.listen(5) while True: connection, address = serversocket.accept() buf = connection.recv(2048) if len(buf) &gt; 0: print(buf.decode()) break My client.py: import socket clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(("192.168.1.157", 5555)) msg = str.encode(input('Enter your message: ')) clientsocket.send(msg) When I run both codes on my laptop, it works: the server receives the message and then closes. However, when I run the client on my desktop, I get a 'TimeoutError [WinError 10060]'. I've tried serversocket.bind(('0.0.0.0',5555)) as well, with the same results. The other IP addresses that I've tried, such as the one I get from sites like www.whatismyip.com just give ConnectionRefusedError: [WinError 10061]. I have no idea what's wrong, although I imagine its something to do with the IP address being wrong, but I can't find anything online that actually helps.
type: UnansweredQuestion
has title: Python server not responding
has answer: http://stackoverflow.com/a/49077669
has comment: http://stackoverflow.com/comment/85157942

http://stackoverflow.com/q/48983169
accepted answer: http://stackoverflow.com/a/48983476
type: AnsweredQuestion
type: Question
has body: Given the following matplotlib snippet that uses annotations: labels = ['Point-%d' %i for i in range(0,10)] outMat = np.array([(-20 + 20*x + 20*np.sin(math.pi * 2 * x), -30 + x*30 + np.sin(math.pi * 2 * x)) for x in range(0,10)]) fig = plt.figure() plt.title(title) ax = fig.subplots(1,1) for i in range(outMat.shape[0]): ax.annotate(labels[i],outMat[i],(outMat[i][0],outMat[i][1])) plt.scatter(outMat[:,0],outMat[:,1]) fig.show() We end up with overlapping/competing y and x tick labels: The correctly scaled ticks from [0.0 to 250.0] - based on the range of the input x and y values- should be the only ones. It is unclear why there are tick marks of [0.0-1.0] in 0.2 increments: the request here is to remove those spurious marks. What needs to change in the snippet?
has title: Competing sets of tick marks on a matplotlib plot with annotations
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48983476
score: 0
has comment: http://stackoverflow.com/comment/84971209
answer count: 1
has comment: http://stackoverflow.com/comment/84971335
tagged with: python

http://stackoverflow.com/comment/85275564
comment on: http://stackoverflow.com/a/49041780
score: 0
type: AnswerComment
type: Comment
has text: Great answer! Thank you so much for the response.I was able to retrieve all the information that I needed. Is your approach faster because you don't need to open a browser at all? Please advise.

http://stackoverflow.com/comment/85001931
type: AnswerComment
has text: @mxbi 10K * 1M is too much memory(10G `long` ???), maybe you need to try 10K * 10K level.
comment on: http://stackoverflow.com/a/48997870
type: Comment
score: 0

http://stackoverflow.com/a/49116467
has comment: http://stackoverflow.com/comment/85238317
upvote count: 1
answers question: http://stackoverflow.com/q/49115909
has comment: http://stackoverflow.com/comment/85238416
has comment: http://stackoverflow.com/comment/85238396
has comment: http://stackoverflow.com/comment/85238341
has body: You need to create a custom ModelAdmin class that subclasses the built-in one. from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User class CustomUserAdmin(UserAdmin): model = User admin.site.register(User, CustomUserAdmin)
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/49115909
has comment: http://stackoverflow.com/comment/85238381

http://stackoverflow.com/comment/85091245
type: QuestionComment
comment on: http://stackoverflow.com/q/49042424
has text: You are not passing a grayscale image to the function.
score: 0
type: Comment

http://stackoverflow.com/q/49113983
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49117085
type: Question
score: 3
tagged with: pyside
accepted answer: http://stackoverflow.com/a/49117085
downvote count: 0
answer count: 1
favorite count: 0
has title: Emit Signal when QListview item's checkbox changes
tagged with: python
has body: How can i emit a signal when a qlistview item's checkbox is changed? Ideally the emitted signal would have some sort of pointer to the item that changed so i could act accordingly in PySide. import os import sys import json from PySide import QtGui, QtCore class MegaMergeWindow(QtGui.QMainWindow): def __init__(self, *args, **kwargs): super(MegaMergeWindow, self).__init__(*args, **kwargs) self.TITLE = 'Mega Merge' self.VERSION = '1.0.0' self.setWindowTitle(self.TITLE + ' | ' + self.VERSION) self.resize(350,500) # vars self.user_folder = os.path.join(os.getenv('LOCALAPPDATA'), 'MegaMerge') # controls self.ui_files = QtGui.QListView() self.ui_files.setModel(QtGui.QStandardItemModel()) self.ui_files.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui_merge = QtGui.QPushButton('Merge') main_layout = QtGui.QVBoxLayout() main_layout.addWidget(self.ui_files) main_layout.addWidget(self.ui_merge) main_widget = QtGui.QWidget() main_widget.setLayout(main_layout) self.setCentralWidget(main_widget) # signals self.ui_merge.clicked.connect(self.merge_clicked) self.populate_files() def populate_files(self, files=[], clear=False): model = self.ui_files.model() if clear: model.clear() files = ['Doug','Kevin','Amy','Melissa','John'] for f in files: name = os.path.basename(f) item = QtGui.QStandardItem(name) item.setData(f, role=QtCore.Qt.UserRole) item.setCheckable(True) item.setCheckState(QtCore.Qt.Checked) model.appendRow(item) model.sort(0, QtCore.Qt.AscendingOrder) def collect_paths(self): files = [] model = self.ui_files.model() for index in range(model.rowCount()): item = model.item(index) if item.checkState() == QtCore.Qt.Checked: files.append(item.text()) return files def merge_files(self, files=[]): print files def merge_clicked(self): files = self.collect_paths() print files def main(): app = QtGui.QApplication(sys.argv) ex = MegaMergeWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()

http://stackoverflow.com/q/49113057
upvote count: 1
answer count: 1
favorite count: 0
tagged with: exception
type: UnansweredQuestion
tagged with: python
tagged with: tftp
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85231665
type: Question
has title: tftpy package sytax errors on import
has comment: http://stackoverflow.com/comment/85231328
has body: I've just installed the package tftpy version 0.6.2 when I import it I get a syntax error with the line: running the code: import tftpy I get the error: raise ImportError, "Requires at least Python 2.3" SyntaxError: Invalid syntax I have version 3.6.3 installed. import sys print(sys.version_info) gives me the out put major=3, minor=6, micro=3. However the line of code that raises the syntax error is the last line in the code below: import sys required_version = (2, 3) if sys.version_info &lt; required_version: raise ImportError, "Requires at least Python 2.3" I don't think the issue is with my version number I think it doesn't like the syntax used to raise the ImportError exception. Any help would be greatly received.
has answer: http://stackoverflow.com/a/52513768
tagged with: syntax-error

http://stackoverflow.com/comment/85172798
type: QuestionComment
comment on: http://stackoverflow.com/q/49065313
score: 0
type: Comment
has text: But MNIST is handwritten digits. These are a font. And Tesseract does a really good job. It just needs a cleaner image.

http://stackoverflow.com/comment/85023522
type: QuestionComment
has text: A field in the model needs to have primary_key=True else django go looking for the id field, I dont think composite keys are doable - but its being worked on here https://code.djangoproject.com/ticket/373 but that ticket has been open for 13 years so dont hold your breath
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49009264

http://stackoverflow.com/comment/90226981
score: 0
comment on: http://stackoverflow.com/a/51617288
type: AnswerComment
has text: Thanks a lot. This works really well for user installs, however when I need to install for all users, I get an error. Please fix it. And BTW, is there any way to not show all of the colourful text?
type: Comment

http://stackoverflow.com/comment/85100214
score: 0
type: Comment
type: QuestionComment
has text: It is not my code, it is the code from TensorFlow
comment on: http://stackoverflow.com/q/49047205

http://stackoverflow.com/q/49056602
possible better answer: http://stackoverflow.com/a/64659437
type: Question
has answer: http://stackoverflow.com/a/64659437
tagged with: zeromq
score: 7
has body: I am trying to make a class that will be able to send data and then receive them. Right now, it is working only for the first send/receive and with another attempt to .send() it will throw an error below. &gt;Traceback (most recent call last): File "main.py", line 31, in &lt;module&gt; zq.send(arr) File "D:\ITIM\video2\MQCompare\cZMQ.py", line 17, in send self.socketC.send(data) File "zmq/backend/cython/socket.pyx", line 636, in zmq.backend.cython.socket.S ocket.send (zmq\backend\cython\socket.c:7305) File "zmq/backend/cython/socket.pyx", line 683, in zmq.backend.cython.socket.S ocket.send (zmq\backend\cython\socket.c:7048) File "zmq/backend/cython/socket.pyx", line 206, in zmq.backend.cython.socket._ send_copy (zmq\backend\cython\socket.c:3032) File "zmq/backend/cython/socket.pyx", line 201, in zmq.backend.cython.socket._ send_copy (zmq\backend\cython\socket.c:2920) File "zmq/backend/cython/checkrc.pxd", line 25, in zmq.backend.cython.checkrc. _check_rc (zmq\backend\cython\socket.c:10014) raise ZMQError(errno) zmq.error.ZMQError: Operation cannot be accomplished in current state` The code I'm using looks like this: import zmq class ZeroMQ: def __init__(self): self.context = zmq.Context() self.socketS = self.context.socket(zmq.REP) self.socketS.bind("tcp://*:5555") self.socketC = self.context.socket(zmq.REQ) self.socketC.connect("tcp://localhost:5555") def __exit__(self, exc_type, exc_value, traceback): self.socketC.close() self.socketS.close() def send(self, data): self.socketC.send(data) def recv(self): self.socketS.recv() Am I making the connection right? Why is the function send throwing an error? I will appreciate any help. Thank you.
tagged with: message-queue
answer count: 2
downvote count: 0
favorite count: 0
has title: ZeroMQ operation throws EXC: [ Operation cannot be accomplished in current state ]
has answer: http://stackoverflow.com/a/49056975
tagged with: sockets
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49056975
upvote count: 7

http://stackoverflow.com/a/48969146
downvote count: 1
score: 5
has comment: http://stackoverflow.com/comment/85491017
has comment: http://stackoverflow.com/comment/98937143
answers question: http://stackoverflow.com/q/48969145
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/85553536
has body: I found a way researching samples from google api python client on github and trying same changes. Using the httplib2 to authenticate you can set the timeout. Following the modified code: import base64 import io import time from PIL import Image # Need: pip install google-api-python-client import httplib2 from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] # API &amp; Services -&gt; Credentials -&gt; Create Credential -&gt; service account key SERVICE_ACCOUNT_FILE = 'mycredentialsfile.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) http = httplib2.Http(timeout=200) http = credentials.authorize(http) ml = discovery.build('ml', 'v1', http=http) projectID = 'projects/{}'.format('projectID ') + '/models/{}'.format('modelID') width = 640 height = 480 instances = [] for image in ["image5.jpg", "image6.jpg"]: img = Image.open(image) img = img.resize((width, height), Image.ANTIALIAS) output_str = io.BytesIO() img.save(output_str, "JPEG") instance = {"b64": base64.b64encode(output_str.getvalue()).decode("utf-8") } output_str.close() instances.append(instance) input_json = {"instances": instances } request = ml.projects().predict(body=input_json, name=projectID) print("Starting prediction") start_time = time.time() response = request.execute() print("%s seconds" % (time.time() - start_time)) I think with a few modifications you can use this to set timeout to almost any google cloud API in python client. I hope this helps.

http://stackoverflow.com/a/49022583
has body: Try filter function: len(list(filter(lambda dic: dic['label'] == 'car', result))) To create a completely new list, do: list(filter(lambda dic: dic['label'] == 'car', result)) Remember to cast a list converter in front, since filter would return a 'filter object' itself.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49020647
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49020647

http://stackoverflow.com/a/49086136
answers question: http://stackoverflow.com/q/49086055
has body: Use a dictionary: d = dict(A=12.74087388, B=12.48817861, C=12.31249807, D=12.95688859, E=12.49693343, F=11.51090636, G=10.16505019, H=11.99872655) and sort by value: &gt;&gt;&gt; sorted(d, key=d.get) ['G', 'F', 'H', 'C', 'B', 'E', 'A', 'D'] or keep the numbers and sort by value: from operator import itemgetter print(sorted(d.items(), key=itemgetter(1))) Output: [('G', 10.16505019), ('F', 11.51090636), ('H', 11.99872655), ('C', 12.31249807), ('B', 12.48817861), ('E', 12.49693343), ('A', 12.74087388), ('D', 12.95688859)]
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/85177927
has comment: http://stackoverflow.com/comment/85177825
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49086055
has comment: http://stackoverflow.com/comment/85177874
type: Answer

http://stackoverflow.com/q/49066856
answer count: 1
has answer: http://stackoverflow.com/a/51090689
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: openshift
score: 2
has body: I have installed this python API: https://github.com/openshift/openshift-restclient-python and am trying to understand how to use that for basic operations that I would normally do on command line using the open shift client, e.g.: oc login [my-openshift-instance] oc project [my-project] But I can't seem to find these basic operations in the above API. Is that API designed for some other purpose or have I simply missed those calls? I tried: from openshift import client, config config.load_kube_config() oapi = client.OapiApi() project_list = oapi.list_project() for project in project_list.items: print (project.metadata.name) but it will not let me specify my open shift instance and user/pass.
type: Question
downvote count: 0
has title: Python client for the OpenShift API and doing oc login
has comment: http://stackoverflow.com/comment/85139720

http://stackoverflow.com/a/49012086
has comment: http://stackoverflow.com/comment/85039926
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49011625
has comment: http://stackoverflow.com/comment/85035023
answers question: http://stackoverflow.com/q/49011625
type: Answer
score: 2
downvote count: 0
has body: One issue is surely: c = Card() print(c.available_cards) Because 1) does the constructor of the Card class take 2 arguments (rank and suit and 2) does the Cards class not have available_cards, so trying to acces c.available_cards will not work So not knowing what you intended with those two lines I omitted them from further debugging. Now you are doing: d = Deck() okay, that doesn't need any argument and creates a new deck with all the cards in a standard 52 deck and initializes dealt_cards to []. Now you immediatly print print(d.dealt_cards) which will of course result in an empty list: print(d.dealt_cards) >>>[] What you might have intended is probably to deal some cards first and then print the result: for i in range(4): d.deal_card() print(d.dealt_cards) This however results in an error message since your deal_card is not correct. You don't want to add anything to the available_cards, but remove one item from it and add it to your dealt_cards like so: def deal_card(self): # self.available_cards.add(Card) # self.available_cards.remove(Card) self.dealt_cards.append(self.available_cards.pop()) Now you will notice that print(d.dealt_cards) does not output the cards in the list in a "pretty" way, instead you might see something like this: [<__main__.Card object at 0x00000285E8C0A978>, <__main__.Card object at 0x00000285E8C0AA58>, <__main__.Card object at 0x00000285E8C0A4E0>, <__main__.Card object at 0x00000285E8BFCF28>] That is because you havn't taught your script how to print a card. For this we add a method to the Cards class: def __repr__(self): return self.get_name() whenever printing an instance of the cards class now, we will get the desired output. Final code: class Card: def __init__(self, rank, suit): self.suit = suit self.rank = rank self.ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def get_name(self): return Card.ranks[self.rank - 1] + ' of ' + self.suit def equals(self, other_card): if self.rank == other_card.ran…
has comment: http://stackoverflow.com/comment/118156108

http://stackoverflow.com/comment/84979567
type: Comment
type: QuestionComment
score: 2
has text: You'd use `fig.subplots_adjust(right=1)` to have the right side of the axes sit tight against the figure boundary.
comment on: http://stackoverflow.com/q/48987387

http://stackoverflow.com/comment/85142784
score: 0
type: Comment
has text: did it, hoping it worked this time. downvote clicked by mistake:)
comment on: http://stackoverflow.com/a/49063612
type: AnswerComment

http://stackoverflow.com/q/49075045
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49085269
tagged with: boto3
has title: ValueError: non-string names in Numpy dtype unpickling only on AWS Lambda
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49085269
tagged with: scikit-learn
score: 1
has body: I am using pickle to save my trained ML model. For the learning part, I am using scikit-learn library and building a RandomForestClassifier rf = RandomForestClassifier(n_estimators=100, max_depth=20, min_samples_split=2, max_features='auto', oob_score=True, random_state=123456) rf.fit(X, y) fp = open('model.pckl', 'wb') pickle.dump(rf, fp, protocol=2) fp.close() I uploaded this model on S3 and I am fetching this model using boto3 library in AWS Lambda. s3_client = boto3.client('s3') bucket = 'mlbucket' key = 'model.pckl' download_path = '/tmp/{}{}'.format(uuid.uuid4(), key) s3_client.download_file(bucket, key, download_path) f = open(download_path, 'rb') model = pickle.load(f) f.close() However, I am getting ValueError: non-string names in Numpy dtype unpickling error at this line: model = pickle.load(f) Here's the log: START RequestId: 3d8a1263-1e3c-11e8-8bdb-03c0ef524c0e Version: $LATEST non-string names in Numpy dtype unpickling: ValueError Traceback (most recent call last): File "/var/task/function.py", line 31, in handler model = pickle.load(f) File "/usr/lib64/python2.7/pickle.py", line 1384, in load return Unpickler(file).load() File "/usr/lib64/python2.7/pickle.py", line 864, in load dispatch[key](self) File "/usr/lib64/python2.7/pickle.py", line 1223, in load_build setstate(state) ValueError: non-string names in Numpy dtype unpickling I am using python 2.7 on both local machine as well as AWS Lambda. The weird part is that the pickle.load() is working fine on my local machine. I have used this code to test pickle on my local machine: with open('/home/Documents/model.pckl', 'rb') as f: rf = pickle.load(f)
tagged with: aws-lambda
favorite count: 0
type: Question
tagged with: pickle
tagged with: python

http://stackoverflow.com/comment/84949226
has text: Ok this is what I needed to clarify.Fine if that is the case.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48971973

http://stackoverflow.com/comment/116783406
score: 0
type: Comment
has text: There is a similar question here: [Highlighting weekends in small multiples](https://stackoverflow.com/questions/66011487/highlighting-weekends-in-small-multiples); Here: [how to highlight weekends in matplotlib plots?](https://stackoverflow.com/questions/61287041/how-to-highlight-weekends-in-matplotlib-plots?); And here: [Pandas Plots: Separate color for weekends, pretty printing times on x axis](https://stackoverflow.com/questions/16480232/pandas-plots-separate-color-for-weekends-pretty-printing-times-on-x-axis)
type: QuestionComment
comment on: http://stackoverflow.com/q/48973471

http://stackoverflow.com/q/49107938
has comment: http://stackoverflow.com/comment/85220989
has comment: http://stackoverflow.com/comment/85222400
type: Question
possible better answer: http://stackoverflow.com/a/49108030
linked to: http://stackoverflow.com/q/7844118
has answer: http://stackoverflow.com/a/49108030
has answer: http://stackoverflow.com/a/49107987
has comment: http://stackoverflow.com/comment/85220796
has title: Convert items in a list element to a list
tagged with: python-2.7
has body: I am forced to use comma separation in one of my input arguments to separate multiple values. So I end up with my_string = ['a,b,c'] How can I convert this so that my_new_string = ['a', 'b', 'c']
has answer: http://stackoverflow.com/a/49108806
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/49107987
tagged with: python
has comment: http://stackoverflow.com/comment/85222623
has comment: http://stackoverflow.com/comment/85220968
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/84984588
type: QuestionComment
has text: Did you use softmax on the last layer?
comment on: http://stackoverflow.com/q/48987959
score: 0
type: Comment

http://stackoverflow.com/q/49035274
has body: My code is this: import urllib.request import re http://www.weather-forecast.com/locations/Paris/forcasts/latest city = input('Please enter a place: ') url = 'http://www.weather-forecast.com/locations/'+city+'forcasts/latest' data = urllib.request.urlopen(url).read() data1 = data.decode('utf-8') I'm having trouble with the url this is my output: Traceback (most recent call last): File "C:/Users/alext/AppData/Local/Programs/Python/Python36/Weather forecast.py", line 9, in data = urllib.request.urlopen(url).read() File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open response = meth(req, response) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 564, in error result = self._call_chain(*args) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 756, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open response = meth(req, response) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Users\alext\AppData\Local\Programs\Python\Python36\lib\urllib…
upvote count: 3
tagged with: web-scraping
downvote count: 1
type: Question
has title: HTTP Error 404: Not Found python urllib
tagged with: urllib
has answer: http://stackoverflow.com/a/49035423
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85075424
tagged with: python
accepted answer: http://stackoverflow.com/a/49035423
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/85094804
has text: Could you share snippets the code in each `html` file? Everything looks OK from your Flask perspective... I'm wondering if something is amiss with your templates in `errorPage.html` or `500.html`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49043744

http://stackoverflow.com/a/49092204
downvote count: 0
answers question: http://stackoverflow.com/q/49091077
accepted answer of: http://stackoverflow.com/q/49091077
type: Answer
upvote count: 1
has body: @bot.command(pass_context=True) async def example(ctx): await bot.send_message(ctx.message.channel, 'Example') Pass the context into the command and then get the channel from the message attribute.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85031749
type: Comment
comment on: http://stackoverflow.com/a/49013190
has text: Oh, interesting... It might be a pandas version issue (I'm using 0.22.0). The commented line is meant to be manually typed out in full :P Hopefully this works: `df_num = df'dist1', 'dist2', 'dist3', 'dist4', 'dist5'`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84963231
type: QuestionComment
has text: Reading the error message surely `guessesTaken = str(guessesTaken)` seems suspect? Maybe read up on the various string formatting options, or at least assign the string to a separate variable for the concatenation.
score: 6
comment on: http://stackoverflow.com/q/48979104
type: Comment

http://stackoverflow.com/comment/85125112
comment on: http://stackoverflow.com/q/49040998
has text: Are you installing tensorflow from a binary wheel. If so it was likely built against a newer C/C++ compiler version and the compiler on your system is too old. When you ``pip`` install it, use options to have ``pip`` ignore any binary wheel and compile it from source code on your system.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85082777
has text: `grep` should work just fine with normal python console output :) but that's unrelated to your main question, which is to stop said logs in the first place.
comment on: http://stackoverflow.com/q/49038678
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/140098705
score: 0
type: Comment
has text: on the macos Sequoia it's: _cat ~/.conda/environments.txt_
comment on: http://stackoverflow.com/a/77043039
type: AnswerComment

zoho
type: Tag
tags question: http://stackoverflow.com/q/49002928
tag name: zoho

sparql
tags question: http://stackoverflow.com/q/49101985
type: Tag
tag name: sparql

http://stackoverflow.com/comment/85044891
has text: @gyre Good suggestion! Personally I like to mirror how I operate on the list myself (get the top two by sorting the three elements in my head)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/49000891
type: AnswerComment

http://stackoverflow.com/q/49070519
tagged with: manifest
has answer: http://stackoverflow.com/a/68174591
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56507546
accepted answer: http://stackoverflow.com/a/68174591
score: 7
tagged with: packaging
has answer: http://stackoverflow.com/a/56507546
has comment: http://stackoverflow.com/comment/120268996
favorite count: 0
tagged with: python-3.x
upvote count: 8
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85146352
tagged with: python
has title: Where are the data files included in MANIFEST.IN stored?
has body: I have this small program do it with Python3.5 with the following structure: awesome_gui/ app.config MANIFEST.in setup.py awesome_gui/ __init__.py main.py setup.py: #!/usr/bin/env python import os from setuptools import setup setup( name = "awesomegui", version = "1.0", author = "Me", author_email = "me@example.com", description = "Awesome GUI", packages=['awesome_gui'], entry_points = { 'console_scripts': ['awesomegui=awesome_gui.main'], }, include_package_data=True, ) MANIFEST.in include app.config After execute the following line and create the .deb: $ python3 setup.py --command-packages=stdeb.command bdist_deb And unpack with: $ sudo dpkg -i deb_dist/python3-awesomegui_1.0-1_all.deb The code (*.py) is saved in /usr/lib/python3/dist-packages/awesome_gui/. But I do not see where app.config is saved. Does anyone know where the data files that are non-code are stored? Thank you!
downvote count: 1
has comment: http://stackoverflow.com/comment/120490894
has comment: http://stackoverflow.com/comment/85149111

http://stackoverflow.com/a/49262523
type: Answer
has comment: http://stackoverflow.com/comment/85909084
has comment: http://stackoverflow.com/comment/85940724
upvote count: 7
answers question: http://stackoverflow.com/q/49009386
score: 7
has body: I haven't found a nice solution like a mask for the Embedding layer. But here's what I've been meaning to try: Two embedding layers - one trainable and one not The non-trainable one has all the Glove embeddings for in-vocab words and zero vectors for others The trainable one only maps the OOV words and special symbols The output of these two layers is added (I was thinking of this like ResNet) The Conv/LSTM/etc below the embedding is unchanged That would get you a solution with a small number of free parameters allocated to those embeddings.
has comment: http://stackoverflow.com/comment/85939296
downvote count: 0
has comment: http://stackoverflow.com/comment/85862669
has comment: http://stackoverflow.com/comment/85886953

http://stackoverflow.com/q/49059920
tagged with: python
has answer: http://stackoverflow.com/a/49060273
type: Question
tagged with: hmac
score: 0
tagged with: api-authorization
answer count: 1
has title: HMAC API authentication issues in Python
has body: I'm attempting to pull JSON data from an API and struggling to nail down the source of my problems. Currently I get accurate data if message = "" but so far any non-empty query parameters return a 403 error. The API documentation asks for parameters to be formatted as "customerCode=XXX" and I've been able to produce valid queries in the API Sandbox. I assume the problem is somewhere in the getSignature function, but I've rewritten it a few ways and .encode() or bytes() gives me the same result. If the code looks coherent and it's a syntax error on my end I can reach out to the support team. Again, when message is an empty string I get valid results back so I'm puzzled. Error occurs on all tested Report pages with multiple different query parameters tested per page. Relevant import functions are not pasted here but are included in the code. #Current hash def getSignature(message): hashed = hmac.new(key, message.encode('utf-8') , hashlib.sha256) return base64.b64encode(hashed.digest()) #Header per API specs def getData(report, message): headers = { 'Content-Type' : 'application/json', 'Accept' : 'application/json', 'api-auth-id' : api_id, 'api-auth-signature' : getSignature(message) } data = requests.get(url + report, headers=headers) data = data.json() return data
type: UnansweredQuestion

apache-superset
tags question: http://stackoverflow.com/q/49077277
tags question: http://stackoverflow.com/q/48966344
tag name: apache-superset
type: Tag

http://stackoverflow.com/comment/85061392
type: QuestionComment
has text: I found it it's recursion problem. Thank you for your time gentleman
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49026353

http://stackoverflow.com/a/49070624
type: Answer
answers question: http://stackoverflow.com/q/49070147
score: 3
upvote count: 3
has body: As Cong Ma mentioned in the comments, the most obvious problem is that you are probably looking in the wrong place. In your code you have the output file as: with open('test_file', 'a') which when you are testing this script appears in the same folder as the script. The problem is, that Python does not interpret file_name as /path/to/python/script/file_name but instead reads a relative path as relative to the present working directory. If you are kicking off from systemd, your present working directory is not the same as where the script is located. You can handle this by configuring your service, but easier in this case is to just provide an absolute path to the output file: import time if __name__ == '__main__': with open('/home/gilles/test_file', 'a') as fd: while True: for i in range(10): fd.write('test' + str(i) + '\r\n') time.sleep(3) break If you'd rather fool around with the service, you can change the working directory of systemd. This info might be helpful: Changing Working Directory of systemd service
accepted answer of: http://stackoverflow.com/q/49070147
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85216343
comment on: http://stackoverflow.com/a/49105649
score: 0
type: AnswerComment
type: Comment
has text: Jupyter notebooks can be edited and run within Pycharm... I don't see how that makes the one an alternative to the other?

http://stackoverflow.com/comment/85218936
type: AnswerComment
comment on: http://stackoverflow.com/a/49102602
type: Comment
has text: That did it! Is this documented somewhere? I wasn't able to find it in the documentation.
score: 0

http://stackoverflow.com/a/49041355
score: 0
has body: 2 1d arrays: In [79]: x1=np.array([1,2,3]) In [80]: x2=np.array([4,5,6]) Make new array - 2d, with 2 rows In [81]: x12 = np.array((x1,x2)) In [82]: x12 Out[82]: array([[1, 2, 3], [4, 5, 6]]) np.array([[1,2,3],[4,5,6]]) does the same thing. The arrays can be summed, element by element: In [83]: x1 + x2 Out[83]: array([5, 7, 9]) rows of the 2d array can also be summed: In [84]: x12.sum(axis=0) Out[84]: array([5, 7, 9])
answers question: http://stackoverflow.com/q/49039113
type: Answer
accepted answer of: http://stackoverflow.com/q/49039113
type: AcceptedAnswer

http://stackoverflow.com/q/49016226
score: 6
type: Question
has title: Difference between exec behavior when module is imported or not
possible better answer: http://stackoverflow.com/a/49220400
has body: I am running to of the following programs. Importantly, imagine that there is mymodule.py file in the directory where both these programs are located. The first: exec('''import sys import os os.chdir('/') sys.path = [] import mymodule''', {}) The second: import mymodule exec('''import sys import os os.chdir('/') sys.path = [] import mymodule''', {}) The first snippet raises ImportError as expected (after all, the directory where mymodule is located is not in path). The second snippet, however, does not, even though mymodule is also not in its path and the environment I am giving it is empty. My question is why
has answer: http://stackoverflow.com/a/49220400
answer count: 2
tagged with: python-import
downvote count: 0
has answer: http://stackoverflow.com/a/49165585
favorite count: 0
accepted answer: http://stackoverflow.com/a/49165585
tagged with: python
has comment: http://stackoverflow.com/comment/85582484
tagged with: exec
upvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/a/49070294
has body: Yes. isinstance and issubclass were killed some time ago for cases like Union. The idea, as also stated in a comment on the issue by GvR is to implement your own version of issubclass/isinstance that use some of the extra metadata attached to types: &gt;&gt;&gt; Union[int, str].__args__ (int, str) &gt;&gt;&gt; Union[int, str].__origin__ typing.Union __args__ and __origin__ are available as of Python 3.6.3. They might not in earlier versions since typing is still provisional. Until the internal interface for introspecting types is fleshed out and typing graduates from provisional status, you should expect breakage due to changes in the API.
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49067070
upvote count: 2
answers question: http://stackoverflow.com/q/49067070
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/49045685
score: 0
upvote count: 1
downvote count: 1
has body: Try this : print [a for a in alist if a[1]=='c'] output: [(2, 'c', 3)]
type: Answer
answers question: http://stackoverflow.com/q/49045444
has comment: http://stackoverflow.com/comment/85095893

http://stackoverflow.com/comment/85027055
type: AnswerComment
type: Comment
has text: data = request.get_json(force=True) <--solved the issue. Thanks again folks. And whoever downvoted is correct. This is a duplicate question. Apologies
score: 16
comment on: http://stackoverflow.com/a/49010614

http://stackoverflow.com/q/49089398
has comment: http://stackoverflow.com/comment/85184432
answer count: 1
has answer: http://stackoverflow.com/a/49089455
tagged with: unicode
favorite count: 0
has body: I created MainUser model and this model has unicode method, but here I have problem like 'unicode' object is not callable this my authorization function: def auth(request): params = dict() if request.method == 'POST': try: login = request.POST['login'] password = request.POST['password'] except: messages.add_message(request, messages.WARNING, 'empty fields') return redirect(reverse('main:sing_in')) user = authenticate(username=login, password=password) if user is not None: login(request, user) return redirect('main:work') else: return redirect(reverse('main:sing_in')) return render(request, 'sing_in.html', params) and this one my mainuser model: class MainUser(AbstractBaseUser, PermissionsMixin): """ django user model """ login = models.CharField(max_length=20, blank=False, unique=True, db_index=True, verbose_name=u'Логин') first_name = models.CharField(max_length=222, blank=True, verbose_name=u'Имя') second_name = models.CharField(max_length=222, blank=True, verbose_name=u'Фамилия') email = models.EmailField(max_length=100, blank=True, verbose_name=u'email') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MainUserManager() USERNAME_FIELD = 'login' REQUIRED_FIELDS = [] def full(self): return { "first_name": self.first_name, "second_name": self.second_name, "email": self.email } @property def is_staff(self): return self.is_admin def get_short_name(self): return self.login def get_full_name(self): return u"{0} {1}".format(self.second_name, self.first_name) def __unicode__(self): return u"{}".format(self.login) class Meta: verbose_name = u"Пользователь" verbose_name_plural = u"Пользователи" I can't understand where bug in the code, it give error when i call login(request, user)
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85184445
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49089455
has comment: http://stackoverflow.com/comment/85184460
has title: user login error unicode object not callable
downvote count: 1
type: Question
upvote count: 0
score: -1

http://stackoverflow.com/comment/85132850
type: QuestionComment
has text: @user2966197: So you just want to use these lists and lists-of-lists as keys in a dictionary?
comment on: http://stackoverflow.com/q/49063779
score: 0
type: Comment

http://stackoverflow.com/a/49065965
type: Answer
has body: Without seeing the function full_item_new, it is difficult to answer but just looking at the args, you provide sc which is apparently your spark context variable. Therefore, it means you are trying to perform an action or transformation with sc while you are performing a transformation on your rdd. This is simply not possible. full_item_new is executed on the workers but sc can only be used on the driver.
answers question: http://stackoverflow.com/q/49064162
has comment: http://stackoverflow.com/comment/85139058
score: 0
has comment: http://stackoverflow.com/comment/85138843

http://stackoverflow.com/comment/84975142
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48985117
has text: In your current code you imorted `test_module_a` and `test_module_b` using `*` notation which is bound not to work. If you use `from tests/test_module_a import *` it will work
score: 0

http://stackoverflow.com/a/49090337
type: Answer
answers question: http://stackoverflow.com/q/49090272
score: 2
has comment: http://stackoverflow.com/comment/85199056
has body: This would be one way to do it: {% for guess_list in answer_guess_list %} {% for guess_value in guess_list %} {{ guess_value }}{% if forloop.counter < guess_list|length %}, {% endif %} {% endfor %} {% empty %} Nothing to show. {% endfor %} Or you could also use the built-in template filter join: {% for guess_list in answer_guess_list %} {% empty %} Nothing to show. {% endfor %}
has comment: http://stackoverflow.com/comment/85186620
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49090272

http://stackoverflow.com/comment/85242105
score: 0
has text: *Why* do you need that specific version of Python? You should *almost never* need *that* specific a version of any language. If your question is just about how to install 2.x alongside 3.x then there's plenty of material about how to do that elsewhere. If you really do need that specific version (it does happen sometimes) it would help us help you to know why.
type: QuestionComment
comment on: http://stackoverflow.com/q/49117991
type: Comment

http://stackoverflow.com/q/49035156
downvote count: 0
upvote count: 11
favorite count: 0
has answer: http://stackoverflow.com/a/49035810
tagged with: python
has body: I would like to know, whether I used toPILImage from torchvision correctly. I want to use it, to see how the images look after initial image transformations are applied to the dataset. When I use it like in the code below, the image that comes up has weird colors like this one. The original image is a regular RGB image. This is my code: import os import torch from PIL import Image, ImageFont, ImageDraw import torch.utils.data as data import torchvision from torchvision import transforms import matplotlib.pyplot as plt # Image transformations normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) transform_img = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(256), transforms.ToTensor(), normalize ]) train_data = torchvision.datasets.ImageFolder( root='./train_cl/', transform=transform_img ) test_data = torchvision.datasets.ImageFolder( root='./test_named_cl/', transform=transform_img ) train_data_loader = data.DataLoader(train_data, batch_size=4, shuffle=True, num_workers=4) #num_workers=args.nThreads) test_data_loader = data.DataLoader(test_data, batch_size=32, shuffle=False, num_workers=4) # Open Image from dataset: to_pil_image = transforms.ToPILImage() my_img, _ = train_data[248] results = to_pil_image(my_img) results.show() Edit: I had to use .data on the Torch Variable to get the tensor. Also I needed to rescale the numpy array before transposing. I found a working solution here, but it doesn't always work well. How can I do this better? for i, data in enumerate(train_data_loader, 0): img, labels = data img = Variable(img) break image = img.data.cpu().numpy()[0] # This worked for rescaling: image = (1/(2*2.25)) * image + 0.5 # Both of these didn't work: # image /= (image.max()/255.0) # image *= (255.0/image.max()) image = np.transpose(image, (1,2,0)) plt.imshow(image) plt.show()
has title: PyTorch - How to use "toPILImage" correctly
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47318871
has answer: http://stackoverflow.com/a/50838995
tagged with: pytorch
possible better answer: http://stackoverflow.com/a/50838995
type: Question
accepted answer: http://stackoverflow.com/a/49035810
score: 11
answer count: 3
has answer: http://stackoverflow.com/a/76234926

http://stackoverflow.com/q/49016991
downvote count: 0
score: 1
has title: Function for summing the dictionaries in the dictionary
type: Question
has comment: http://stackoverflow.com/comment/85039293
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85039580
favorite count: 0
has body: Every loop in this function: def sum_total(files, local_dir): final_dict = {} for i in range(len(files)): with open(local_dir+files[i], 'r') as f: data = f.readlines() res = find_by_tag(data) print('res: ', res) sum_values_from_several_dict_to_one(res) Generates example output: {'Critical Tests': {'failed': 1, 'passed': 2, 'total': 5}, 'All Tests': {'failed': 5, 'passed': 0, 'total': 5}} {'Critical Tests': {'failed': 2, 'passed': 3, 'total': 5}, 'All Tests': {'failed': 10, 'passed': 12, 'total': 12}} {'Critical Tests': {'failed': 3, 'passed': 4, 'total': 5}, 'All Tests': {'failed': 10, 'passed': 0, 'total': 10}} EXPECTED OUTPUT: I would like to sum those values into one dictionary to get output like: {'Critical Tests': {'failed': 6, 'passed': 9, 'total': 15}, 'All Tests': {'failed': 25, 'passed': 12, 'total': 27}} The problem is - how should the 'sum_values_from_several_dict_to_one' function looks like? Thats my code but it does not work.. What should be improved? def sum_values_from_several_dict_to_one(d1): final_dict = {} for d in d1 &lt;?&gt;: for test, results in d.items(): if test not in final_dict: final_dict[test] = {} for key, value in results.items(): if key in final_dict[test]: final_dict[test][results] += value else: final_dict[test][key] = value return final_dict
has comment: http://stackoverflow.com/comment/85039375
accepted answer: http://stackoverflow.com/a/49017523
has comment: http://stackoverflow.com/comment/85039190
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49017523
type: AnsweredQuestion

http://stackoverflow.com/q/49113965
score: 1
has answer: http://stackoverflow.com/a/49114253
accepted answer: http://stackoverflow.com/a/49114253
type: Question
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
tagged with: generator
has title: Exporting duplicated code from inside a yielding generator function
type: AnsweredQuestion
has body: Observe the following method: def _locate(self, text): """ This method accesses preceding locators if these exist, it then calls an overridable helper method called _relocate which receives text with readjusted boundaries and searches inside, the basic implemented behaviour is that of a logical or """ if not self.precedents: for sub_segment in self._relocate(text, Segment(0, len(text), 1)): if self._multiple: yield sub_segment elif self.max_segment.prob &gt; self._prob_threshold: yield self.max_segment return else: for precedent in self.precedents: for segment in precedent.locate(text): for sub_segment in self._relocate(text, segment): if self._multiple: yield sub_segment elif self.max_segment.prob &gt; self._prob_threshold: yield self.max_segment return # if we haven't found a good enough segment return the best one we came across while locating if not self._multiple: yield self.max_segment it has some code which is duplicated twice: for sub_segment in self._relocate(text, segment): if self._multiple: yield sub_segment elif self.max_segment.prob &gt; self._prob_threshold: yield self.max_segment return I naively thought I could probably define a single helper method and have the code just once so started to implement it, however, this proved next to impossible (because of the fact that the code uses both yields and returns) and caused me much more pain in terms of code length and run-time that it was worth. Not sure what I'm asking exactly (if anything perhaps I'm asking if anyone has any idea of some general approach to sharing generator code that yields or else sees how this can be done here?), but in any case as the topic of generators go I found this experience quite telling and interesting so I thought I'd share.

http://stackoverflow.com/q/49060336
tagged with: dll
has comment: http://stackoverflow.com/comment/85183773
tagged with: cx-oracle
has body: I have configured the Oracle client and try with the below code, But error prompted from the code. import os os.chdir("C:\\oreclient_install_dir\\instantclient_12_2") import cx_Oracle ORACLE_CONNECT = "user/pass@(DESCRIPTION=(SOURCE_ROUTE=OFF)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=1521)))(CONNECT_DATA=(SID=sid)(SRVR=DEDICATED)))" orcl = cx_Oracle.connect(ORACLE_CONNECT) print("Connected to Oracle: " + orcl.version) Error : Python.exe - Entry Point Not Found The Procedure entry point K32GetModuleBaseNameA could not be located in the dynamic link library KERNEL32.dll I am using Server 2008 32 bit as client machine and remotely connect to Oracle Data Base 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Tried both Python 2.7 and 3.6. Instant client version is "instantclient_12_2" Appreciate if you can give me a feedback on this. Thanks, Tharindu Panagoda
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85159132
has title: Python cx_Oracle connection DLL error
type: Question

http://stackoverflow.com/comment/85278577
type: Comment
comment on: http://stackoverflow.com/a/49109870
has text: @StefanS I think that's the idiomatic way in Fortran (which says something about Fortran...).
score: 0
type: AnswerComment

http://stackoverflow.com/a/48972689
type: Answer
has comment: http://stackoverflow.com/comment/84950515
score: 3
downvote count: 0
has body: Because is a method. For it to be not callable make it property with @property decorator. class Headers: @property def login_headers(self): return { 'origin': 'address.com', 'accept-encodig': 'gzip, deflate, br', 'more': '...' } For it to be more pythonic, i woud suggest using method and call it appropriate class Headers: def __init__(self): self.login_headers = { 'origin': 'address.com', 'accept-encodig': 'gzip, deflate, br', 'more': '...' } def get_login_headers(self): return self.login_headers headers = Headers() headers.get_login_headers() In instance initialization you would assign default value of login_headers and if you need to inherit you Headers class you can just override your get_login_headers to match your possible changes.
answers question: http://stackoverflow.com/q/48972673
has comment: http://stackoverflow.com/comment/84950452
has comment: http://stackoverflow.com/comment/84950433
has comment: http://stackoverflow.com/comment/84950425
upvote count: 3

uninstallation
tags question: http://stackoverflow.com/q/49012316
type: Tag
tag name: uninstallation

http://stackoverflow.com/comment/85073817
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49034016
type: QuestionComment
has text: No, please read that link again. For example, if your view was clibs/views.py, and inside that you did `from clib.api import create_dispute`, you would need to do `@patch('clib.views.create_dispute')`.

http://stackoverflow.com/a/49113220
has body: You can override __doc__ attribute test = "123" def my_func(): pass my_func.__doc__ = "help text" + test From PEP-0257: A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.
answers question: http://stackoverflow.com/q/49113174
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49113174
type: Answer
score: 9
upvote count: 9

http://stackoverflow.com/comment/84961266
comment on: http://stackoverflow.com/a/48977380
score: 0
type: AnswerComment
has text: I didn't use 'a' here, it wont make any effect, because 'a'-'a' is 0, so the 'pop' will remain same as 'pop'
type: Comment

http://stackoverflow.com/comment/85196796
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49095874
has text: Yes, custom validation of your forms.
score: 0

http://stackoverflow.com/q/49074805
has comment: http://stackoverflow.com/comment/85155646
has body: I want to crawl a website with 786 pages. my code extracts data and save it to an excel file. when I run my program for 10 pages, it works fine but when I try to crawl whole 786 pages at one-time it gives me this error: Traceback (most recent call last): File "app.py", line 32, in &lt;module&gt; crawl_names(i) File "app.py", line 16, in crawl_names html = urlopen(rq) File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.5/urllib/request.py", line 472, in open response = meth(req, response) File "/usr/lib/python3.5/urllib/request.py", line 582, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.5/urllib/request.py", line 510, in error return self._call_chain(*args) File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain result = func(*args) File "/usr/lib/python3.5/urllib/request.py", line 590, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 524: Origin Time-out my code: from urllib.request import urlopen from urllib.request import Request from bs4 import BeautifulSoup import re import xlwt headers={'User-Agent': 'Mozilla/5.0'} book = xlwt.Workbook(encoding="utf-8") sheet1 = book.add_sheet("Sheet 1") def crawl_names(page): site = 'http://nex1music.ir/pages/' + str(page) + '/' rq = Request(site, headers=headers) html = urlopen(rq) bsObj = BeautifulSoup(html, "lxml") musics = bsObj.findAll("div", {"class": "pctn"}) names = [] for m in musics: names.append(m.findChild().findAll("a", {"href": re.compile("http\:\/\/nex1music\.ir\/tag\/.+\/")})[-1].string) for i in range(len(names)): sheet1.write(i, page-1, names[i]) for i in range(1, 786): crawl_names(i) book.save("data.xls") How can I change my code in order to crawl whole 786 pages ? thank you.
downvote count: 0
has comment: http://stackoverflow.com/comment/85155537
favorite count: 0
tagged with: beautifulsoup
has title: HTTP Error 524 while crawling big websites
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
tagged with: web-crawler
tagged with: urllib
type: Question
tagged with: python-3.5

http://stackoverflow.com/q/49113247
possible better answer: http://stackoverflow.com/a/53304009
has title: Python and Visual Studio Code - How do I run a specific file in the editor?
favorite count: 0
score: 16
tagged with: python
upvote count: 16
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49137722
has answer: http://stackoverflow.com/a/53304009
accepted answer: http://stackoverflow.com/a/49137722
type: Question
answer count: 2
tagged with: visual-studio-code
has body: I am writing a small application with Visual Studio Code and Python. My application has two files, Main.py and MyCustomClass.py. Main.py is the entry point to the application, MyCustomClass.py contains the logic code to solve some problems. Currently, the debugger is set to run whatever the active file is. Is it possible to configure Visual Studio Code to run a specific file versus the active file in the editor?
downvote count: 0

http://stackoverflow.com/a/48981760
has comment: http://stackoverflow.com/comment/84968705
score: 1
has comment: http://stackoverflow.com/comment/84969127
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48981724
has comment: http://stackoverflow.com/comment/84996673
answers question: http://stackoverflow.com/q/48981724
type: AcceptedAnswer
downvote count: 0
has body: Sys.time is what you need. current_time &lt;- Sys.time() Sys.time() - current_time #Time difference of 2.900852 secs However, this has a class of difftime class(Sys.time() - current_time) #[1] "difftime" If you want it as a number for manipulation you can use as.numeric as.numeric(Sys.time() - current_time) #[1] 2.900852 The units are not always constant here and you might face issues handling it. So for example, when I now do Sys.time() - current_time it gives me #Time difference of 12.12814 mins Point here to observe is at first the units were in seconds and now they are in minutes. So this is inconsistent and maybe troublesome when you are using them for some calculation. To overcome that , as @r2evans mentions in the comment we can set the units by doing my_diff = Sys.time() - current_time units(my_diff) &lt;- "secs" my_diff #Time difference of 592.8649 secs So this would always return difference in seconds irrespective of the duration passed.
type: Answer
has comment: http://stackoverflow.com/comment/84968784
has comment: http://stackoverflow.com/comment/84968911

http://stackoverflow.com/comment/85213293
has text: @권효섭 I seem to have done something similar to what you want with `iloc` initially. Please take a look at my answer if you have time.
type: Comment
comment on: http://stackoverflow.com/a/49103701
type: AnswerComment
score: 0

http://stackoverflow.com/q/49053777
has answer: http://stackoverflow.com/a/49055444
has title: How to merge json objects containing arrays using python?
has answer: http://stackoverflow.com/a/49055946
answer count: 3
tagged with: array-merge
downvote count: 0
favorite count: 0
has body: I have two json files which contain all kinds of levels of properties. I want to write a python script that will replace existing properties and add missing ones, but keep all the other ones in place. In my attempts until now the entire "configurations" array of the original file is overwritten, including all properties. All examples I could find show merge for objects without arrays. Any help would be appreciated. Original: { "configurations": [ { "this-needs-to-stay": { "properties": { "some_property": "EXISTING" } } }, { "this-needs-to-be-updated": { "properties": { "this.would.stay": "EXISTING", "this.wont.be.overwritten": "EXISTING" } } } ], "other-values-1": [ { "components": [ { "name": "EXISTING" } ], "name": "somename" } ], "other-values-2": { "randomProperties": { "type": "random" }, "and_so_on": "you_get_the_point" } } Additional data that should be added to original: { "configurations" : [ { "this-would-be-added": { "properties": { "some-property": "ADDED" } } }, { "this-needs-to-be-updated": { "properties": { "this.would.stay": "CHANGED", "this.would.be.added": "ADDED" } } } ] } Result is a merging of the two on the property level: { "configurations": [ { "this-would-be-added": { "properties": { "some-property": "ADDED" } } }, { "this-needs-to-stay": { "properties": { "some_property": "EXISTING" } } }, { "this-needs-to-be-updated": { "properties": { "this.would.stay": "CHANGED", "this.would.be.added": "ADDED" "this.wont.be.overwritten": "EXISTING" } } } ], "other-values-1": [ { "components": [ { "name": "EXISTING" } ], "name": "somename" } ], "other-values-2": { "randomProperties": { "type": "random" }, "and_so_on": "you_get_the_point" } }
has answer: http://stackoverflow.com/a/51738480
tagged with: python
tagged with: merge
linked to: http://stackoverflow.com/q/38987
type: UnansweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
type: Question

ms-word
tags question: http://stackoverflow.com/q/49109061
tags question: http://stackoverflow.com/q/49021534
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/49088748

http://stackoverflow.com/q/49006722
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50137966
type: Question
has body: The code is as follows: # coding=utf-8 from __future__ import print_function import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import sklearn import sklearn.datasets import sklearn.ensemble import numpy as np import lime import lime.lime_tabular class Randomforest: def __init__(self): self.trained_model = None self.clf = None pass def split_dataset(self, dataset, train_percentage, feature_headers, target_header): # Split dataset into train and test dataset self.train_x, self.test_x, self.train_y, self.test_y = train_test_split(dataset[feature_headers], dataset[target_header], train_size=train_percentage) return self.train_x, self.test_x, self.train_y, self.test_y def random_forest_classifier(self, features, target): self.clf = RandomForestClassifier() self.clf.fit(features, target) return self.clf def predictProba(self, input): return self.clf.predict_proba(input) def predict_proba(self, input): return self.predictProba(input) rf = Randomforest() Headers = ["vectorName", "abmessungen_Lange", "starrflugler", "tragflachen", "triebwerke", "rumpf", "leitwerk", "drehflugler", "drehflugler_Rumpf_Cockpit", "doppeldecker", "tragflachen_Stellung_Gerade","hochDecker","triebwerke_triebwerksart", "rumpf_Rumpfformen","drehflugler_Rotor","drehflugler_Triebwerk","drehflugler_Rumpf","drehflugler_Heckausleger", "drehflugler_Triebwerk_Lufteinlass","drehflugler_Triebwerk_Luftauslass", "result"] dataset = pd.read_csv("filename.csv") train_x, test_x, train_y, test_y = rf.split_dataset(dataset, 0.7, Headers[1:-1], Headers[-1]) trained_model = rf.random_forest_classifier(train_x, train_y) predictions = trained_model.predict(test_x) feature_names = Headers[1:-1] class_names = ['1', '0'] explainer = lime.lime_tabular.LimeTabularExplainer(train_x, feature_names= feature_names, class_names=class_names, categorical_features= None, ca…
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/85019707
score: 0
has title: res = cache.get(item) TypeError: unhashable type (the error which i am getting is after running the lime explainer))
tagged with: machine-learning
tagged with: lime
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85020092
tagged with: pandas

http://stackoverflow.com/a/49144887
has body: I finally solved the problem on windows. Here is the solution in case you face it. The Theano package was faulty. I installed the latest version from github and then it threw another error as below: RuntimeError: To use MKL 2018 with Theano you MUST set "MKL_THREADING_LAYER=GNU" in your environment. In order to solve this, I created a variable named MKL_Threading_Layer under user environment variable and passed GNU. Reset the kernel and it was working. Hope it helps!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49119718

http://stackoverflow.com/a/49038131
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49037968
upvote count: 2
has body: IIUC using .loc df1.loc[below[below].index,'last_below']=1008000 df1 Out[607]: above below last_below asn country 12345 MX 7.0 3.0 1002000.0 US 5.0 4.0 1006000.0 54321 MX 4.0 6.0 1008000.0 US 1.0 0.0 NaN
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49037968

http://stackoverflow.com/a/48999516
type: Answer
downvote count: 0
score: 1
has body: l0,l1=zip(*lt) Using zip you can achieve this. l0,l1=map(list,zip(*lt)) # To get as list
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85004376
accepted answer of: http://stackoverflow.com/q/48999475
answers question: http://stackoverflow.com/q/48999475

http://stackoverflow.com/a/49026821
downvote count: 0
answers question: http://stackoverflow.com/q/49026675
has comment: http://stackoverflow.com/comment/85058678
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49026675
has comment: http://stackoverflow.com/comment/85058805
type: Answer
score: 6
upvote count: 6
has body: The problem is with the map function not the Pool object. For this case, starmap would be a good choice like this: p.starmap(f, zip([1,2,3], [4,5,6])) From python 3.3 starmap was added to the Pool object

http://stackoverflow.com/a/57894561
score: 11
answers question: http://stackoverflow.com/q/48966606
upvote count: 11
has body: There is another workaround to this error: Delete your node_modules folder. Run npm install --global windows-build-tools --save in your command prompt. Install node-sass using the command: npm install node-sass@4.12.0 --save (or the latest version) This should solve the error and return you a gyp info ok message! If you encounter Node Sass could not find a binding for your current environment, resolve it by running: npm rebuild node-sass
has comment: http://stackoverflow.com/comment/137348843
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/135446271

swagger-codegen
tag name: swagger-codegen
tags question: http://stackoverflow.com/q/48995459
type: Tag

http://stackoverflow.com/comment/84943381
has text: Print the first letter of the inputted middle name, and print that, instead of the entire middle name, I believe anyway, very new to coding.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48968861

http://stackoverflow.com/q/49002056
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85013922
tagged with: go
tagged with: protocol-buffers
has body: I want to send a message from go client to python server. I am using protobuff for the same. Go side message structure type CreateProductInfo struct { name string fruits []*Fruits } type Fruits struct { name string } I am expecting the below response in my python server. { name : "product_info" fruits : [ { name : "Apple" } ] } Instead, I'm getting this. { name : "product_info" fruits : [ name : "Apple" ] }
has title: Protobuff message from go client to python server
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49006108

http://stackoverflow.com/a/49091345
type: Answer
has body: Ok, problem 1 is you never call s_phrase. Problemo 2 is that the phrase variable can't be seen by s_phrase. Problem numero C is that your indentation is messed up. Issue 4 is more the fact that this seems like a very 'C' way of tackling the challenge. Borrowing from Spade, here is a more succinct way of doing it that is formatted to your original program. def main(): s= "" phrase="" programdescription(s) s_phrase(phrase) #This function displays the program description def programdescription(s): s = print("This program determines if a word, phrase, or sequence can be read the same backward as forward.") #This function requests user input for analysis def s_phrase(phrase): phrase = input("Enter a word or phrase: ") phrase = phrase.upper() r_phrase = phrase[::-1] print(r_phrase) if phrase == r_phrase: print(phrase, "is a palindrome.") else: print(phrase, "is not a palindrome.") main()
score: 0
accepted answer of: http://stackoverflow.com/q/49091283
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49091283

http://stackoverflow.com/q/49097593
favorite count: 0
tagged with: python-3.x
has title: Can't enable SSL with celery
tagged with: python
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49111240
linked to: http://stackoverflow.com/q/12871565
has body: I have Django application with celery, which works fine. app = Celery('backend', broker='amqp://guest:guest@localhost:5672//',) Then I tried to cipher connection with SSL: app = Celery('backend', broker='amqp://guest:guest@localhost:5672//',) app.config_from_object('django.conf:settings', namespace='CELERY') And with settings.py: import ssl CELERY_BROKER_USE_SSL = { 'keyfile': '/var/ssl/server-key.pem', 'certfile': '/var/ssl/server-crt.pem', 'ca_certs': '/var/ssl/ca-crt.pem', 'cert_reqs': ssl.CERT_REQUIRED } defining certificates as described in https://stackoverflow.com/a/34712536/6153117 but when running celery -A backend worker I got the error [2018-03-04 16:27:16,771: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:645). Trying again in 2.00 seconds... [2018-03-04 16:27:18,794: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:645). Trying again in 4.00 seconds...
tagged with: celery
type: Question
has answer: http://stackoverflow.com/a/49097823
upvote count: 4
answer count: 2
possible better answer: http://stackoverflow.com/a/49097823
downvote count: 0
has answer: http://stackoverflow.com/a/49111240

http://stackoverflow.com/comment/85103392
comment on: http://stackoverflow.com/q/49049208
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85106468
comment on: http://stackoverflow.com/a/49031573
type: AnswerComment
has text: .. But i want to pass the length of each element of size_DF to the function like this for row in size_DF: length = row[0] print "length: ", length insertDF = newObject.full_item(sc, dataBase, length, end_date)
score: 0
type: Comment

http://stackoverflow.com/a/48967630
score: 0
has body: This would do: Elements of key are in LstA key is also in LstB result = 0 output = [] for key, value in dict.items(): element1, element2 = key if (element1 in lstA and element2 in lstA and key in lstB): result += value output.append(value) print(result, output) 0.35400000000000004 [0.04, 0.05, 0.03, 0.1, 0.06, 0.074] Is this what you were looking for?
type: Answer
answers question: http://stackoverflow.com/q/48967353

http://stackoverflow.com/q/49107868
tagged with: python
has answer: http://stackoverflow.com/a/49108127
has answer: http://stackoverflow.com/a/49107982
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85221107
type: Question
tagged with: monthcalendar
has body: Test Code: import calendar from collections import Counter dates = ( '2017-05-01 11:45:35', '2017-06-01 11:45:35', '2017-06-01 11:45:35', '2017-07-01 11:45:35', ) city_file = [{'Start Time': d} for d in dates] c = Counter((calendar.month_name[int(month['Start Time'][5:7])] for month in city_file)) print(c) can someone explain the code c = Counter((calendar.month_name[int(month['Start Time'][5:7])] for month in city_file)) especially the part, if i enter anything other than 5:7 it gives an error message. month['Start Time][5:7] desired output : count of months example January 12 feb 13
tagged with: counter
has answer: http://stackoverflow.com/a/49107974
score: 0
answer count: 3
tagged with: datetime
has title: Finding the max month of a year

http://stackoverflow.com/a/49201164
has body: Mercator should be 'mercator' Lattitude and longtitude must be lists: 'lat': ['36.734772499999998'], 'lon': ['70.811995299999978'], Here is working example: import plotly.plotly as py import plotly.graph_objs as go from plotly import tools from plotly.offline import iplot, init_notebook_mode init_notebook_mode() mpis = [{'lat': ['36.7347725'], 'lon': ['70.8119953'], 'marker': {'color': 'rgb(0,116,217)', 'line': {'color': 'rgb(40,40,40)', 'width': 0.5}, 'size': 38.700000000000003, 'sizemode': 'diameter'}, 'text': '0.387', 'type': 'scattergeo'}, ] layout = go.Layout( title = 'MPI', showlegend = True, geo = dict( scope='world', projection=dict( type = 'natural earth'), showland = True, landcolor = 'rgb(217, 217, 217)', subunitwidth=1, countrywidth=1, subunitcolor="rgb(255, 255, 255)", countrycolor="rgb(255, 255, 255)" ),) fig = go.Figure(layout=layout, data=mpis) iplot( fig, validate=False)
accepted answer of: http://stackoverflow.com/q/49097639
downvote count: 0
answers question: http://stackoverflow.com/q/49097639
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/a/49020352
has body: by for loop, you are printing the items inside the list, but in list comprehension itself creating a outer list. I think you need, print sum([i for i in datas],[])
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49020269
has comment: http://stackoverflow.com/comment/85046623
has comment: http://stackoverflow.com/comment/85046074
has comment: http://stackoverflow.com/comment/85047698

http://stackoverflow.com/a/49120189
type: Answer
answers question: http://stackoverflow.com/q/49120112
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49120112
score: 2
type: AcceptedAnswer
downvote count: 0
has body: IIUC df.apply(pd.value_counts).T Out[1224]: AboveStandard BelowStandard Results_Disadvantaged 2.0 1.0 Results_Advantaged 3.0 NaN

http://stackoverflow.com/comment/85084040
has text: @MartinEvans Just realised what you mean ... fixed it :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49033583

http://stackoverflow.com/comment/85171229
comment on: http://stackoverflow.com/q/49083021
score: 0
type: QuestionComment
type: Comment
has text: List comprehension is what you want, almost the same as your sql.

http://stackoverflow.com/q/49114178
upvote count: 1
has answer: http://stackoverflow.com/a/49114214
downvote count: 1
type: AnsweredQuestion
has title: Can't find aggregation result column in Python Pandas
has comment: http://stackoverflow.com/comment/85235945
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/49114214
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: python
has body: s = pd.Series(["08-10-2017", "08-10-2017", "08-10-2017", "09-10-2017", "09-10-2017", "09-10-2017", "10-10-2017", "10-10-2017", "10-10-2017", "11-10-2017", "11-10-2017", "11-10-2017", "12-10-2017", "12-10-2017", "12-10-2017", "13-10-2017", "13-10-2017", "13-10-2017", "14-10-2017", "14-10-2017"]) p = pd.DataFrame(data=s) p.columns = ['date'] p.groupby('date').agg('count').reset_index().columns Where is 'count' column ?

http://stackoverflow.com/q/49053741
favorite count: 0
tagged with: rest
has body: I'm currently using flask-restful (http://flask-restful.readthedocs.io/en/0.3.5/index.html) to deploy resources as endpoints and I'm wondering if there's a way to access the API logger from within then resources classes. I've skimmed through the docs and couldn't find the appropriate answer. Basically I want to do that : from flask_restful import Resource class SomeEndpoint(Resource): def get(self): try: ... something throws an exception except SomeException as se: ... send custom message to API logger &lt;----- Here! return response What I though of doing was passing the logger from the API through the constructor of the Resource like that : App = Flask(__name__) api = Api(App) api.add_resource(SomeEndpoint, '/', resource_class_kwargs={'logger': App.logger}) Is this the most appropriate way to access the logger inside flask-restful resource endpoints ? Thanks a lot
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/52678595
upvote count: 11
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/60476125
accepted answer: http://stackoverflow.com/a/49070017
tagged with: flask
possible better answer: http://stackoverflow.com/a/52678595
has title: Accessing the API logger in Flask-Restful's resources
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49070017

http://stackoverflow.com/a/49325567
downvote count: 0
score: 1
has body: It appears you are trying to get the intersection of these. Pybedtools will accept streams as an input. Read your data into a string that is in bed format. "chr,start,stop" I start with a python dictionary and loop through it. bed_string += "{0} {1} {2} {3} {0}|{1}|{2}|{3}\n".format(chrom, coord_start, coord_stop, aberration) # Now create your bedtools. breakpoint_bedtool = pybedtools.BedTool(bed_string, from_string=True) target_bedtool = pybedtools.BedTool(self.args.Target_Bed_File, from_string=False) # Find target intersects for printing. breakpoint_target_intersect = breakpoint_bedtool.intersect(target_bedtool, wb=True, stream=True)
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49118347

http://stackoverflow.com/a/49178394
has comment: http://stackoverflow.com/comment/85405652
answers question: http://stackoverflow.com/q/49101952
type: Answer
score: 1
upvote count: 1
has body: Unfortunately, this is currently not supported by pyDatalog.
has comment: http://stackoverflow.com/comment/85364326
downvote count: 0

http://stackoverflow.com/comment/85187430
type: Comment
has text: Sure, new solution added.
comment on: http://stackoverflow.com/a/49090913
score: 0
type: AnswerComment

http://stackoverflow.com/q/49051378
score: 1
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: maze
has body: I've been working on this for a while, this is what I've got so far... this code doesn't work. This code is just for reference. The assignment is a maze without walls. I have to use a recursive algorithm. Each space has a number, when I land on a space, that number tells me how much I can move in a specific direction. I have to return the path. (I already did the version where I return True or False if there is a solution.) I can't seem to return the path itself. def pathsolve(self, start, end, vis=None): z=self.__getitem__(start) x,y=start b=False if path==None: path=deque() if vis==None: vis=deque() if start == end: vis.appendleft(start) return True elif start in path: return False elif z==0: return False else: #visited.add(start) path.append(start) if self.onboard((x+z,y)) and (x+z,y) not in path: #print("going to"+str((x+z,y))+" by "+str(z)+" from "+str (start)) b=self.pathsolve((x+z,y),end, path) #print() if self.onboard((x,y+z)) and (x,y+z) not in path and b == False: #print("xgoing to"+str((x,y+z))+" by "+str(z)+" from "+str(start)) b=self.pathsolve((x,y+z),end, path) #print() if self.onboard((x,y-z)) and (x,y-z) not in path and b == False: #print("ygoing to"+str((x,y-z))+" by "+str(z)+" from "+str(start)) #print(self.onboard((x,y-z))) b=self.pathsolve((x,y-z),end, path) #print(path) if self.onboard((x-z,y)) and (x-z,y) not in path and b == False: #print("zgoing to"+str((x-z,y))+" by "+str(z)+" from "+str(start)) #print(end) b=self.pathsolve((x-z,y),end, path) # if b==True and start is not vis.appendleft(start) return b
tagged with: python
has title: Can't seem to create recursive algorithm for wallless maze
downvote count: 0
has answer: http://stackoverflow.com/a/49052747
accepted answer: http://stackoverflow.com/a/49052747
type: AnsweredQuestion
tagged with: recursion

http://stackoverflow.com/q/49004398
accepted answer: http://stackoverflow.com/a/49004442
upvote count: 1
tagged with: python
has title: Convert a square pandas dataframe to a tall format
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/49004773
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49004442
possible better answer: http://stackoverflow.com/a/49004773
tagged with: pandas
favorite count: 0
has body: I have a dataframe which is a correlation matrix. I want to create a graph out of it and to do so I need to convert the correlation dataframe that looks like this df = pd.DataFrame([[1,0.2,0.4],[0.2,1,0.6],[0.4,0.6,1]]) df.columns = list('ABC') df.index= list('ABC') df # result- A B C A 1.0 0.2 0.4 B 0.2 1.0 0.6 C 0.4 0.6 1.0 to this format - df = pd.DataFrame({ 'from':['A', 'A', 'A', 'B', 'B', 'C'], 'to':['A', 'B', 'C', 'B', 'C', 'C'], 'value':[1, 0.2,0.4,1,0.6,1]}) df # result- from to value 0 A A 1.0 1 A B 0.2 2 A C 0.4 3 B B 1.0 4 B C 0.6 5 C C 1.0 How do I achieve this?

http://stackoverflow.com/a/49074723
upvote count: 4
answers question: http://stackoverflow.com/q/49074599
has body: Pandas is convenient for this: import pandas as pd hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)] df = pd.DataFrame([[i[0][0], i[0][1], i[1]] for i in hello], columns=['keyword 1', 'keyword 2', 'frequency']) # keyword 1 keyword 2 frequency # 0 case iphone 91524 # 1 adapter iphone 12233 # 2 battery smartphone 88884 df.to_csv('file.csv', index=False)
downvote count: 0
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49074599
type: Answer

http://stackoverflow.com/comment/85212997
has text: d is the set of attributes for node n
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49103913
score: 1

http://stackoverflow.com/comment/85098456
comment on: http://stackoverflow.com/q/49046972
score: 0
type: Comment
type: QuestionComment
has text: you have just opened the file, you have never read it

http://stackoverflow.com/comment/85098396
comment on: http://stackoverflow.com/q/49044610
has text: @Frank when trying to send keys with out making the input element visible I get: ElementNotInteractableException: Message: Element is not reachable by keyboard
type: Comment
type: QuestionComment
score: 0

tkmessagebox
tags question: http://stackoverflow.com/q/49084839
type: Tag
tag name: tkmessagebox
tags question: http://stackoverflow.com/q/49072942

http://stackoverflow.com/q/49103077
tagged with: pyspark
has title: Error when submitting a python script on YARN using spark-submit
has comment: http://stackoverflow.com/comment/85227430
tagged with: spark-submit
has comment: http://stackoverflow.com/comment/85227422
score: 0
has comment: http://stackoverflow.com/comment/85220015
tagged with: apache-spark
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85227312
type: UnansweredQuestion
tagged with: hadoop-yarn
has body: I have configured hadoop and spark on cluster and use 10.1.10.101 as master node, 10.1.10.102 ~ 110 as slave nodes. Here I write a simple python script from pyspark.conf import SparkConf from pyspark.context import SparkContext sc = SparkContext(conf=SparkConf().setAppName("test")) def inside(p): x, y = random.random(), random.random() return x*x + y*y &lt; 1 count = sc.parallelize(xrange(0, NUM_SAMPLES)) \ .filter(inside).count() and submitting it use spark-submit as follows spark-submit --master yarn /home/test/pyspark_script.py where pyspark_scirpt.py is the python file given above. Then I got the following lengthy output, in which several ERRORs and WARNs appear. 18/03/05 21:01:17 INFO spark.SparkContext: Running Spark version 2.1.0 18/03/05 21:01:17 INFO spark.SecurityManager: Changing view acls to: hadoop 18/03/05 21:01:17 INFO spark.SecurityManager: Changing modify acls to: hadoop 18/03/05 21:01:17 INFO spark.SecurityManager: Changing view acls groups to: 18/03/05 21:01:17 INFO spark.SecurityManager: Changing modify acls groups to: 18/03/05 21:01:17 INFO spark.SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(hadoop); groups with view permissions: Set(); users with modify permissions: Set(hadoop); groups with modify permissions: Set() 18/03/05 21:01:17 INFO util.Utils: Successfully started service 'sparkDriver' on port 35615. 18/03/05 21:01:17 INFO spark.SparkEnv: Registering MapOutputTracker 18/03/05 21:01:17 INFO spark.SparkEnv: Registering BlockManagerMaster 18/03/05 21:01:17 INFO storage.BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information 18/03/05 21:01:17 INFO storage.BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up 18/03/05 21:01:17 INFO storage.DiskBlockManager: Created local directory at /tmp/blockmgr-2299fc0c-6efe-47e1-9bb5-7e1ca7aa49a1 18/03/05 21:01:17 INFO memory.MemoryStore: MemoryStore started with capacity 366.3 MB …
type: Question

http://stackoverflow.com/q/49041912
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49042122
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49042099
score: 1
type: Question
answer count: 2
downvote count: 0
has body: right now I have a problem where I want to raise a specific TypeError if there is one. However, what ends up happening is the interpreter sees the first error, and then in the middle of handling it it raises the other one as well saying "During handling of the above exception, another exception occurred:" this is what I have def function(dictionary) try: value = max(dictionary.values()) except TypeError: raise TypeError("some error") I plug in the following into the shell: function({1:'a', 2:3}) How can I approach this?
favorite count: 0
tagged with: exception
has comment: http://stackoverflow.com/comment/85089133
has comment: http://stackoverflow.com/comment/85089248
tagged with: python-3.x
has title: How to raise exception within a try/except block properly

http://stackoverflow.com/comment/85215663
comment on: http://stackoverflow.com/a/49093783
type: AnswerComment
type: Comment
score: 1
has text: In the view you can access the errors using form.errors which returns a dictionary

http://stackoverflow.com/comment/124019472
type: Comment
has text: Where are you getting `T` is equivalent to minutes? These values are not listed in the pandas docs for [Series.rolling](https://pandas.pydata.org/docs/reference/api/pandas.Series.rolling.html)
comment on: http://stackoverflow.com/a/49089266
score: 0
type: AnswerComment

http://stackoverflow.com/a/48980314
has comment: http://stackoverflow.com/comment/84965780
has body: For purposes of efficiency, traditional python dictionaries are unordered. If you need order, then you need OrderedDict: &gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; newDict = OrderedDict((list1[c], number) for c, number in enumerate(list2)) &gt;&gt;&gt; print(newDict) OrderedDict([('a', 5), ('b', 3), ('c', 7), ('d', 3)]) In Python 3.7, ordinary python dictionaries, implemented using a new algorithm, will be ordered. Until then, if you need order, use OrderedDict.
answers question: http://stackoverflow.com/q/48980285
score: 3
accepted answer of: http://stackoverflow.com/q/48980285
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84965751
upvote count: 3
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85163268
type: AnswerComment
has text: yes I misunderstood what the add function does and edited accordingly ;-)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49078443

http://stackoverflow.com/comment/85218807
type: QuestionComment
comment on: http://stackoverflow.com/q/49106837
score: 1
has text: Is possible add some sample data?
type: Comment

http://stackoverflow.com/q/49032834
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49032910
favorite count: 0
has title: Getting last element from a JSON with Python
accepted answer: http://stackoverflow.com/a/49032910
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
has body: I have files with the following structure: { "function": "ComAl_Set_nad_crtl_xcall_state", "timeStamp": 1488500329974, "Param1": "SIG_NAD_XCALL_ATTEMPTS_COUNT", "Value1": "2" } These JSON files are created by some functions which I have in my program. But I have an issue getting the last value from these files (Value1). Currently this is the code I am using to get data from the file: def get_json_from_stub(self, file_name): def jsonize_stub(raw_data): end = raw_data.rfind(",") parsed_data = "[" + raw_data[:end] + "]" return json.loads(parsed_data.replace("\00", "")) command = "'cat " + self.stub_path + file_name + "'" content = self.send_ssh_command(command) json_stub = jsonize_stub(content) return json_stub and this is the code for getting Value1: @app.route('/stub/comal/getSignal/ComAl_Set_nad_crtl_xcall_requests', methods=['GET']) def get_nad_crtl_xcall_requests(): file_name = "ComAl_Set_nad_crtl_xcall_requests.out" json_stub = self.stubManager.get_json_from_stub(file_name) return MapEcallRequests().tech_to_business(json_stub[-1]["Value1"]) more specifically I want to replace json_stub[-1]["Value1"] with another way of getting Value1. The problem is that sometimes these files don´t get written so I would like to get Value1 in a different way and to raise an error message in case Value1 isn´t there, just to avoid my application crashing in case the value is not there. Is there are way to do it? Thanks.

http://stackoverflow.com/a/49132584
has comment: http://stackoverflow.com/comment/85281063
answers question: http://stackoverflow.com/q/49119768
downvote count: 0
has body: Why don't you try to run it through your host via xterm. In mininet: xterm h0 Then (be in the right directory): ./arp_ping.py
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/49031309
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: tensorflow
type: Question
tagged with: numpy
downvote count: 0
has title: ValueError: `class_weight` must contain all classes in the data. The classes {1, 2, 3} exist in the data but not in `class_weight`
tagged with: keras
has body: ValueError: class_weight must contain all classes in the data. The classes {1, 2, 3} exist in the data but not in class_weight I am trying to assign class-weights to my un-balanced classes but after model.fit() it generates this error although i seen other solutions already given for this problem but still unable to solve it. test_split=round(n*2/3) x_train=x[:test_split] y_train=y[:test_split] x_test=x[test_split:] y_test=y[test_split:] class_weight_list = compute_class_weight('balanced', numpy.unique(y_train), y_train) class_weight = dict(zip(numpy.unique(y_train), class_weight_list)) x_train=x_train.astype('float64') x_test=x_test.astype('float64') x_train/=255 x_test/=255 y_train=keras.utils.to_categorical(y_train, num_classes) y_test=keras.utils.to_categorical(y_test, num_classes) hist=model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test), callbacks=[checkpoint], class_weight=class_weight )
tagged with: deep-learning
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49031961
accepted answer: http://stackoverflow.com/a/49031961

http://stackoverflow.com/comment/85129931
type: Comment
comment on: http://stackoverflow.com/q/49062287
has text: All back propagation algorithms use SGD. Adam stands for adaptive momentum, it is SGD + momentum. There is no "fixing" this problem, however, read about "[early stopping](https://www.quora.com/How-does-one-employ-early-stopping-in-TensorFlow)".
score: 0
type: QuestionComment

http://stackoverflow.com/q/49029907
downvote count: 0
answer count: 1
has body: I am new to Sanic and I am trying to get it to work with Motor. I did manage to get everything to work in a single file, however, when I try it out within my project structure, I am running into the below issues. [2018-02-28 17:26:58 +0530] [3720] [ERROR] Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/sanic/app.py", line 556, in handle_request response = await response File "/usr/src/Python-3.6.4/Lib/asyncio/coroutines.py", line 129, in throw return self.gen.throw(type, value, traceback) File "/home/msambare/Documents/Projects/Snippets/Sanic-Motor- Issue/IAC/src/MyPackgae/REST/user_REST.py", line 42, in post request.json['last'] File "/usr/src/Python-3.6.4/Lib/asyncio/coroutines.py", line 129, in throw return self.gen.throw(type, value, traceback) File "/home/msambare/Documents/Projects/Snippets/Sanic-Motor- Issue/IAC/src/MyPackgae/DAO/user_DAO.py", line 40, in register_user result = await db.users.insert_one(serialized_user) RuntimeError: Task &lt;Task pending coro=&lt;Sanic.handle_request() running at /usr/local/lib/python3.6/site-packages/sanic/app.py:556&gt; created at /usr/local/lib/python3.6/site-packages/sanic/server.py:299&gt; got Future &lt;Future pending cb=[run_on_executor.&lt;locals&gt;._call_check_cancel() at /usr/local/lib/python3.6/site- packages/motor/frameworks/asyncio/__init__.py:85]&gt; attached to a different loop I did some research and as mentioned on the GitHub pages of Sanic, tried the 'before-server-block' section for db setup. That works in a single file, however, not in my project structure. My project structure looks something like: Project Structure Below is my code. I have recreated the issue in a simpler structure without losing the essence. src/MyPackage/Model/user.py class User(object): def __init__(self, first, last): self.first = first self.last = last src/MyPackage/UC/user_uc.py from Model import User from DAO import User_DAO class User_UC(object): def __init__(self): self._user = None def create_u…
has title: Sanic and Motor use different event loops
has answer: http://stackoverflow.com/a/49042217
favorite count: 0
tagged with: motordriver
tagged with: python
score: 5
accepted answer: http://stackoverflow.com/a/49042217
type: AnsweredQuestion
upvote count: 5
tagged with: sanic
type: Question

http://stackoverflow.com/comment/110784810
has text: One thing you can do is normalize all the vectors ahead of time. Then you don't need to divide by the two norms in your comparator.
type: QuestionComment
comment on: http://stackoverflow.com/q/49019091
score: 1
type: Comment

http://stackoverflow.com/q/49083680
answer count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/69079804
tagged with: tensorboard
tagged with: python
has title: How are the new tf.contrib.summary summaries in TensorFlow evaluated?
has comment: http://stackoverflow.com/comment/121411706
has answer: http://stackoverflow.com/a/69079804
type: AnsweredQuestion
score: 147
has body: I'm having a bit of trouble understanding the new tf.contrib.summary API. In the old one, it seemed that all one was supposed to do was to run tf.summary.merge_all() and run that as an op. But now we have things like tf.contrib.summary.record_summaries_every_n_global_steps, which can be used like this: import tensorflow.contrib.summary as tfsum summary_writer = tfsum.create_file_writer(logdir, flush_millis=3000) summaries = [] # First we create one summary which runs every n global steps with summary_writer.as_default(), tfsum.record_summaries_every_n_global_steps(30): summaries.append(tfsum.scalar("train/loss", loss)) # And then one that runs every single time? with summary_writer.as_default(), tfsum.always_record_summaries(): summaries.append(tfsum.scalar("train/accuracy", accuracy)) # Then create an optimizer which uses a global step step = tf.create_global_step() train = tf.train.AdamOptimizer().minimize(loss, global_step=step) And now come a few questions: If we just run session.run(summaries) in a loop, I assume that the accuracy summary would get written every single time, while the loss one wouldn't, because it only gets written if the global step is divisible by 30? Assuming the summaries automatically evaluate their dependencies, I never need to run session.run([accuracy, summaries]) but can just run, session.run(summaries) since they have a dependency in the graph, right? If 2) is true, can't I just add a control dependency to the training step so that the summaries are written on every train run? Or is this a bad practice? Is there any downside to using control dependencies in general for things that are going to be evaluated at the same time anyway? Why does tf.contrib.summary.scalar (and others) take in a step parameter? By adding a control dependency in 3) I mean doing this: tf.control_dependencies(summaries): train = tf.train.AdamOptimizer().minimize(loss, global_step=step)
tagged with: tensorflow
type: Question
upvote count: 148

http://stackoverflow.com/comment/84941051
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48967197
has text: `2 <= r <= 12 >= c >= 2`

statistics
tags question: http://stackoverflow.com/q/48997277
tags question: http://stackoverflow.com/q/49086721
tags question: http://stackoverflow.com/q/49008278
tags question: http://stackoverflow.com/q/49025162
tag name: statistics
tags question: http://stackoverflow.com/q/49067869
tags question: http://stackoverflow.com/q/49045372
tags question: http://stackoverflow.com/q/49006013
tags question: http://stackoverflow.com/q/49039201
tags question: http://stackoverflow.com/q/49087869
tags question: http://stackoverflow.com/q/48989708
type: Tag

http://stackoverflow.com/q/49021566
has comment: http://stackoverflow.com/comment/85049139
downvote count: 0
has title: Python Request to send a file with a specific part
has comment: http://stackoverflow.com/comment/85052689
has answer: http://stackoverflow.com/a/49039927
answer count: 1
has body: I'm trying to send a file via the request library but the receiver requires a part with a designated name (receivers terminology). I have something like this... so far: filePath = os.path.join( GetDownloadFolder(), fileName ) files = {'upload': open( str( filePath ),'rb')} response = requests.post( url, headers=header, files=files, verify=False ) GetDownloadFolder() simply gets the location where the file is. Header contains the account info and content type. The code above talks to the server and no longer complains that the file cannot be found. I get an error back from the server that a part with a specific name must exist. I tried using the data=values parameters with: values = {'upload': ''} That unfortunately didn't solve the issue. Any ideas would be appreciated.
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/85076988
score: 1
type: Question

http://stackoverflow.com/a/49075217
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85158176
type: Answer
answers question: http://stackoverflow.com/q/49075086
upvote count: 1
has body: Your only call to move_ball uses a constant vector. Since you never change the call parameters, the ball moves only that way. b.move_ball(5, -5) Yes, you change the vector components within move_ball when you hit a wall. However, on the next call, you change them back to the original values and move the ball in the original direction. You have to initialize the vector outside move_ball, and then let the routine access the existing vector when it's called.
score: 1
accepted answer of: http://stackoverflow.com/q/49075086

http://stackoverflow.com/a/48982484
has comment: http://stackoverflow.com/comment/84970836
has comment: http://stackoverflow.com/comment/84970577
has comment: http://stackoverflow.com/comment/84973392
has comment: http://stackoverflow.com/comment/84973353
has comment: http://stackoverflow.com/comment/84974370
has comment: http://stackoverflow.com/comment/84970783
has comment: http://stackoverflow.com/comment/84970739
has comment: http://stackoverflow.com/comment/84971155
has comment: http://stackoverflow.com/comment/84973372
has comment: http://stackoverflow.com/comment/84970609
has comment: http://stackoverflow.com/comment/84971282
has body: It seems you need if get: ValueError: If using all scalar values, you must pass an index what means there is only dict: d = {"PatientGuid": "0", "Gender": 1, "YearOfBirth": 1923} df = pd.DataFrame([d]).rename(columns={'PatientGuid':'a','Gender':'b','YearOfBirth':'c'}) print (df) b a c 0 1 0 1923 But if add columns parameter to DataFrame constructor get NaNs row, because no align: d = {"PatientGuid": "0", "Gender": 1, "YearOfBirth": 1923} df = pd.DataFrame([d], columns=['a','b','c']) print (df) a b c 0 NaN NaN NaN
has comment: http://stackoverflow.com/comment/84974316
score: 0
has comment: http://stackoverflow.com/comment/84970059
has comment: http://stackoverflow.com/comment/85019394
has comment: http://stackoverflow.com/comment/84970086
has comment: http://stackoverflow.com/comment/84970914
has comment: http://stackoverflow.com/comment/84970147
has comment: http://stackoverflow.com/comment/84970177
type: Answer
has comment: http://stackoverflow.com/comment/84970033
answers question: http://stackoverflow.com/q/48982185

http://stackoverflow.com/comment/85229432
score: 1
type: AnswerComment
has text: I found many issues in this library on GitHub. I guess, I'll need to see it through Autobahn. I hope it's a flexible module which can be used with different Websockets. Thanks for your effort.
type: Comment
comment on: http://stackoverflow.com/a/49112178

http://stackoverflow.com/q/49048520
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49070994
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: pycharm
upvote count: 14
type: Question
score: 14
tagged with: matplotlib
has title: How to prevent PyCharm from overriding default backend as set in matplotlib?
has answer: http://stackoverflow.com/a/49070994
has body: I've set my default backend to Qt5Agg in .config/matplotlib/matplotlibrc. This works if I use a regular ssh prompt and open ipython and run import matplotlib as mpl I correctly get: mpl.get_backend() =&gt; "Qt5Agg" When I connect through pyCharm remote console, the default backend is set to 'module://backend_interagg' which seems to be a purpose built helper extension by pycharm. Using mpl.use("Qt5Agg") works as expected (i.e. correctly sets the backend and allows me to use it). I'm just trying to get the default working and the pycharm remote console to properly use my rc file parameters. Fwiw, I've tried actually setting my master rc file (in the site-packages directory) to have Qt5Agg and I still get this problem. Also, mpl.get_configdir() correctly returns ~/.config/matplotlib Any ideas?

http://stackoverflow.com/a/49130224
has comment: http://stackoverflow.com/comment/86201594
downvote count: 0
has body: The recommended way to interact with Cloud Datastore from a Cloud Dataflow Pipeline is to use the Datastore I/O API, which is available through the Dataflow SDK and provides some methods to read and write data to a Cloud Datastore database. You can find detailed documentation for the Datastore I/O package for Dataflow SDK 2.x for Python in this other link. The datastore.v1.datastoreio module is the specific module that you want to use. There is plenty of information in the links I am sharing, but in short, it is a connector to Datastore that uses PTransform to read / write / delete a PCollection from Datastore using the classes ReadFromDatastore() / WriteToDatastore() / DeleteFromDatastore() respectively. You should try using it instead of implementing the calls yourself. I suspect this may be the reason for the error you are seeing, as a Datastore implementation already exists in the Dataflow SDK: "google.datastore.v1.PartitionId.project_id" is already defined in file "google/cloud/proto/datastore/v1/entity.proto". UPDATE: It looks like those three classes collect several mutations and executes them in a single transaction. You can check that in the code describing the classes. If the aim is to retrieve (get()) and then update (put()) a Datastore entity, you can probably work with the write_mutations() function, which is described in the documentation, and you can work with a full batch of mutations performing the operations you are interested in.
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48990784
upvote count: 1
has comment: http://stackoverflow.com/comment/85266742
has comment: http://stackoverflow.com/comment/85314662

http://stackoverflow.com/a/49070085
score: 0
has comment: http://stackoverflow.com/comment/85162569
type: Answer
has body: I would store all the radio buttons in a list, then disable every buttons when you reach 30, as seen below : total_choices = [("1"), ("2"), ("3"), ("4"), ("5")] var = tk.IntVar() var.set(0) sum = 0 def Calculator(): global sum global buttons num = var.get() sum = sum + num if sum&gt;30 # Grey out all the radio buttons for b in buttons: b.config(state=disabled) global buttons buttons = list() for val, choice in enumerate(total_choices): buttons.append(tk.Radiobutton(root, text=choice, indicatoron = 0, width = 10, variable=var, command=Calculator, value=val)) buttons[-1].place(x=val*100,y=180))
answers question: http://stackoverflow.com/q/49061602

http://stackoverflow.com/a/49020081
answers question: http://stackoverflow.com/q/49020018
type: Answer
accepted answer of: http://stackoverflow.com/q/49020018
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Python doesn't break this a, b = b, a + b into this: a = b b = a + b Instead, Python compiler evaluates right hand of an expression first by converting this: a = 0 b = 1 a, b = b, a + b into this: a = 0 b = 1 a, b = 1, 1 then assigns it in proper order. So a and b becomes 1.

variables
tag name: variables
tags question: http://stackoverflow.com/q/49061754
tags question: http://stackoverflow.com/q/49030793
tags question: http://stackoverflow.com/q/49103406
tags question: http://stackoverflow.com/q/49033116
tags question: http://stackoverflow.com/q/49099141
tags question: http://stackoverflow.com/q/49095038
type: Tag
tags question: http://stackoverflow.com/q/49099687
tags question: http://stackoverflow.com/q/49058510
tags question: http://stackoverflow.com/q/49099798
tags question: http://stackoverflow.com/q/48990191
tags question: http://stackoverflow.com/q/49081377
tags question: http://stackoverflow.com/q/49068153

buildroot
tags question: http://stackoverflow.com/q/49059035
tag name: buildroot
type: Tag

http://stackoverflow.com/a/49081558
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49081524
has body: Use string slicing: word = "dictionary" for i in range(len(word), 0, -1): print(word[:i]) Output: dictionary dictionar dictiona diction dictio dicti dict dic di d As a function: def slice_output(w): print('\n'.join(w[:i] for i in range(len(w), 0, -1)))
type: Answer
downvote count: 0

http://stackoverflow.com/q/49083524
has body: I have a dataframe and I want to convert it to a numpy array. &gt;&gt;&gt; df.index DatetimeIndex(['2018-02-28 01:00:00', '2018-02-28 01:01:00', '2018-02-28 01:02:00', '2018-02-28 01:03:00', '2018-02-28 01:04:00', '2018-02-28 01:05:00', '2018-02-28 01:06:00', '2018-02-28 01:07:00', '2018-02-28 01:08:00', '2018-02-28 01:09:00', ... '2018-02-28 17:25:00', '2018-02-28 17:26:00', '2018-02-28 17:27:00', '2018-02-28 17:28:00', '2018-02-28 17:29:00', '2018-02-28 17:30:00', '2018-02-28 17:31:00', '2018-02-28 17:32:00', '2018-02-28 17:33:00', '2018-02-28 17:34:00'], dtype='datetime64[ns]', name='date', length=995, freq='T') But if I just simply try to convert it, the format changes. &gt;&gt;&gt; np.array( ohlc.index ) array(['2018-02-28T01:00:00.000000000', '2018-02-28T01:01:00.000000000', '2018-02-28T01:02:00.000000000', '2018-02-28T01:03:00.000000000', '2018-02-28T01:04:00.000000000', '2018-02-28T01:05:00.000000000', ... '2018-02-28T17:30:00.000000000', '2018-02-28T17:31:00.000000000', '2018-02-28T17:32:00.000000000', '2018-02-28T17:33:00.000000000', '2018-02-28T17:34:00.000000000'], dtype='datetime64[ns]') It seems 2018-02-28 01:00:00 and 2018-02-28T01:00:00.000000000 are not the same. How can I keep the format?
possible better answer: http://stackoverflow.com/a/49084003
has answer: http://stackoverflow.com/a/49084003
has comment: http://stackoverflow.com/comment/85172272
has comment: http://stackoverflow.com/comment/85173706
has comment: http://stackoverflow.com/comment/85172674
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49083541
downvote count: 0
favorite count: 0
tagged with: python
has title: Why does the format change when converting DatetimeIndex to np.array?
has comment: http://stackoverflow.com/comment/85172694
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13703720
accepted answer: http://stackoverflow.com/a/49083541
has comment: http://stackoverflow.com/comment/85175805
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85173244
type: Question
tagged with: numpy

http://stackoverflow.com/a/48995418
answers question: http://stackoverflow.com/q/48995023
score: 0
type: Answer
has body: If I understand your problem correctly, this is one solution: import pandas as pd, numpy as np df = pd.DataFrame([[1, np.nan, 'A', 10], [2, np.nan, 'B', 20], [3, np.nan, 'C', 30], [np.nan, 15, 'A', np.nan], [np.nan, 10, 'B', np.nan], [np.nan, 20, 'C', np.nan]], columns = ['Item', 'Price', 'Material', 'MaterialSum']) # Item Price Material MaterialSum # 0 1.0 NaN A 10.0 # 1 2.0 NaN B 20.0 # 2 3.0 NaN C 30.0 # 3 NaN 15.0 A NaN # 4 NaN 10.0 B NaN # 5 NaN 20.0 C NaN prices = df[df['Item'].isnull()].set_index('Material')['Price'] df['Cost'] = df['Material'].map(prices) * df['MaterialSum'] # Item Price Material MaterialSum Cost # 0 1.0 NaN A 10.0 150.0 # 1 2.0 NaN B 20.0 200.0 # 2 3.0 NaN C 30.0 600.0 # 3 NaN 15.0 A NaN NaN # 4 NaN 10.0 B NaN NaN # 5 NaN 20.0 C NaN NaN

http://stackoverflow.com/q/48974059
duplicate of: http://stackoverflow.com/q/14241133
answer count: 1
has comment: http://stackoverflow.com/comment/84953054
has answer: http://stackoverflow.com/a/48974189
has body: judges = ["judge 1", "judge 2", "judge 3", "judge 4", "judge 5",] couples = [1, 2, 3, 4, 5] x=0 j=0 done = False def judging(j, x, judges, couples,): couplescores1 = [] couplescores2 = [] couplescores3 = [] couplescores4 = [] couplescores5 = [] print ("scoreing couple",couples[j],) for i in couples: print("score couples" ,couples[j],judges[x],"out of 30 minimum 1") score = int(input( ": ")) couplescores[j].append(score) x=x+1 j=j+1 if j == 5: done = True else: x = 0 judging(j, x, judges, couples,) judging(j, x, judges, couples,) so that is my code and what i need help with is the append what i want is for the [j] in it to be counted as its integer so that the first time round it saves score into couplescores1 then without needing extra long code next round couplescores2 and ect i do know i an use if and elif statments for example if j == 0: couplescores1.append(score) elif j == 1: couplescores2.append(score) ect but i want to avoid it if i can thank you
tagged with: python
type: AnsweredQuestion
has title: Changing a list name variable in a for loop
accepted answer: http://stackoverflow.com/a/48974189
type: Question
duplicate of: http://stackoverflow.com/q/1373164
duplicate of: http://stackoverflow.com/q/4010840
has comment: http://stackoverflow.com/comment/84953017
score: 0

http://stackoverflow.com/a/49098070
score: 1
accepted answer of: http://stackoverflow.com/q/49092454
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49092454
has body: I was able to answer my question with the help of the comments. (Thanks!) My code now extracts .tex files from multiple .gz files that are inside a single .tar file, without unzipping/saving each .gz file to the computer. def extractFile(filename): tar = tarfile.open(filename) for subfile in tar.getmembers(): # Open subfile only if .gz if subfile.name.endswith('.gz'): try: gz = tar.extractfile(subfile) gz = tarfile.open(fileobj=gz) # Extract file from .gz into 'latex' subfolder only if .tex for subsubfile in gz.getmembers(): if subsubfile.name.endswith('.tex'): gz.extract(subsubfile, path='latex') except tarfile.ReadError: # Add subfile name to error log with open('error_log.txt', 'a') as log: log.write(subfile.name + '\n')
upvote count: 1

http://stackoverflow.com/comment/85220405
comment on: http://stackoverflow.com/q/49106837
has text: it works. thanks. also how do i take the date only? when trying 'Date',lambda x: x.dt.date.max() I am getting an error AttributeError: 'SeriesGroupBy' object has no attribute 'Date'
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/48979103
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48979118
duplicate of: http://stackoverflow.com/q/75666408
linked to: http://stackoverflow.com/q/3840784
has answer: http://stackoverflow.com/a/48979124
has title: Why do I get this error (NoneType)?
answer count: 2
accepted answer: http://stackoverflow.com/a/48979124
score: 0
duplicate of: http://stackoverflow.com/q/11205254
tagged with: python
favorite count: 0
has body: I know there are help forums on the NoneType error. But for the love of me I can't save my coding. counter=0 agesList=[] for line in database: newlist=database[counter].split(',') counter=counter+1 age=newlist[-2] agesList=agesList.append(age) #print(age) print(agesList) I have a document of comma separated values, and I split them all into their own list and take out the number I'm looking for which sits in the second to last positon of the newlist. If I print age I get all of the correct ages 1 by 1 throughout the loop. But if I try to append all of the age numbers onto my blank list I get this error: agesList=agesList.append(age) AttributeError: 'NoneType' object has no attribute 'append' Can I please get some help on why I get this error? Thanks
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/48979118

http://stackoverflow.com/q/48997695
type: AnsweredQuestion
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/48997734
has title: Creating Python dictionary of classes
has comment: http://stackoverflow.com/comment/85000856
tagged with: python-2.7
answer count: 1
has answer: http://stackoverflow.com/a/48997734
has body: I'm sure there's an answer to this question somewhere on SO, but I can't seem to find the right search terms to ferret it out. Source file layout: ./mycode.py ./protocols/__init__py (empty) ./protocols/prot1.py ./protocols/prot2.py ./protocols/prot3.py ./protocols/prot1.py: class Prot1: @classmethod def getAddress(cls, data): return f(data) Similar for Prot2 and Prot3, but the return value is calculated differently in each class. mycode.py: import protocols self.protocolClasses = { "1" : Prot1, "2" : Prot2, "3" : Prot3 } protocol = "1" # just for the example f = self.protocolClasses[protocol].getAddress(somedata) That seems right to me, but Python gives an error: NameError: global name 'Prot1' is not defined The line number referenced is: "1" : Prot1, What am I missing? Edit: If I use the following syntax: "1" : protocols.prot1.Prot1, I get: AttributeError: 'module' object has no attribute 'prot1' If I use: "1" : protocols.Prot1, I get: AttributeError: 'module' object has no attribute 'Prot1'
tagged with: python
has comment: http://stackoverflow.com/comment/85000910

http://stackoverflow.com/comment/85203522
score: 1
has text: Yes that is exactly what normalization does.
type: Comment
comment on: http://stackoverflow.com/q/49098713
type: QuestionComment

http://stackoverflow.com/a/49096668
type: Answer
score: 6
upvote count: 7
downvote count: 1
answers question: http://stackoverflow.com/q/49096599
has body: You can obtain the truthiness of a value, by using the bool(..) function: &gt;&gt;&gt; bool('') False &gt;&gt;&gt; bool('foo') True &gt;&gt;&gt; bool(1) True &gt;&gt;&gt; bool(None) False In an if statement, the truthiness is calculated implicitly. You can use the not keyword, to invert the truthiness. For example: &gt;&gt;&gt; not '' True &gt;&gt;&gt; not 'foo' False &gt;&gt;&gt; not 1 False &gt;&gt;&gt; not None True

http://stackoverflow.com/comment/85184573
type: Comment
has text: But keys in d are not those values' position in that list of lists
score: 0
comment on: http://stackoverflow.com/q/49089435
type: QuestionComment

http://stackoverflow.com/q/49021811
tagged with: django
has answer: http://stackoverflow.com/a/49021876
has title: Django template does not detect instance of model
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49021876
has comment: http://stackoverflow.com/comment/85048736
type: Question
has comment: http://stackoverflow.com/comment/85048767
has body: I added a Languages model to models.py: class Languages(models.Model): language = models.CharField(max_length=20,blank=False) level = models.CharField(max_length=30,blank=False) ordering = models.IntegerField(default=1) class Meta: order = ['order','id'] def __unicode__(self): return ''.join([self.language, '-', self.level]) called python3 manage.py makemigrations && python3 manage.py migrate and created a couple of instances: python3 manage.py shell In [1]: from resume.models import Languages In [2]: Languages.objects.all() Out[2]: <QuerySet [<Languages: Languages object (5)>, <Languages: Languages object (6)>]> In [3]: Languages.objects.get(id=5).__dict__ Out[3]: {'_state': <django.db.models.base.ModelState at 0x7f0f21bb7668>, 'id': 5, 'language': 'English', 'level': 'professional', 'ordering': 1} however my template does not detect any language: Languages {% for lan in languages %} {{ lan.language }} {{ lan.level }} {% endfor %} On the html of the site I see Languages but not the rest. Other models work fine. As said, this is the latest model I added to models.py. I also called flush: python3 manage.py flush This is part of showmigrations: python3 manage.py showmigrations | grep -i langua [X] 0016_remove_language_personalinfo [X] 0018_delete_language [X] 0019_languages How to troubleshoot this problem?
score: 0
answer count: 1
tagged with: python

http://stackoverflow.com/comment/85229863
comment on: http://stackoverflow.com/q/49112001
score: 0
type: Comment
type: QuestionComment
has text: thanks you guys, that fixed the issue

http://stackoverflow.com/comment/85113449
comment on: http://stackoverflow.com/q/49053793
has text: Both your comprehension and explicit loop use the same name `states_`; I don't see how one could produce the given `NameError` but the other not.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49604585
type: Answer
answers question: http://stackoverflow.com/q/49035644
has body: The pattern would typically be: convert your data into a spark DataFrame df = spark.read.csv('./neg_tweets.txt') you can use train/test split here: df.randomSplit([0.8, 0.2]) find a suitable model: if naive bayes works for you it will look somethig like this import org.apache.spark.mllib.classification.{NaiveBayes, NaiveBayesModel} Otherwise, for sentiment analysis there may not be one precisely built in to spark.ml/mllib. You may need to look for external projects. Iterate, iterate on the model and tuning parameters.. You can run an evaluator for the metrics you decide are important to your problem. Some examples for binary classification problems are here: https://spark.apache.org/docs/2.2.0/mllib-evaluation-metrics.html#binary-classification metrics = BinaryClassificationMetrics(predictionAndLabels)
score: 0

http://stackoverflow.com/a/49293887
upvote count: 9
score: 9
downvote count: 0
answers question: http://stackoverflow.com/q/49073217
type: Answer
has body: As mentioned by others, your code is iterating through the entire input before attempting to write the result. I wanted to suggest how one might do this with a streaming approach: from Bio import SeqIO from Bio.SeqRecord import SeqRecord with open("AAseq.fasta", 'w') as aa_fa: for dna_record in SeqIO.parse("dnaseq.fasta", 'fasta'): # use both fwd and rev sequences dna_seqs = [dna_record.seq, dna_record.seq.reverse_complement()] # generate all translation frames aa_seqs = (s[i:].translate(to_stop=True) for i in range(3) for s in dna_seqs) # select the longest one max_aa = max(aa_seqs, key=len) # write new record aa_record = SeqRecord(max_aa, id=dna_record.id, description="translated sequence") SeqIO.write(aa_record, aa_fa, 'fasta') The main improvements here are: Individual records are translated and outputted in each iteration, minimizing memory usage. Adds support for reverse complements. Translated frames are created through a generator comprehension, and only the longest length one is stored. Avoids if...elif...else structures by instead using max with a key.

http://stackoverflow.com/comment/85123169
score: 1
has text: Ok, now I get the issue. I editet and restored my answer (which missed the point initially).
comment on: http://stackoverflow.com/q/49058510
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85041075
score: 0
has text: I just checked with a different MPI (`mpich/3.1.4/intel` instead of `openmpi`) it works! Thanks anyways for the help
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48999637

http://stackoverflow.com/q/49020654
answer count: 0
tagged with: numerical-analysis
has comment: http://stackoverflow.com/comment/85046959
type: Question
tagged with: numpy
tagged with: gaussian
has body: Having trouble with this problem. I can't tell what's wrong. It seems a bit too complicated and I'm getting errors. I actually did this with pseudocode from wikipedia. import numpy as np import math A = [[5,1,0,2,1],[0,4,0,1,2],[1,1,4,1,1],[0,1,2,6,0],[0,0,1,2,4]] b = [[1],[2],[3],[4],[5]] def swap_rows(A,i,j): temp = A[i] A[i]=A[j] A[j] = temp return(A) def Gauss(A): n = len(A) for k in range(n): myList = [] for p in range(k,n): myList.append(abs(A[p][k])) i_max = np.argmax(myList) if A[i_max][k] == 0: print('Error: Matrix is singular') return A = swap_rows(a,k,i_max) for i in range(k,n): f = (A[i][k])/(A[k][k]) for j in range(k,n): A[i][j] = A[i][j]-A[k][j]*f A[i][k] = 0 return(A) Gauss(A)
score: 0
has comment: http://stackoverflow.com/comment/85046599
has title: Gaussian Elimination in Python with Pivoting
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48993770
has comment: http://stackoverflow.com/comment/84992903
has body: You can use explode() function - it flattens the map by creating two additional columns - key and value for each entry: &gt;&gt;&gt; df.printSchema() root |-- event: string (nullable = true) |-- properties: map (nullable = true) | |-- key: string | |-- value: string (valueContainsNull = true) &gt;&gt;&gt; df.select('event', explode('properties')).printSchema() root |-- event: string (nullable = true) |-- key: string (nullable = false) |-- value: string (nullable = true) You can use pivot if you have a column with unique value you can group by. For example: df.withColumn('id', monotonically_increasing_id()) \ .select('id', 'event', explode('properties')) \ .groupBy('id', 'event').pivot('key').agg(first('value'))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48993176
accepted answer of: http://stackoverflow.com/q/48993176
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84993120
score: 4

http://stackoverflow.com/comment/85041103
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49017861
has text: Of course I missed that. Thanks, @Barmar

http://stackoverflow.com/q/49058472
tagged with: python
has comment: http://stackoverflow.com/comment/85121940
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/49058504
has comment: http://stackoverflow.com/comment/85123464
has body: Suppose i have 3 Numpy arrays containing floats with the following names: one two three. Is it possible to refer to them in a for-loop in the following manner: list=one two three for arr in list: arr=arr[2,1]+1 The above example obviously does not work but i was wondering if there is a way to do this?
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49058581
accepted answer: http://stackoverflow.com/a/49058581
score: 1
has comment: http://stackoverflow.com/comment/85121977
tagged with: numpy
answer count: 2
tagged with: for-loop
upvote count: 1
possible better answer: http://stackoverflow.com/a/49058504
has comment: http://stackoverflow.com/comment/85123191
favorite count: 0
has title: Referring to arrays in a for-loop

http://stackoverflow.com/comment/84938166
score: 0
type: Comment
type: QuestionComment
has text: ok, i would try to fit the `__init__.py` to the format as in documentation http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html , also try to remove the crap you inserted there, but if it is relevant provide what those files contains... and maybe i would try to do absolute imports rather then relative
comment on: http://stackoverflow.com/q/48963659

http://stackoverflow.com/comment/85151485
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49071064
has text: Could you be more precise, please?

http://stackoverflow.com/comment/85173797
type: QuestionComment
comment on: http://stackoverflow.com/q/49083939
type: Comment
has text: Not understand your issue, the program just works, you write `test_showw`, and the board echo back it, what's wrong?
score: 0

http://stackoverflow.com/q/49084856
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49106042
type: Question
answer count: 1
has title: Django REST Framework - Issues with extending the user model using signals
tagged with: rest
score: 0
has body: I am new to Django and want to extend my user model with OneToOne field (seems its mostly recommended), also I have a ManyToManyField which is mandatory. Below is my models.py : from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField from django.db.models.signals import post_save from django.dispatch import receiver class Config_Table(models.Model): entity_name = models.TextField(primary_key=True) category = models.TextField() description = models.TextField(blank=True,default='') class Profile(models.Model): "The Profile of a user with details are stored in this model." user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=11) # The default username is phone number (Ver. 1.0) phone_number = models.TextField(max_length=11,default=user) avatar = models.ImageField(default='../Static/1.jpeg') GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ) gender = models.CharField(max_length=1,choices=GENDER_CHOICES) city = models.TextField(max_length=25) description = models.TextField(max_length=2000, blank=True, default='') interests = models.ManyToManyField(Config_Table) date_of_birth = models.DateField(auto_now_add=True) USER_TYPES = ( ('User','Normal User'), ('Leader','Tour Leader'), ('Admin','Administrator'), ) user_type = models.TextField(choices=USER_TYPES, default='User') join_date = models.DateTimeField(auto_now_add=True) official_docs = models.ImageField(default='../Static/1.jpeg') group_name = models.TextField(blank=True,default='') debit_card_number = models.IntegerField(blank=True, default=0) MUSIC_CHOICES = ( ('Rock','Rock Music'), ('Trad','Traditional Music'), ('Elec','Electronic Music'), ('Clas','Classical Music') ) favorite_music = ArrayField(models.TextField(null=True,default=''),size=2) Using shell, I can successfully create a user and assign a profile like below. The table "Config_table" has been populated with some initial data : &gt;&gt;&gt; user = User.objects.create_user(…
has answer: http://stackoverflow.com/a/49106042
tagged with: django
tagged with: python

http://stackoverflow.com/q/48966465
has comment: http://stackoverflow.com/comment/84941137
has title: BGR to HSV conversion doesn't work with OpenCV Python
score: 0
linked to: http://stackoverflow.com/q/48528754
tagged with: python
has body: I'm trying to detect color-range using OpenCV Python. When I use RGB colors on HSV converted image, it works fine. But when I change lower and upper colors to HSV, it cannot detect colors. Here is a bit dirty code. lower and upper variables are BGR and I try to convert them below with hsv_lower and hsv_upper but when passed them to cv2.inRange() function, it results with empty black mask/screen. image = cv2.imread('images/circles.jpg', 1) hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) green = np.uint8([[[0, 255, 0]]]) hsv_green = cv2.cvtColor(green, cv2.COLOR_BGR2HSV) print hsv_green lower = np.array([0, 100, 100], np.uint8); upper = np.array([10, 255, 255], np.uint8); lowerz = np.uint8([[[0, 100, 100]]]); hsv_lower = cv2.cvtColor(lowerz, cv2.COLOR_BGR2HSV) print hsv_lower upperz = np.uint8([[[10, 255, 255]]]); hsv_upper = cv2.cvtColor(upperz, cv2.COLOR_BGR2HSV) print hsv_upper # Threshold the HSV image to get only blue colors mask = cv2.inRange(hsv, hsv_lower, hsv_upper) output = cv2.bitwise_and(image, image, mask=mask) cv2.imshow("images", np.hstack([image, output])) cv2.imshow('frame', image) cv2.imshow('mask', mask) cv2.imshow('res', output) #cv2.waitKey(0) k = cv2.waitKey(0) &amp; 0xFF if k == 27: cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/84944050
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84941179
tagged with: computer-vision
type: Question
tagged with: opencv
tagged with: opencv3.0
tagged with: image-processing

http://stackoverflow.com/q/49059296
tagged with: pandas-groupby
tagged with: pandas
has body: Currently, I have two dataframes where I am merging on 'KEY'. My first dataframe contains a KEY and the original price of a product. My second dataframe collects information for each time a person makes a payment. I need to create a final calculated column in df1 which shows the remaining balance. The remaining balance is calculated by subtracting payment_price from the original_price. The only caveat is that only certain price_codes reflect a payment (13, 14 and 15). I'm not sure if the best approach utilizes merges or if I can simply refer to another df without having to merge (the latter approach would seem more ideal since both dfs have 500,000,000+ rows), but I can't find much content on this specific scenario. df1 = pd.DataFrame({'KEY': ['100000555', '100000009','100000034','100000035', '100000036'], 'original_price': [1205.20,1253.25,1852.15,1452.36,1653.21], 'area': [12, 13, 12,12,12]}) df2 = pd.DataFrame({'KEY': ['100000555', '100000009', '100000009', '100000009', '100000009','100000034','100000034', '100000034'], 'payment_price': [134.04, 453.43, 422.32,23.23,10.43,10.47,243.09,23.45], 'Price_code': ['13', '13', '14','15','16','13','14','15']}) df1: KEY area original_price 0 100000555 12 1205.20 1 100000009 13 1253.25 2 100000034 12 1852.15 3 100000035 12 1452.36 4 100000036 12 1653.21 df2: KEY payment_price Price_code 0 100000555 134.04 13 1 100000009 453.43 13 2 100000009 422.32 14 3 100000009 23.23 15 4 100000009 10.43 16 5 100000034 10.47 13 6 100000034 243.09 14 7 100000034 23.45 15 I need to create a calculation where I need to subtract any payment_price from df2 if they match the key and have price_code values of 13,14, or 15. final result KEY area original_price calculated_price 0 100000555 12 1205.20 1071.16 # (1205.20 - 134.04) 1 100000009 13 1253.25 354.27 # (1253.25 - 453.43 - 422.32 - 23.23) 2 100000034 12 1852.15 1575.14 # (1852.15 - 10.47 - 243.09 - 23.45) 3 100000035 12 1452.36 1452.36 4 100000036 12 1653.21 1653.21 My initial inclination w…
favorite count: 0
has title: Using two dataframes to calculate final value pandas
tagged with: python
tagged with: merge
possible better answer: http://stackoverflow.com/a/49061536
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49061536
type: Question
has answer: http://stackoverflow.com/a/49061590
accepted answer: http://stackoverflow.com/a/49061590
tagged with: dataframe
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/84964496
score: 3
has text: Can you please provide an example DF and expected output?
type: QuestionComment
comment on: http://stackoverflow.com/q/48979604
type: Comment

http://stackoverflow.com/q/48968918
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48969119
accepted answer: http://stackoverflow.com/a/48969119
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: urllib3
has title: urlib usage from Python 3
tagged with: python
upvote count: 3
score: 1
downvote count: 2
has body: I get the following error: TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. When making the call below import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse import json chemcalcURL = 'http://www.chemcalc.org/chemcalc/em' # Define a molecular formula string mfRange = 'C0-100H0-100N0-10O0-10' # target mass mass = 300 # Define the parameters and send them to Chemcalc # other options (mass tolerance, unsaturation, etc. params = {'mfRange': mfRange,'monoisotopicMass': mass} response = urllib.request.urlopen(chemcalcURL, urllib.parse.urlencode(params)) # Read the output and convert it from JSON into a Python dictionary jsondata = response.read() data = json.loads(jsondata) print(data)
type: Question

http://stackoverflow.com/q/49066351
has comment: http://stackoverflow.com/comment/85140950
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85138979
tagged with: a-star
has title: A star implementation in ROS
type: Question
linked to: http://stackoverflow.com/q/43310743
has comment: http://stackoverflow.com/comment/85139795
tagged with: ros
score: 0
has comment: http://stackoverflow.com/comment/85137874
has body: i have been trying to implement A star in python,something similar to Robotic Path Planning - A* (Star). I wanted to ask how does one get the vector (x,y) coordinates of each grid of cell.I have been trying to do something with occupancy grid data but although it says its 2D,its a 1D dimensional tuple with (-1,0,100) depending on if its empty or not. rospy.wait_for_message('/map',OccupancyGrid) rospy.Subscriber('/map',OccupancyGrid,self.update_map) def update_map(self,msg3): self.data=msg3.data The documentation for this msg is https://mirror.umd.edu/roswiki/doc/diamondback/api/nav_msgs/html/msg/OccupancyGrid.html but i want to get (x,y) coordinates so i can create a node class for each cell something like this: class node(): def __init__(self): int x, int y, double G double F, double H, node *parent How do i get x,y coordinates for each of them so i can create a node out of each cell? P.S. my origin is (-10,-10,0) and i believe it makes a difference in how you calculate.Thanks

http://stackoverflow.com/comment/85035697
comment on: http://stackoverflow.com/q/49015210
score: 0
type: Comment
type: QuestionComment
has text: ohh yes .. well i have tried that but it shows no output. is there any path argument error in function or anything else...? or should i use something other than print() in py...?

http://stackoverflow.com/q/49100930
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85207162
favorite count: 0
has body: I did not get this question right. The function read_words turns a text file with a bunch of names in new lines into a list and it works. def read_words(words_file): """ (file open for reading) -&gt; list of str Return a list of all words (with newlines removed) from open file words_file. Precondition: Each line of the file contains a word in uppercase characters from the standard English alphabet. """ words_list = [] words = words_file.readlines() for i in range(len(words)): new_word = words[i] for char in '\n': new_word = new_word.replace(char,'') words_list.append(new_word) return words_list the problem arises when I try to get a list of lists def read_board(board_file): """ (file open for reading) -&gt; list of list of str Return a board read from open file board_file. The board file will contain one row of the board per line. Newlines are not included in the board. """ board_list = [] row_list = [] rows = read_words(board_file) for i in range(len(rows)): for char in rows[i]: row_list.append(char) board_list.append(row_list) return board_list the goal is to turn a text file of the type: ABCD EFGH into [['A','B','C','D'],['E','F','G','H']] I have already tried playing around with the indices for board_list.append(row_list) call without luck. How can I get this to work?
tagged with: python
tagged with: nested-lists
downvote count: 0
score: 2
type: AnsweredQuestion
has title: Adding lists to a new list
has answer: http://stackoverflow.com/a/49100985
accepted answer: http://stackoverflow.com/a/49100985

http://stackoverflow.com/comment/85216617
score: 0
type: Comment
type: QuestionComment
has text: yes python file inside a django app
comment on: http://stackoverflow.com/q/49105821

http://stackoverflow.com/a/49009633
has body: You may want to Google for python parser generator. A parser generator is a library that helps developers create parsers for any kind of formula or language (technically, any "grammar") without doing all the work from scratch. You may have to do some reading to understand what type of grammar a chemical formula adheres to. An interesting overview for Python is this.
upvote count: 1
has comment: http://stackoverflow.com/comment/85055177
answers question: http://stackoverflow.com/q/49009035
has comment: http://stackoverflow.com/comment/85023631
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/85069346
type: QuestionComment
has text: At each step, update the distance to be the sum of travel time + wait time, where wait time is determined by (cumulative time traveled up to that point) mod (time between departures)? Would also have to take into account some offset if departures don't all start exactly at 12:00
comment on: http://stackoverflow.com/q/49031935
score: 1
type: Comment

http://stackoverflow.com/comment/85139225
type: QuestionComment
comment on: http://stackoverflow.com/q/49067081
score: 0
has text: How many arguments does `write()` take? And how many did you pass? Hint: concatenate your strings before writing
type: Comment

http://stackoverflow.com/a/55473570
type: Answer
answers question: http://stackoverflow.com/q/49082416
has body: Look at this example: and refer--> https://chillyfacts.com/send-soap-request-and-read-xml-response-from-php-page/#respond from zeep import Client cl = Client('http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx?wsdl') request_data = { 'countryCode': 'Scotland', 'year': 2018} print(cl.service.GetHolidaysForYear(**request_data))
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/48997442
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85001010
accepted answer of: http://stackoverflow.com/q/48997213
answers question: http://stackoverflow.com/q/48997213
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85001060
upvote count: 2
has body: Try to read the file as UTF-8.

http://stackoverflow.com/q/49032998
has body: It is normally possible to install miniconda on a remote server and run a command like conda install -c pandas bottleneck However, there are two things that are unfavorable to this. I need to install roughly 20 packages on many remote servers. Even when running these commands I get a CondaHTTPError: HTTP 000 CONNECTION FAILED for url &lt;https://conda.anaconda.org/pandas/linux-64/repodata.json&gt; because of the remote locations have limited internet access I assume. So I was wondering how I could set up a sh file to install a version of miniconda with all the packages needed (lightweight version of anaconda) that I can rsync to other servers. Similar to how you run bash Latest-Version-anaconda3-x86_64.sh which installs python and packages. Let me know if clarification is needed. Edit: I should add that anaconda does have all the needed packages but to rsync the installer onto these servers takes in excess of a hour
type: UnansweredQuestion
tagged with: python
tagged with: miniconda
has comment: http://stackoverflow.com/comment/85148957
tagged with: anaconda
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85071706
has comment: http://stackoverflow.com/comment/85137425
tagged with: conda
has title: Is it possible to create a custom miniconda/anaconda like installer for linux
score: 0
has comment: http://stackoverflow.com/comment/85071406
has comment: http://stackoverflow.com/comment/85147226

http://stackoverflow.com/comment/85263897
comment on: http://stackoverflow.com/a/49033290
type: Comment
has text: I have done everything that is required but I think it is my code I am failing at. I have never programmed in Python before this so I don't entirely know what I am doing. It returns holiday as true but my flow always gets an error in the invoke function block.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48972650
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has title: Python: How can i add a second "non-Nan"-condition to the limits of my quiver plot axis?
downvote count: 0
tagged with: matplotlib
type: Question
upvote count: 2
has body: I wanna set the limits of my quiver plot axes s.t. NaNs in the outer used grid do not cause my axe limits being unnecessarily long without any data points. What I got is by myself is: import numpy as np pylab.xlim(np.min(Km[np.isnan(C_diff) &lt; 0.5 ]), np.max(Km[np.isnan(C_diff) &lt; 0.5 ])) #two conditions: "np.min(Cm[np.isnan(K_diff) &lt; 0.5" on min, max (Km) are missing pylab.ylim(np.min(Cm[np.isnan(K_diff) &lt; 0.5 ]), np.max(Cm[np.isnan(K_diff) &lt; 0.5 ])) #two conditions: "np.min(Km[np.isnan(K_diff) &lt; 0.5" on min, max (Cm) are missing To further illustrate, in matlab language I wanna have: xlim([min(min(Km(real(~(isnan(K_diff))).*real(~(isnan(C_diff))) &gt; 0.5))), max(max(Km(real(~(isnan(K_diff))).*real(~(isnan(C_diff))) &gt; 0.5)))]); ylim([min(min(Cm(real(~(isnan(K_diff))).*real(~(isnan(C_diff))) &gt; 0.5))), max(max(Cm(real(~(isnan(K_diff))).*real(~(isnan(C_diff))) &gt; 0.5)))]); Would be great to get an answer! Thanks in advance! :) Tobias
has answer: http://stackoverflow.com/a/48973879
accepted answer: http://stackoverflow.com/a/48973879
tagged with: limits
answer count: 1
tagged with: nan

http://stackoverflow.com/comment/119950761
score: 0
comment on: http://stackoverflow.com/a/49039535
type: Comment
has text: After doing `pip install --editable .` if we made a change on any file under the imported folder, should we do `pip install --editable .` again to fetch the new updates?
type: AnswerComment

http://stackoverflow.com/q/49113148
tagged with: flask
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
tagged with: flask-socketio
type: Question
has body: I am developing a Flask application with Flask-SocketIO library to real time communication between a server background task and clients. I need to access to my database inside the background task and I don't know how to achieve it as no application context is initialized. My code is: @socketio.on('connect', namespace='/rt/notifications/') def start_notifications_thread(): global thread with thread_lock: if thread is None: thread = socketio.start_background_task(target=notifications_job) def notifications_job(): last_alert_id = None while True: socketio.sleep(60) last_id = Alert.get_last_alert_id() # Flask-SQLAlchemy model if last_alert_id is not None and last_id != last_alert_id: socketio.emit('new_alerts', {'msg': 'New alert', 'id': last_id}, namespace='/rt/notifications/') last_alert_id = last_id
has title: Accessing to application context in flask socketio background task
has answer: http://stackoverflow.com/a/49125486
answer count: 1
downvote count: 0

awk
tag name: awk
tags question: http://stackoverflow.com/q/48967051
tags question: http://stackoverflow.com/q/49094035
type: Tag
tags question: http://stackoverflow.com/q/49055354
tags question: http://stackoverflow.com/q/48993022
tags question: http://stackoverflow.com/q/49108795

http://stackoverflow.com/a/48993366
has body: The error message points to "1":NR, which does not look like valid JSON, so it seems like a valid error. Edit: try putting all NR within quotes.
type: Answer
answers question: http://stackoverflow.com/q/48993168
score: 0

http://stackoverflow.com/comment/85062122
type: Comment
comment on: http://stackoverflow.com/a/49021793
type: AnswerComment
has text: @ajsp that is for pickle `SSLContext` object, [see this ref](https://stackoverflow.com/questions/33994158/how-to-pickle-a-ssl-sslcontext-object).
score: 0

http://stackoverflow.com/comment/84983940
type: QuestionComment
type: Comment
has text: seen https://stackoverflow.com/questions/14262433/large-data-work-flows-using-pandas ?
score: 2
comment on: http://stackoverflow.com/q/48989597

http://stackoverflow.com/comment/85075654
has text: Try changing this line from `BeautifulSoup(res.text,"lxml")` to `BeautifulSoup(res.text,"html.parser")`. Hope it will fix the issue. Btw, as it solves the issue make sure to accept it as an answer by ticking the grayed out checkmark next to my answer. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/49034662
score: 0
type: Comment

http://stackoverflow.com/q/48970538
linked to: http://stackoverflow.com/q/43624625
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: deconvolution
downvote count: 0
accepted answer: http://stackoverflow.com/a/48973304
has comment: http://stackoverflow.com/comment/84946496
tagged with: convolution
answer count: 1
has title: What defines the output tensor shape of tf.layers.conv2d_transpose?
has answer: http://stackoverflow.com/a/48973304
favorite count: 0
has body: When using tf.layers.conv2d_transpose what defines the output tensor shape? For example: if the input was 4x4x512, for the output to be 8x8x256 the filters can be given, but how are is the height and width defined? Or else is it always two times the input height and width? Thanks.
has comment: http://stackoverflow.com/comment/84946465

http://stackoverflow.com/a/49062258
type: Answer
has comment: http://stackoverflow.com/comment/85130217
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85129857
has comment: http://stackoverflow.com/comment/85129837
has comment: http://stackoverflow.com/comment/85130522
upvote count: 1
answers question: http://stackoverflow.com/q/49061953
has body: It looks like you're trying to get the size of the overlap between A and B including repeated entries? If I understand this correctly you can use Python's Counter from the collections module. A Counter takes a list and creates a mapping from each entry in the list to how often it appears. from collections import Counter def func(A, B): a = Counter(A) b = Counter(B) count = 0 for key in a: count += min(a[key], b[key]) return count This runs in O(n) time where n = max(len(A), len(B))
has comment: http://stackoverflow.com/comment/85197133

http://stackoverflow.com/comment/84957334
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48973273
has text: So have you _tried_ the fifo? like in `mkfifo a; tail -f a | bash & ` and then `echo ls >> a`? Isn't that what you are asking (first part)?

http://stackoverflow.com/comment/85063739
comment on: http://stackoverflow.com/q/49028871
has text: I have added C:\Users\Nicolai Iversen\OpenBLAS\package\bin. Still does not work..
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/126611921
type: AnswerComment
comment on: http://stackoverflow.com/a/49121508
type: Comment
score: 0
has text: This gives me an error `ValueError: Unable to determine whether fp is closed.`

gaussian
tags question: http://stackoverflow.com/q/48975480
tags question: http://stackoverflow.com/q/48996789
type: Tag
tag name: gaussian
tags question: http://stackoverflow.com/q/49020654

http://stackoverflow.com/comment/85220176
comment on: http://stackoverflow.com/q/49049044
has text: @Chris_Rands I added a script to reproduce it. Your question "what exactly is your desired output?" is very good. I have no clue. Up to now we parse the log files and assume that every line is a single log entry. I guess the current pattern is not feasible any more. What is the simplest, sane, most pythonic solution?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85227666
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49101545
type: Comment
has text: @ManishSaraswat, would you mind writing an example?

http://stackoverflow.com/a/49059172
accepted answer of: http://stackoverflow.com/q/49058713
has comment: http://stackoverflow.com/comment/85123655
has comment: http://stackoverflow.com/comment/85123982
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85123624
has comment: http://stackoverflow.com/comment/85123734
has comment: http://stackoverflow.com/comment/85123696
has body: seems like you are missing a \ - use os.path.join: from os.path import dirname, join, abspath filename = join(dirname(abspath(__file__)), 'starttext') file = open(filename, 'r') __file__ - the path to the module's source file (you can also do import requests;requests.__file__) os.path.abspath - returns the absolute filename (e.g. abspath('..') returns /home) os.path.dirname - returns the dirname of a file os.path.join - joins a file parts compatible on both linux and windows
type: Answer
answers question: http://stackoverflow.com/q/49058713
has comment: http://stackoverflow.com/comment/85124253
upvote count: 1

http://stackoverflow.com/comment/85227527
type: QuestionComment
comment on: http://stackoverflow.com/q/49111000
has text: Please provide a [mcve]. I'm afraid these incomplete chunks of code aren't enough to solve this.
score: 0
type: Comment

http://stackoverflow.com/q/49110920
type: Question
has comment: http://stackoverflow.com/comment/85227148
type: AnsweredQuestion
score: -1
has body: I have imported the nba dataset into a variable named nba. these are my classes: class Player(): def __init__(self, data_row): self.player_name = data_row[0] class team(): def __init__(self,team_name): self.team_name = team_name self.roaster = [] for x in nba: if x[3]==self.team_name: self.roaster.append(Player(x)) what i want is to store each player of a team to a team object. spurs = team("TOT") but when I run the code, I get a list of class objects as following: print(spurs.roaster) [&lt;__main__.Player at 0x2211b2d06a0&gt;, &lt;__main__.Player at 0x2211b2d06d8&gt;, &lt;__main__.Player at 0x2211b2d0630&gt;, &lt;__main__.Player at 0x2211b2d0588&gt;,] how can I retrieve the objects attribute? I have tried: spurs.roaster.player_name but it came up with an error: AttributeError: 'list' object has no attribute 'player_name'
has comment: http://stackoverflow.com/comment/85227165
tagged with: class
answer count: 2
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49111076
has comment: http://stackoverflow.com/comment/85227094
has comment: http://stackoverflow.com/comment/85226988
possible better answer: http://stackoverflow.com/a/49111084
has answer: http://stackoverflow.com/a/49111084
tagged with: python
has title: How to retrieve the class attributes from a list of class object
has comment: http://stackoverflow.com/comment/85227085
accepted answer: http://stackoverflow.com/a/49111076
downvote count: 1

http://stackoverflow.com/comment/85035825
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49014735
has text: I solved it. I didnt have my python interface to mysql set up.
score: 0

http://stackoverflow.com/a/49056406
accepted answer of: http://stackoverflow.com/q/49056343
type: Answer
has body: You are doing float-math - use integer division: A = [1,2,3,4,5,6] B = A[:len(A)//2] C = A[len(A)//2:] print(A,B,C) Output: ([1, 2, 3, 4, 5, 6], [1, 2, 3], [4, 5, 6]) Have a look at the operators here: numeric-types-int-float-complex
answers question: http://stackoverflow.com/q/49056343
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85212040
has text: tensorflow by default reserves all GPU memory for its own use. You can modify this behavior, see [here](https://stackoverflow.com/questions/34199233/how-to-prevent-tensorflow-from-allocating-the-totality-of-a-gpu-memory)
comment on: http://stackoverflow.com/q/49102528
type: Comment
type: QuestionComment
score: 1

django-views
tags question: http://stackoverflow.com/q/49009527
tags question: http://stackoverflow.com/q/49085748
tags question: http://stackoverflow.com/q/49009169
tags question: http://stackoverflow.com/q/48994545
tags question: http://stackoverflow.com/q/49098458
tag name: django-views
tags question: http://stackoverflow.com/q/49093335
type: Tag
tags question: http://stackoverflow.com/q/48982838
tags question: http://stackoverflow.com/q/48964845
tags question: http://stackoverflow.com/q/48975787
tags question: http://stackoverflow.com/q/49099308
tags question: http://stackoverflow.com/q/49023207
tags question: http://stackoverflow.com/q/49079274
tags question: http://stackoverflow.com/q/49039468
tags question: http://stackoverflow.com/q/49027544

http://stackoverflow.com/comment/85029471
type: AnswerComment
comment on: http://stackoverflow.com/a/49011626
has text: I tried doing that way. Still I am finding same error ValueError: Input 0 is incompatible with layer block1_conv1: expected ndim=4, found ndim=5
type: Comment
score: 0

http://stackoverflow.com/a/49101074
score: 0
has body: Are you running on an NVIDA GPU? If so it's possible some part of the old model is still on the GPU. Try running nvidia-smi while the slow model is running and see if anything else is using up GPU memory/resources. If that doesn't work you can also run the tensorflow timeline and compare between the slow and fast runs. More info on how to generate the timeline in Keras here: https://github.com/tensorflow/tensorflow/issues/9868 and the code I pasted below for creating the timeline was taken from that link from tensorflow.python.client import timeline # Make your keras model # ... run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() model.compile(loss='MSE', optimizer='Adam', options=run_options, run_metadata=run_metadata) # Run model in your usual way # ... trace = timeline.Timeline(step_stats=run_metadata.step_stats) with open('timeline.ctf.json', 'w') as f: f.write(trace.generate_chrome_trace_format()) For more info on the tensorflow timeline see https://stackoverflow.com/a/37774470/2826818 The timeline will allow you to see how much time each operation is taking and determine which one is causing the slow down.
type: Answer
answers question: http://stackoverflow.com/q/49100959

http://stackoverflow.com/a/49051169
has body: Use broadcasting to create the 3D mask and then assign zeros with boolean-indexing - mask = idx[...,None] &gt; np.arange(a.shape[2]) a[mask] = 0 Alternatively, we can also use NumPy builtin for outer-greater comparison to get that mask - mask = np.greater.outer(idx, np.arange(a.shape[2])) Run on given sample - In [34]: mask = idx[...,None] &gt; np.arange(a.shape[2]) In [35]: a[mask] = 0 In [36]: a Out[36]: array([[[ 0, 0, 3], [ 0, 5, 6]], [[ 7, 8, 9], [ 0, 11, 12]], [[ 0, 22, 23], [ 0, 26, 27]]])
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49050500
upvote count: 3
answers question: http://stackoverflow.com/q/49050500
score: 3

http://stackoverflow.com/q/48967305
tagged with: python
type: AnsweredQuestion
score: 0
has title: NumPy Dot Product Matrices
has answer: http://stackoverflow.com/a/48967434
type: Question
has comment: http://stackoverflow.com/comment/84941192
has body: Is there a NumPy matrix/vector function that does, [x1*y1] [x2*y2] x*y = [x3*y3] [-----] [xn*yn]
tagged with: numpy
possible better answer: http://stackoverflow.com/a/48970144
answer count: 2
has answer: http://stackoverflow.com/a/48970144
tagged with: matrix
accepted answer: http://stackoverflow.com/a/48967434
has comment: http://stackoverflow.com/comment/84940321
has comment: http://stackoverflow.com/comment/84940242

http://stackoverflow.com/q/49090514
accepted answer: http://stackoverflow.com/a/49099993
tagged with: sublimelinter
type: AnsweredQuestion
tagged with: pyflakes
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49099993
type: Question
tagged with: pycodestyle
has body: So after opening up sublime sublimelinter updated and now none of my linters work. I have looked around online and had no luck. when I updated it said that I can manually install the old version but I much rather use the newer version. I am not sure as to how to change the path to my linters. I am sure its something simple. I am new to coding so any and all help will be appreciated. thanks DPI scale: 1.25 startup, version: 3143 windows x64 channel: stable executable: /C/Program Files/Sublime Text 3/sublime_text.exe working dir: /C/Program Files/Sublime Text 3 packages path: /C/Users/Jovanny/AppData/Roaming/Sublime Text 3/Packages state path: /C/Users/Jovanny/AppData/Roaming/Sublime Text 3/Local zip path: /C/Program Files/Sublime Text 3/Packages zip path: /C/Users/Jovanny/AppData/Roaming/Sublime Text 3/Installed Packages ignored_packages: ["Vintage"] Errors parsing theme: icon_file_type is missing layer0.opacity, setting to 1.0 for backwards compatibility icon_folder is missing layer0.opacity, setting to 1.0 for backwards compatibility pre session restore time: 0.206906 font face "Menlo" could not be found, defaulting to "Consolas" startup time: 0.295906 first paint time: 0.300906 reloading plugin Default.auto_indent_tag reloading plugin Default.block reloading plugin Default.comment reloading plugin Default.convert_syntax reloading plugin Default.copy_path reloading plugin Default.delete_word reloading plugin Default.detect_indentation reloading plugin Default.duplicate_line reloading plugin Default.echo reloading plugin Default.exec reloading plugin Default.fold reloading plugin Default.font reloading plugin Default.goto_line reloading plugin Default.history_list reloading plugin Default.indentation reloading plugin Default.install_package_control reloading plugin Default.kill_ring reloading plugin Default.mark reloading plugin Default.new_templates reloading plugin Default.open_context_url reloading plugin Default.open_in_browser reloading plugin Default.pane relo…
score: 1
tagged with: sublimetext3
has title: Sublimelinter 4.0.2 new update can no longer find any of my linters
upvote count: 1
tagged with: python
answer count: 1

http://stackoverflow.com/q/49098057
upvote count: 3
type: Question
tagged with: discord.py
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/67886313
has body: Say I want to make a bot with a "poke" feature (aka sends a pm to a user saying "Boop" when someone says "!poke @user#0000"), how would I do this? It works perfectly when I do this: @bot.command(pass_context=True) async def poke(ctx, message): await client.send_message(ctx.message.author, 'boop') but only if I want to poke the author of the message. I want to poke whoever's being @'d. I know the discord.py documents say I can use this: start_private_message(user) but I don't know what to put in place of user.
has answer: http://stackoverflow.com/a/49098076
tagged with: discord
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to make a discord.py bot private/direct message someone who's not the author?
score: 3

http://stackoverflow.com/a/49049657
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49049535
type: AcceptedAnswer
downvote count: 0
has body: As @UdayrajDeshmukh said, you can use the transpose method (which, despite the name that evokes the "transpose" operator in linear algebra, is better understood as "permuting the axes"): &gt;&gt;&gt; t = a.transpose(1, 0, 2) &gt;&gt;&gt; t array([[[ 1, 2], [ 5, 6], [ 9, 10]], [[ 3, 4], [ 7, 8], [11, 12]]]) The newly created object t is a shallow array looking into a's data with a different permutation of indices. To replicate your own example, you need to copy it, e.g. t = a.transpose(1, 0, 2).copy()
type: Answer
answers question: http://stackoverflow.com/q/49049535

http://stackoverflow.com/comment/85041792
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49018026
has text: @HenryH yes I imported the models as such since I am using all of them `from models import *`
score: 0

http://stackoverflow.com/a/49100830
type: Answer
score: 6
answers question: http://stackoverflow.com/q/49100697
downvote count: 0
upvote count: 6
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49100697
has body: You might be looking for a BibTeX-parser: https://bibtexparser.readthedocs.io/en/master/ Source: https://bibtexparser.readthedocs.io/en/master/tutorial.html#step-0-vocabulary Input/Create bibtex file: bibtex = """@ARTICLE{Cesar2013, author = {Jean César}, title = {An amazing title}, year = {2013}, month = jan, volume = {12}, pages = {12--23}, journal = {Nice Journal}, abstract = {This is an abstract. This line should be long enough to test multilines...}, comments = {A comment}, keywords = {keyword1, keyword2} } """ with open('bibtex.bib', 'w') as bibfile: bibfile.write(bibtex) Parse it: import bibtexparser with open('bibtex.bib') as bibtex_file: bib_database = bibtexparser.load(bibtex_file) print(bib_database.entries) Output: [{'journal': 'Nice Journal', 'comments': 'A comment', 'pages': '12--23', 'month': 'jan', 'abstract': 'This is an abstract. This line should be long enough to test\nmultilines...', 'title': 'An amazing title', 'year': '2013', 'volume': '12', 'ID': 'Cesar2013', 'author': 'Jean César', 'keyword': 'keyword1, keyword2', 'ENTRYTYPE': 'article'}]

http://stackoverflow.com/comment/85232949
score: 1
type: Comment
type: QuestionComment
has text: I am doing that.
comment on: http://stackoverflow.com/q/49113933

http://stackoverflow.com/a/49006204
accepted answer of: http://stackoverflow.com/q/49005887
type: Answer
has body: Assuming I understood you correctly: lst = [np.zeros((10, 2)), np.zeros((20, 2)), np.zeros((15, 2)), np.zeros((12, 2))] result = sorted(lst, key=lambda x: x.shape[0] * x.shape[1])[-1] This sorts your list by the product of the matrix dimensions and returns the biggest of them.
answers question: http://stackoverflow.com/q/49005887
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85057459
comment on: http://stackoverflow.com/q/49025790
score: 0
type: Comment
type: QuestionComment
has text: Just a tip (which doesn't affect the answer) but instead of using chained column and row references, it's better to use `DataFrame.iloc` - as well as being arguably more readable, it sets you up better to avoid `SettingWithCopy` errors later down the line. More detail on this [best practice in the docs](https://pandas.pydata.org/pandas-docs/stable/indexing.html#why-does-assignment-fail-when-using-chained-indexing) - HTH!

http://stackoverflow.com/comment/85089873
type: Comment
has text: I also try to change the [complex conjugated](https://ocw.mit.edu/courses/mathematics/18-03sc-differential-equations-fall-2011/unit-iv-first-order-systems/matrix-methods-eigenvalues-and-normal-modes/MIT18_03SCF11_s33_7text.pdf) pairs to real ones, but it doesn't narrow the error.
type: AnswerComment
comment on: http://stackoverflow.com/a/49041867
score: 0

http://stackoverflow.com/q/48991252
has comment: http://stackoverflow.com/comment/84987312
accepted answer: http://stackoverflow.com/a/48991659
has body: I run a code that gives me the result I want but it shows at the end of this result an "IndexError: list index out of range". Here is a part of the data I have: AMI;ZFAMIEM1;NBAMI702;DSDOU904;WHD93;SAGEM_WHD93_stbmib_02.29.82;08:3E:5D:5F:7A:42;2018-01-26 12:14:35;1516965275678;/app//wakeup;\N AMI;ZFAMIEM1;NBAMI702;DSDOU904;WHD93;SAGEM_WHD93_stbmib_02.29.82;08:3E:5D:5F:7A:42;2018-01-26 12:14:35;1516965275824;/app//connect;ethernet AMI;ZFAMIEM1;NBAMI702;DSDOU904;WHD93;SAGEM_WHD93_stbmib_02.29.82;08:3E:5D:5F:7A:42;2018-01-26 12:14:35;1516965275970;/app//tv_off;\N Here is my code: ligne = data.split("\n") for i in ligne: col = i.split(";") print(col[1]) The result I am looking for and that I get with my code is: ZFAMIEM1 ZFAMIEM1 ZFAMIEM1 IndexError Traceback (most recent call last) &lt;ipython-input-53-4d9c2e4b9014&gt; in &lt;module&gt;() 5 for i in ligne: 6 col = i.split(";") --&gt; 7 print(col[1]) IndexError: list index out of range If you have any idea on how I can avoid this error, please help me. Thank you!
downvote count: 1
type: Question
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/84987328
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48991659
has comment: http://stackoverflow.com/comment/84987825
has title: Code runnig with "IndexError: list index out of range" at the end
has comment: http://stackoverflow.com/comment/84987349
tagged with: python
has comment: http://stackoverflow.com/comment/84987338
tagged with: indexing
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84987367
has comment: http://stackoverflow.com/comment/84987423

http://stackoverflow.com/comment/85008697
comment on: http://stackoverflow.com/a/49001955
score: 0
type: AnswerComment
type: Comment
has text: "premature optimization is the root of all evil in programming" is one of the best Knuth quotes I've ever heard. thanks for sharing.

http://stackoverflow.com/a/49016204
type: Answer
accepted answer of: http://stackoverflow.com/q/49015192
answers question: http://stackoverflow.com/q/49015192
has body: I've solved the issue. It was happening because I split my data into chunks in a manner that some of these chunks only had 1 category out of the possible 2, so the RandomForestClassifier would .fit() in only 1 category. I solved it using sklearn.model_selection.StratifiedKFold.
type: AcceptedAnswer
score: 0

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48969566
type: Tag
tags question: http://stackoverflow.com/q/49109987
tags question: http://stackoverflow.com/q/49102930
tags question: http://stackoverflow.com/q/49070242
tags question: http://stackoverflow.com/q/49026104
tags question: http://stackoverflow.com/q/49024296
tags question: http://stackoverflow.com/q/49114921
tags question: http://stackoverflow.com/q/49000768
tags question: http://stackoverflow.com/q/49079420
tags question: http://stackoverflow.com/q/49118619
tags question: http://stackoverflow.com/q/48984180
tags question: http://stackoverflow.com/q/49010513
tags question: http://stackoverflow.com/q/49097510
tags question: http://stackoverflow.com/q/49074246
tags question: http://stackoverflow.com/q/49021161
tag name: csv
tags question: http://stackoverflow.com/q/49052588
tags question: http://stackoverflow.com/q/49080298
tags question: http://stackoverflow.com/q/49054468
tags question: http://stackoverflow.com/q/49113109
tags question: http://stackoverflow.com/q/49117457
tags question: http://stackoverflow.com/q/49095465
tags question: http://stackoverflow.com/q/49007626
tags question: http://stackoverflow.com/q/49077684
tags question: http://stackoverflow.com/q/49112231
tags question: http://stackoverflow.com/q/49069623
tags question: http://stackoverflow.com/q/49084094
tags question: http://stackoverflow.com/q/49041110
tags question: http://stackoverflow.com/q/49103097
tags question: http://stackoverflow.com/q/49072727
tags question: http://stackoverflow.com/q/49063055
tags question: http://stackoverflow.com/q/49019176
tags question: http://stackoverflow.com/q/49097886
tags question: http://stackoverflow.com/q/49050455
tags question: http://stackoverflow.com/q/49099577
tags question: http://stackoverflow.com/q/49032045
tags question: http://stackoverflow.com/q/48994383
tags question: http://stackoverflow.com/q/48973817
tags question: http://stackoverflow.com/q/49117525
tags question: http://stackoverflow.com/q/49004624
tags question: http://stackoverflow.com/q/48971320
tags question: http://stackoverflow.com/q/49018551
tags question: http://stackoverflow.com/q/49111440
tags question: http://stackoverflow.com/q/49089566
tags question: http://stackoverflow.com/q/49059551
tags question: http://stackoverflow.com/q/48988841
tags question: http://stackoverflow.com/q/48973101
tags question: http://stackoverflow.com/q/49112642
tags question: http://stackoverflow.com/q/48968286
tags question: http://stackoverflow.com/q/49118882
tags question: http://stackoverflow.com/q/49038137
tags question: http://stackoverflow.com/q/49105693
tags question: http://stackoverflow.com/q/49044235
tags question: http://stackoverflow.com/q/49079464
tags question: http://stackoverflow.com/q/49116569
tags question: http://stackoverflow.com/q/49012156
tags question: http://stackoverflow.com/q/48971879
tags question: http://stackoverflow.com/q/49014357
tags question: http://stackoverflow.com/q/48999368
tags question: http://stackoverflow.com/q/49006807
tags question: http://stackoverflow.com/q/49029078
tags question: http://stackoverflow.com/q/49036453
tags question: http://stackoverflow.com/q/49074599
tags question: http://stackoverflow.com/q/49101815
tags question: http://stackoverflow.com/q/48974618
tags question: http://stackoverflow.com/q/49026913
tags question: http://stackoverflow.com/q/49058313
tags question: http://stackoverflow.com/q/49007929
tags question: http://stackoverflow.com/q/49017088
tags question: http://stackoverflow.com/q/48977822
tags question: http://stackoverflow.com/q/49097281
tags question: http://stackoverflow.com/q/49010709
tags question: http://stackoverflow.com/q/49039057
tags question: http://stackoverflow.com/q/49106732
tags question: http://stackoverflow.com/q/48970822
tags question: http://stackoverflow.com/q/48977607
tags question: http://stackoverflow.com/q/48974103
tags question: http://stackoverflow.com/q/48978698
tags question: http://stackoverflow.com/q/49094631

http://stackoverflow.com/q/49058361
tagged with: pandas-groupby
has body: I have a dataframe which look like this Code DIAG Time 1999-12-01 00:00:01.870 None 1999-12-01 00:00:10.870 None 2000-01-01 09:10:09.870 None 2000-01-01 09:10:10.870 None 2000-01-01 09:00:10.940 None 2000-01-01 09:00:11.160 None 2000-01-01 09:00:11.640 None 2000-01-01 09:00:12.460 None 2010-01-01 09:00:34.910 1_19_1_4_0_0 2010-01-01 09:00:35.060 3_22_4_0_0_0 2010-01-01 09:00:35.120 6_22_10_3_0_0 I want to backfill the missing data only for one hour before each data and change the label so the data should look like something like this Code DIAG Time 1999-12-01 00:00:01.870 None 1999-12-01 00:00:10.870 None 2000-01-01 09:10:09.870 1_19_1_4_0_0_H 2000-01-01 09:10:10.870 1_19_1_4_0_0_H 2000-01-01 09:00:10.940 1_19_1_4_0_0_H 2000-01-01 09:00:11.160 1_19_1_4_0_0_H 2000-01-01 09:00:11.640 1_19_1_4_0_0_H 2000-01-01 09:00:12.460 1_19_1_4_0_0_H 2010-01-01 09:00:34.910 1_19_1_4_0_0_H 2010-01-01 09:00:35.060 3_22_4_0_0_0 2010-01-01 09:00:35.120 6_22_10_3_0_0 I wrote this code and it look like this: def FillData(dff): s=dff.bfill() s.loc[s.notnull()]=s.astype('str').astype('str')+'_H' return s df=A['DIAG'].groupby(pd.Grouper(freq='H')).apply(FillData) The issue is that this is producing out put which is look like this: Code DIAG Time 1999-12-01 00:00:01.870 None 1999-12-01 00:00:10.870 None 2000-01-01 09:10:09.870 None 2000-01-01 09:10:10.870 None 2000-01-01 09:00:10.940 None 2000-01-01 09:00:11.160 None 2000-01-01 09:00:11.640 None 2000-01-01 09:00:34.460 1_19_1_4_0_0_H 2010-01-01 09:00:34.910 1_19_1_4_0_0_H 2010-01-01 09:00:35.060 3_22_4_0_0_0_H 2010-01-01 09:00:35.120 6_22_10_3_0_0_H I see two main issue one is that groupby is not grouping by H and is only grouping by minute. The other issue is that is that it is adding label(_H) to all row. my main goal is to label the data 1 hour before it happen with _H and 1 week before they happen by _W. I appreciate if any one can help me with this, I spent a lot of time on it but I cant find straight forward way to it. Thanks
tagged with: pandas
favorite count: 0
tagged with: aggregate
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 0
upvote count: 3
type: Question
has title: Filling Missing values Pandas Dataframe backward hourly/weekly
downvote count: 0
tagged with: dataframe

http://stackoverflow.com/a/49112340
has body: I am not sure what you are trying to do. But this should help: prob = np.dot(X_train,w)&gt;=0 pred = [int(i) for i in prob] z0= [1 if y_val[i,0]!=pred[i] else 0 for i in range(len(pred)) ] error = sum(z0)/len(z0)
accepted answer of: http://stackoverflow.com/q/49112031
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49112031

http://stackoverflow.com/q/48978698
has answer: http://stackoverflow.com/a/49008832
accepted answer: http://stackoverflow.com/a/49008832
has body: I have a folder with many different images (.jpg) and additionally a csv file that holds the different image names. Each row of the csv file has a different image name combination. For example, for 3 participants the combinations would look like this: images1 = ['01_2.jpg', '06_2.jpg', '08_1.jpg', '04_2.jpg', '10_1.jpg'] images2 = ['10_1.jpg', '01_2.jpg', '06_2.jpg', '08_1.jpg', '03_1.jpg'] images3 = ['06_2.jpg', '08_1.jpg', '01_2.jpg', '04_2.jpg', '10_1.jpg'] In the csv file, each element from the above lists belongs in a column. Also, images1 is in row one, images2 in row two, and images3 in row 3. The file looks the following way: list_stim.csv: 01_2.jpg, 06_2.jpg, 08_1.jpg, 04_2.jpg, 10_1.jpg 10_1.jpg, 01_2.jpg, 06_2.jpg, 08_1.jpg, 03_1.jpg 06_2.jpg, 08_1.jpg, 01_2.jpg, 04_2.jpg, 10_2.jpg My problem happens when trying to select one row randomly from the csv file (going through each of its columns in consecutive order), and matching it to each name.jpg from the images folder. Since the csv file holds the order of presentation of the images in each row, I would like the name in row n column m to be matched to the image that matches its string name (e.g. '06_2.jpg'). How can I use each item from one row from the csv file to retrieve the images from a folder and present them? Until now I have done the following: from psychopy import core, visual, gui, data, misc, event, logging from time import strftime import numpy, random import os, glob import string import csv # RETRIEVE IMAGES FROM FOLDER path = "/Users/mdc/Dropbox/UMARM/int/stim/" paintings = [] for file in os.listdir( path ) if file.lower().endswith(".jpg"): paintings.append(file) # READ ITEMS stim_order = [] # to store some list from csv (random row) f1 = open('list_stim.csv') items = csv.reader(f1, delimiter=',', quotechar='"') for row in items: stim_order.append(row)
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/85020586
has comment: http://stackoverflow.com/comment/85014741
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85020060
has comment: http://stackoverflow.com/comment/85013902
has comment: http://stackoverflow.com/comment/85020884
has title: Matching images to list in csv file
tagged with: python
has comment: http://stackoverflow.com/comment/85015347
type: AnsweredQuestion

http://stackoverflow.com/comment/85408785
type: Comment
comment on: http://stackoverflow.com/q/49021734
has text: @GrahamDumpleton To be honest, I'm not quite sure, but I don't think so. I just started modifying their example project (https://github.com/sclorg/django-ex) and since I've never had an issue with it, i've never looked into it. From what I've looked up (on your site no less), it looks like you need mod_wsgi.server installed as an application to be using it, so no. Honestly at this point I don't even know what to read up on further, so any help at all with where to go next to try to get some answers, i'm new to the whole gunicorn/wsgi running it on a server world.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85041376
score: 2
comment on: http://stackoverflow.com/q/49018060
type: Comment
type: QuestionComment
has text: My guess is that you have a version of pandas that is borking when comparing `int` to `str`. Try `df.astype(object) == 'z'`

http://stackoverflow.com/comment/91740298
has text: What I ended up just doing was using string methods to get the commands as strings in a list, print that in a cell, and copy the output into a new cell... you can use alt-dragging and find/replace to remove the quotes. I can type that into an answer if it helps but it didn't really feel like a "solution"
comment on: http://stackoverflow.com/q/49059521
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85026509
score: 0
has text: I updated it with more of the HTML. Is this better?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48999829

http://stackoverflow.com/q/49031841
linked to: http://stackoverflow.com/q/12665625
score: 8
favorite count: 0
tagged with: linux
upvote count: 8
type: UnansweredQuestion
has title: How to get stdout and stderr from a tmux session?
tagged with: python
has answer: http://stackoverflow.com/a/49067242
tagged with: subprocess
type: Question
answer count: 2
has body: I am writing a sample python program in linux system. I am using tmux to create a session and execute another script within the tmux-session. I would like to get the stdout and stderr out of the tmux session to the parent script but that somehow does not work. Code snippet: cmd = "tmux new-session -d -s 'test' '/my_dir/fibonacci.py __name:=fibonacci_0'" proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) (stdout, stderr) = proc.communicate() print(stderr) I have came across answers to use show-buffer and pipe-pane. But that did not help. Maybe I need to modify the tmux command itself.
linked to: http://stackoverflow.com/q/43013576
has answer: http://stackoverflow.com/a/49032022
tagged with: tmux
downvote count: 0

http://stackoverflow.com/a/67513215
has body: The line you're trying to execute tn, fp, fn, tp = confusion_matrix(y_true, y_predict).ravel() is valid only if you have 2 classes in output (binary classification). However, the error you get is an indicator that you have more than 2 classes (multi-class classification). In this case, there's no meaning of tn, fp, fn, tp. Instead you can visualize the confusion matrix (e.g. by using heatmap).
upvote count: 4
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/49055410

http://stackoverflow.com/comment/87113215
type: Comment
comment on: http://stackoverflow.com/a/50030705
type: AnswerComment
has text: @qqqwww, please check the updated answer with python 2.7 code
score: 0

http://stackoverflow.com/tag/2048
type: Tag
tags question: http://stackoverflow.com/q/49061757
tag name: 2048

http://stackoverflow.com/q/49007215
answer count: 3
has body: I want get the occurrence of characters in a string, I got this code: string = "Foo Fighters" def conteo(string): copia = '' for i in string: if i not in copia: copia = copia + i conteo = [0]*len(copia) for i in string: if i in copia: conteo[copia.index(i)] = conteo[copia.index(i)] + 1 out = ['0']*2*len(copia) for i in range(len(copia)): out[2*i] = copia[i] out[2*i + 1] = conteo[i] return (out) And I want return something like: ['f', 2, 'o', 2, '', 1, 'i', 1, 'g', 1, 'h', 1, 't', 1, 'e', 1, 'r', 1, 's', 1] How can I do it? Without use a python library Thank you
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49007278
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49007287
has comment: http://stackoverflow.com/comment/85018911
has answer: http://stackoverflow.com/a/49007337
type: Question
has title: Create function to count occurrence of characters in a string
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/85114107
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49054567
score: 0
has text: It's not clear yet - does the file contain a list of words? And you're trying to print "success" only if the word is in BOTH trigger and city lists?

http://stackoverflow.com/comment/112201459
type: QuestionComment
has text: Of interest: [The design and implementation of a PROLOG interpreter](https://preserve.lehigh.edu/cgi/viewcontent.cgi?article=5506&context=etd) While this is done in Pascal, many of the concepts given as examples are still relevant for any way of implementing Prolog.
score: 0
comment on: http://stackoverflow.com/q/49101342
type: Comment

http://stackoverflow.com/comment/85245094
score: 0
has text: Sorry, I don't understand what you mean. If it does not depend on the use of basemap, why is basemap used in the code at all?
comment on: http://stackoverflow.com/q/49118464
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84986413
score: 0
type: Comment
has text: The tutorial you point at is great, but the error you're getting seems to indicate something is wrong with permissions. I would suggest to go back and create a bucket without customising the policy: 1) Create a bucket, with public read access 2) Create a IAM group with full S3 access 3) Add a user to that group, generate AWS key and secret for that user 4) Use that key ID and secret in your app. You might want to ask a new question...
type: AnswerComment
comment on: http://stackoverflow.com/a/48965084

http://stackoverflow.com/comment/85424104
comment on: http://stackoverflow.com/q/49068622
type: Comment
type: QuestionComment
score: 0
has text: @VeneetReddy: a line with known endpoints is commonly called a line segment. SVG paths can be complex composite curves. For me your question still makes no sense.

http://stackoverflow.com/comment/84984000
has text: Ok. It's weird, but one year ago, I was searchng a good way to obtain PDF with pictures and `Pisa` with `html2pdf` seems to be the best tool to do that ;) I don't have any issue and it works fine. If my answer helped you, don't hesitate to vote up.
type: Comment
comment on: http://stackoverflow.com/a/48989179
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85141047
type: Comment
comment on: http://stackoverflow.com/a/49054330
score: 0
type: AnswerComment
has text: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) File "C:\Users\*****\Documents\****\*****\Inventory (new).py", line 57, in Product Calculation=info4/0.1 TypeError: unsupported operand type(s) for /: 'IntVar' and 'float' >>>

http://stackoverflow.com/comment/86225375
has text: If your question is solved, please mark the correct answer with the green tick so the thread is closed.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48992868

http://stackoverflow.com/a/49058223
type: Answer
has comment: http://stackoverflow.com/comment/85121500
accepted answer of: http://stackoverflow.com/q/49058127
answers question: http://stackoverflow.com/q/49058127
has body: In signup/forms.py Change: user=super(User,self).save(commit=False) To user = super(allusers1, self).save(commit=False) And read some articles on coding style. Like PEP-8 and Django style. It helps others (and your future self) to read and understand your code.
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49095523
has comment: http://stackoverflow.com/comment/85211519
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85258838
type: Answer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49090954
answers question: http://stackoverflow.com/q/49090954
has comment: http://stackoverflow.com/comment/85211389
score: 1
has comment: http://stackoverflow.com/comment/85277211
has body: I think it should be possible, if you can setup a Jupyter notebook locally, and enable SSH tunneling to the AWS Glue. I do see some reference sites for setting up local Jupyter notebook, enable SSH tunneling, etc, though not AWS Glue specific.
has comment: http://stackoverflow.com/comment/85198774
has comment: http://stackoverflow.com/comment/85211435
upvote count: 2

http://stackoverflow.com/comment/85255846
has text: Hey, thanks for tips! I used yield_per() method and it seemed to improve memory use. Unfortunately it seems the problem lies in writing file. That's what logging returns for me INFO:__main__:Adding product no. 228887 INFO:__main__:Adding product no. 228888 INFO:__main__:Adding product no. 228889 INFO:__main__:Saving XML to file Killed
comment on: http://stackoverflow.com/a/49107092
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49039746
type: Answer
answers question: http://stackoverflow.com/q/49038974
score: 0
has body: I guess this is an issue of a Race Condition take a look at this answer Race Condition, Hope it helps.
has comment: http://stackoverflow.com/comment/85533915
has comment: http://stackoverflow.com/comment/85360079

http://stackoverflow.com/a/49007383
upvote count: 1
answers question: http://stackoverflow.com/q/49007301
downvote count: 0
type: Answer
has body: You have 2 options: Use their API if they use one, to make http requests and obtain data and informations from their servers. Or use a python scraping / web test framework, eg scrapy or selenium, to scrap their website directly in a python program. Scrapy will be harder than selenium on this website because a lot of content is dynamic and will require custom code to trigger. Selenium should be easy to use.
has comment: http://stackoverflow.com/comment/85031153
score: 1

http://stackoverflow.com/comment/85063125
type: QuestionComment
has text: Please post a __verifiable__ example. If we cannot reproduce the problem, we cannot know what the problem is.
comment on: http://stackoverflow.com/q/49029226
score: 0
type: Comment

http://stackoverflow.com/q/49111504
has answer: http://stackoverflow.com/a/49147918
accepted answer: http://stackoverflow.com/a/49147918
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51219197
has title: AWS Lambda : Original error was: cannot import name multiarray
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/85229304
has body: Hi i deployed an application with lambda aws (using Serverless Framework). but i receive the error when i run a test START RequestId: 5bcf988a-2064-11e8-8d1e-c5a0129510f Version: $LATEST Unable to import module 'handler': 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, try `git clean -xdf` (removes all files not under version control). Otherwise reinstall numpy. Original error was: cannot import name multiarray I removed the numpy package folder multiple times and reinstalled but, still not working So do you have any solution for this problem ? for the code : import sys import os sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),'env','Lib','site-packages')) import numpy as np import pandas as pd import boto3 import csv import psycopg2 def hello(event, context): s3 = boto3.resource('s3') return "test" Thank you in advance
possible better answer: http://stackoverflow.com/a/51219197
favorite count: 0
tagged with: serverless-framework
has comment: http://stackoverflow.com/comment/85229084
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48982835
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48982698
has body: Add a tag to indicate that whether you have found the first ''', if you found that, then set the tag and add "PROTECTED" for all lines after that until you find another '''. Below is code sample: firstPosFound = False for line in infile: if line.find("'''") !=-1 and firstPosFound == False: print("PROTECTED",line.rstrip(),end = "") firstPosFound = True continue if line.find("'''") !=-1 and firstPosFound == True: print("PROTECTED",line.rstrip(),end = "") firstPosFound = False continue if firstPosFound == True: print("PROTECTED", line.rstrip(), end="")
answers question: http://stackoverflow.com/q/48982698

http://stackoverflow.com/a/48994515
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48994414
type: Answer
answers question: http://stackoverflow.com/q/48994414
score: 2
downvote count: 0
upvote count: 2
has body: You can use BeautifulSoup: from bs4 import BeautifulSoup as soup s = """ Gradient Puffy Jacket """ new_s = soup(s, 'lxml').find('h1', {'itemprop':'name'}).text Output: u'Gradient Puffy Jacket'

http://stackoverflow.com/q/49020649
upvote count: 9
has title: Python 2to3 adding extra parenthesis around functional argument
has body: I'm a bit baffled why 2to3 is bothering embracing my print arguments that are already in functional style to be wrapped in an extra set of parenthesis. For example print("\t[Warn] Can not connect {}".format(ssid)) becomes print(("\t[Warn] Can not connect {}".format(ssid))) Are these essentially conservative false positives? I'm thinking maybe the trailing ) in the format function is throwing its logic.
has answer: http://stackoverflow.com/a/55476779
tagged with: python-2to3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/55476779
favorite count: 0
tagged with: python
type: AnsweredQuestion
type: Question
score: 9

http://stackoverflow.com/a/48981240
score: 0
type: Answer
has body: first, you are getting that error because you are trying to split on Nan. You can check for nan condition as per the answer given by onepan. Second, you need to have c=float(a)/float(b) which will give you output like 0.492537 for 33:67. But if you do c=int(a)/int(b) it will give you 0.0 for 33:67. Really depends on what you want.
answers question: http://stackoverflow.com/q/48980388

http://stackoverflow.com/q/49112170
has title: Python: Time periods into 'shift' buckets
has comment: http://stackoverflow.com/comment/85229750
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85232396
downvote count: 1
has body: I have a data set that contains "sign in" and "sign out" times for users. I want to look at the full time range and say how much of the time fell into shift 1 (5:30-1:30), shift 2 (1:30-9:30) and shift 3 (9:30-5:30). Can this be done? Within this data set, there can be one person signed into multiple stations during overlapping times. I don't want to add those times together, so I'm currently just taking the min sign in and max sign out times and doing a datediff. The issue is, their shift is considered only by the sign in time. So, if a person comes in 2 minutes before their shift at 1:28, it puts their hours in shift 1 when it should be shift 2... Any ideas on how to handle this?
type: Question
upvote count: 0
answer count: 1
score: -1
tagged with: date-range
has answer: http://stackoverflow.com/a/49113653
has comment: http://stackoverflow.com/comment/85230807

http://stackoverflow.com/q/49039015
tagged with: python
type: AnsweredQuestion
has title: How does one interpret sklearn sparse matrix outputs?
has answer: http://stackoverflow.com/a/49043122
accepted answer: http://stackoverflow.com/a/49043122
type: Question
has comment: http://stackoverflow.com/comment/85188417
tagged with: scikit-learn
tagged with: sparse-matrix
score: 0
answer count: 1
has body: I am trying to produce a bigram word co-occurrence matrix, indicating how many times one word follows another in a corpus. As a test, I wrote the following (which I gathered from other SE questions): from sklearn.feature_extraction.text import CountVectorizer test_sent = ['hello', 'i', 'am', 'hello', 'i', 'dont', 'want', 'to', 'i', 'dont'] bigram_vec = CountVectorizer(ngram_range=(1,2)) X = bigram_vec.fit_transform(test_sent) Xc = (X.T * X) print Xc This should give the correct output. The matrix Xc is output like so: (0, 0) 1 (1, 1) 2 (2, 2) 2 (3, 3) 1 (4, 4) 1 I have no idea how to interpret this. I attempted to make it dense to help with my interpretation using Xc.todense(), which got this: [[1 0 0 0 0] [0 2 0 0 0] [0 0 2 0 0] [0 0 0 1 0] [0 0 0 0 1]] Neither of these give the correct word co-occurrence matrix showing one how many times row follows column. Could someone please explain how I can interpret/use the output? Why is it like that? Addition to question Here is another possible output with a different example using ngram_range=(2,2): from sklearn.feature_extraction.text import CountVectorizer test_sent = ['hello biggest awesome biggest biggest awesome today lively splendid awesome today'] bigram_vec = CountVectorizer(ngram_range=(2,2)) X = bigram_vec.fit_transform(test_sent) print bigram_vec.get_feature_names() Xc = (X.T * X) print Xc print ' ' print Xc.todense() (4, 0) 1 (2, 0) 2 (0, 0) 1 (3, 0) 1 (1, 0) 2 (7, 0) 1 (5, 0) 1 (6, 0) 1 (4, 1) 2 (2, 1) 4 (0, 1) 2 (3, 1) 2 (1, 1) 4 (7, 1) 2 (5, 1) 2 (6, 1) 2 (4, 2) 2 (2, 2) 4 (0, 2) 2 (3, 2) 2 (1, 2) 4 (7, 2) 2 (5, 2) 2 (6, 2) 2 (4, 3) 1 : : (6, 4) 1 (4, 5) 1 (2, 5) 2 (0, 5) 1 (3, 5) 1 (1, 5) 2 (7, 5) 1 (5, 5) 1 (6, 5) 1 (4, 6) 1 (2, 6) 2 (0, 6) 1 (3, 6) 1 (1, 6) 2 (7, 6) 1 (5, 6) 1 (6, 6) 1 (4, 7) 1 (2, 7) 2 (0, 7) 1 (3, 7) 1 (1, 7) 2 (7, 7) 1 (5, 7) 1 (6, 7) 1 [[1 2 2 1 1 1 1 1] [2 4 4 2 2 2 2 2] [2 4 4 2 2 2 2 2] [1 2 2 1 1 1 1 1] [1 2 2 1 1 1 1 1] [1 2 2 1 1 1 1 1] [1 2 2 1 1 1 1 1] [1 2 2 1 1 1 1 1]] Thi…

http://stackoverflow.com/a/49034857
score: 2
has comment: http://stackoverflow.com/comment/85075076
has comment: http://stackoverflow.com/comment/85074852
downvote count: 0
has body: You can use Unipath. path = Path("/Electricity/Data_Input/regression_vals/regression_vals.csv") path = path.parent path = path.parent And now path refers to /Electricity/Data_Input directory.
answers question: http://stackoverflow.com/q/49034576
has comment: http://stackoverflow.com/comment/85074732
upvote count: 2
type: Answer

http://stackoverflow.com/q/49116375
tagged with: python
has comment: http://stackoverflow.com/comment/85238841
has comment: http://stackoverflow.com/comment/85237945
downvote count: 0
score: 1
has title: python modules vs organizational security requirements
type: Question
has comment: http://stackoverflow.com/comment/85242112
tagged with: security
upvote count: 1
has comment: http://stackoverflow.com/comment/85238094
favorite count: 0
has body: I have a group of python developers who are asking to install xlrd and xlsxwriter modules so they can use them to read/write Excel Files. The problem is my security team. They will not authorize any module that sends requests and connections outside the server without proper authorization. How do I test these two packages to prove to them that they do not talk to the internet? Thanks!
answer count: 0
has comment: http://stackoverflow.com/comment/85242080
type: UnansweredQuestion

http://stackoverflow.com/comment/85073455
has text: IT says invalid expression for @.*+\W
comment on: http://stackoverflow.com/a/49034180
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85049227
has text: When parsing the file using csv module json part is splitting in different fields.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49015110

http://stackoverflow.com/a/49073441
accepted answer of: http://stackoverflow.com/q/49071739
score: 1
answers question: http://stackoverflow.com/q/49071739
has comment: http://stackoverflow.com/comment/85153256
type: AcceptedAnswer
has body: That property is not by default, so it has to be created. instead of using root.manager.current = 'flash_display' you should call another function that passes the index and change the screen. to set the index we can use setattr to create a new property, and then we can get that index through self.index. test.kv &lt;FlashCard&gt;: ScrollView: size: self.size GridLayout: cols: 5 rows: 2 padding:10 spacing:10 Button: text:'Flash Card 1' on_press: root.on_press(1) width:200 size_hint_x: None Button: text:'Flash Card 2' on_press: root.on_press(2) width:200 size_hint_x: None Button: text:'Flash Card 3' on_press: root.on_press(3) width:200 size_hint_x: None Button: text:'Flash Card 4' on_press: root.on_press(4) width:200 size_hint_x: None Button: text:'Flash Card 5' on_press: root.on_press(5) width:200 size_hint_x: None Button: text:'Flash Card 6' on_press: root.on_press(6) width:200 size_hint_x: None Button: text:'Flash Card 7' on_press: root.on_press(7) width:200 size_hint_x: None Button: text:'Flash Card 8' on_press: root.on_press(8) width:200 size_hint_x: None Button: text:'Flash Card 9' on_press: root.on_press(9) width:200 size_hint_x: None Button: text:'Flash Card 10' on_press: root.on_press(10) width:200 size_hint_x: None main.py from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen class FLashCard(Screen): def on_press(self, index): flash_display_screen = self.manager.get_screen('flash_display') setattr(flash_display_screen, 'index', index) self.manager.current='flash_display' class FlashDisplayPage(Screen): def on_pre_enter(self): print("on_pre_enter",self.index) def on_enter(self): print("on_enter", self.index) class TestApp(App): def build(self): sm = ScreenManager() sm.add_widget(FLashCard(name="flasg_card")) sm.add_widget(FlashDisplayPage(name="flash_display")) return sm if __name__ == '__main__': TestApp().run()
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/a/49031025
type: Answer
has body: Here's the snippet you should use in your code- if(len(nose_rect)&gt;0): print ("Only Nose") for (x,y,w,h) in nose_rect: cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 3) #Here we say that m (the variable created before, should move the mouse using the x, and y variable from the nose rect. # We have acellerated movement speed by 4 to make it possible to navigate the cursor through the whole screen. m.move(x * 4, y * 4) # TODO: Write and if that goes into face if nose is not visible elif (len(face_rect)&gt;0): print ("Only Face") for (x,y,w,h) in face_rect: cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3) elif (len(face_rect)&gt;0): print ("Only Eye") for (x,y,w,h) in eye_rect: cv2.rectangle(frame, (x,y), (x+w,y+h), (205,0,0), 3) else: print ("Nothing detected.") Also, for waiting use the time.sleep() method time.sleep(0.001) # Waiting 1 millisecond to show the next frame. if (cv2.waitKey(1) &amp; 0xFF == ord('q')):#exit on pressing 'q' break
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49029751
has comment: http://stackoverflow.com/comment/85067194
accepted answer of: http://stackoverflow.com/q/49029751
has comment: http://stackoverflow.com/comment/85066940

http://stackoverflow.com/q/49040059
score: 1
linked to: http://stackoverflow.com/q/10377998
has comment: http://stackoverflow.com/comment/85113126
upvote count: 1
has answer: http://stackoverflow.com/a/49055370
type: Question
has title: Python script to add path to the images
has body: I have the following script wherein I add the path to the images in TEST_IMAGE_PATHS. My input is "test_images" folder. In "test_images" folder images are named as image0, image1, image2 etc. Script to add images in test_images to the path is: PATH_TO_TEST_IMAGES_DIR = 'test_images' TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpeg'.format(i)) for i in range(5, 7) ] This script outputs: How do I modify this script such that: I can input any type of images(not just limited to jpeg) as mentioned above. Type of image include JPG, png, jpg, etc Images should not be named as image0, image1, image2, image3, image4, image5, image6 etc. It should not be restricted to this naming convention and should pick up all the images in the 'test_images' folder I referred How can I iterate over files in a given directory?. as suggested, however this link explains how to reference files in the folder and add them to the path. My question has to do with modifications to do to the file after being added to the path. I am able to add files to the path using above script. I need to attach multiple extensions of images. to the existing path
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49055370
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/85112932
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85085653

http://stackoverflow.com/a/48976976
type: Answer
answers question: http://stackoverflow.com/q/48973038
has body: Raspberry pi is more complex, with a microprocessor, memory and GPU. Its like a full fledged computer, basically it needs a OS to managed everything unlike micro controllers like Arduino.
score: 0

http://stackoverflow.com/q/49013882
has answer: http://stackoverflow.com/a/49014566
score: 4
possible better answer: http://stackoverflow.com/a/49014225
has title: How to break a string into a dictionary
answer count: 3
has body: I have a string that looks like this, b'2018-02-27 11:42:40:b\'{"EventID":"65605751","Priority":"Lav Emerg","PriorityColor":"16725041","SortLevel":"7","VStationID":"1002","accepted_flag":"0","ack":"0","bedid":"42","elapseTimeInSeconds":"9","eventTimedOut":"0","failedname":" ","iconindex":"7","location":"1021","operating_mode":"0","pfunction_id":"8","priority_hw_id":"7","priorityindex":"2"}\'' I would like to load this data into a dictionary that looks like this, {"EventID":"65605751","Priority":"Lav Emerg","PriorityColor":"16725041","SortLevel":"7","VStationID":"1002","accepted_flag":"0","ack":"0","bedid":"42","elapseTimeInSeconds":"9","eventTimedOut":"0","failedname":" ","iconindex":"7","location":"1021","operating_mode":"0","pfunction_id":"8","priority_hw_id":"7","priorityindex":"2"} Can someone please tell me how to do this on Win7 Python 3.4? Please note that string length can be variable. But Date, time, '{ both in the beginning and end is going to be there for sure.
has comment: http://stackoverflow.com/comment/85860432
favorite count: 0
tagged with: python-3.x
upvote count: 5
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49014225
type: AnsweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49014348
accepted answer: http://stackoverflow.com/a/49014348

http://stackoverflow.com/a/49063315
upvote count: 2
answers question: http://stackoverflow.com/q/49063008
downvote count: 0
type: Answer
score: 2
has body: You can use query but you need to type the name of columns: df.query("not(line_changed-hist == line_changed-myers and line_changed-hist == line_changed-min and line_changed-hist == line_changed-pat)")

http://stackoverflow.com/comment/86793002
type: Comment
has text: are you trying to run the MNIST or a custom model?
type: AnswerComment
comment on: http://stackoverflow.com/a/49697646
score: 0

http://stackoverflow.com/a/48975450
score: 2
has comment: http://stackoverflow.com/comment/84956460
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48975310
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48975310
downvote count: 0
has body: You need to first loop through the tr's and then inside of that loop, loop through the td's. Below is a simple example. I would also recommend getting the total pages number (819) dynamically and stay away from using hardcoded numbers (like you do in your for loop). import requests from bs4 import BeautifulSoup if __name__ == '__main__': requestUrl = "http://www.portaltransparencia.gov.br/ceis?pagina=2" response = requests.get(requestUrl) soup = BeautifulSoup(response.content, "html.parser") data = [] for tr in soup.find_all('tr'): col = 0 for td in tr.find_all('td'): td_text = td.get_text().strip() if col == 0: cnpj_cpf = td_text cnpj_cpf_link = 'http://www.portaltransparencia.gov.br{}' cnpj_cpf_link = cnpj_cpf_link.format(td.find('a').get('href')) if col == 1: nome = td_text if col == 2: tipo = td_text if col == 3: data_final = td_text if col == 4: nome_do_orago = td_text if col == 5: uf = td_text data.append({ 'cnpj_cpf' : cnpj_cpf, 'cnpj_cpf_link' : cnpj_cpf_link, 'nome' : nome, 'tipo' : tipo, 'data_final' : data_final, 'nome_do_orago' : nome_do_orago, 'uf' : uf }) col += 1 print (data)
type: Answer
has comment: http://stackoverflow.com/comment/84955909

http://stackoverflow.com/q/49121089
type: Question
has answer: http://stackoverflow.com/a/49121127
has answer: http://stackoverflow.com/a/49122176
tagged with: filter
tagged with: pandas
has title: Filter dataframe by line row
has body: Hi I am a beginner python user and I need some help. I am trying to filter one dataframe against another. Df1 date emp# sku transaction# 2017-01-01 10 200 399 2017-01-01 10 201 399 2017-01-01 10 202 399 2017-01-01 11 203 399 2017-01-01 11 200 399 Df2 date emp# sku transaction# 2017-01-01 10 200 301 2017-01-01 11 200 301 Desired Df1 date emp# sku transaction# 2017-01-01 10 200 399 2017-01-01 11 200 399 I know this can work with an inner join (one emp# and sku) but I would have erroneous columns, how can I do this as a filter?
favorite count: 0
has answer: http://stackoverflow.com/a/49121669
upvote count: 2
possible better answer: http://stackoverflow.com/a/49121213
tagged with: python
has answer: http://stackoverflow.com/a/49121213
tagged with: merge
answer count: 4
type: AnsweredQuestion
score: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49121669

http://stackoverflow.com/comment/94719302
type: AnswerComment
score: 0
type: Comment
has text: I am having similar issue but your answer didn't really work for me. I am on Windows 10 x64 with Python 2.7 installed using Anaconda.
comment on: http://stackoverflow.com/a/49053132

http://stackoverflow.com/comment/85206116
has text: Doesn't allow detecting dead ends early, though. If `a+b` is futile prefix, you'll still try it with every available `c`.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49100442

http://stackoverflow.com/q/49031121
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49031731
has body: How should internal linking be done? I try to link from page 1 to page 2. That works ok. But from page to page 2 doesn't work. What is wrong. from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 16) to_page_2 = pdf.add_link() pdf.cell(40, 10, 'Page 1', border=1, ln=0, align='', fill=False, link=to_page_2) pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.set_link(to_page_2) pdf.cell(40, 10, 'Page 2', border=1, ln=0, align='', fill=False) pdf.add_page() pdf.set_font('Arial', 'B', 16) to_page_2 = pdf.add_link() pdf.cell(40, 10, 'Page 3', border=1, ln=0, align='', fill=False, link=to_page_2) pdf.output('pdf_link.pdf', 'F')
tagged with: fpdf
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/49031731
has title: PyFPDF internal link
answer count: 1
favorite count: 0

http://stackoverflow.com/a/49071245
has comment: http://stackoverflow.com/comment/85148547
has comment: http://stackoverflow.com/comment/85149051
has comment: http://stackoverflow.com/comment/85149936
has comment: http://stackoverflow.com/comment/85149361
has comment: http://stackoverflow.com/comment/85148096
answers question: http://stackoverflow.com/q/49070594
has comment: http://stackoverflow.com/comment/85148155
accepted answer of: http://stackoverflow.com/q/49070594
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85149999
has comment: http://stackoverflow.com/comment/85148053
has body: IIUC stack with dropna = False df.set_index('IDs').stack(dropna=False).astype(object).reset_index() Out[915]: IDs level_1 0 0 Ellie AABC 12 1 Ellie ABC6 NaN 2 Ellie YHG.8 48.7 3 Ellie D78Ha 33 4 Kate AABC 98 5 Kate ABC6 34 6 Kate YHG.8 21 7 Kate D78Ha 76.36 8 Joe AABC 22 9 Joe ABC6 53 10 Joe YHG.8 49 11 Joe D78Ha NaN 12 Van AABC 77 13 Van ABC6 NaN 14 Van YHG.8 40 15 Van D78Ha 12.1 16 Xavier AABC NaN 17 Xavier ABC6 NaN 18 Xavier YHG.8 NaN 19 Xavier D78Ha 88.85
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/85148031
has comment: http://stackoverflow.com/comment/85147830
score: 2
has comment: http://stackoverflow.com/comment/85148177
has comment: http://stackoverflow.com/comment/85147978

http://stackoverflow.com/a/67403151
answers question: http://stackoverflow.com/q/49101093
upvote count: 1
type: Answer
has body: You can always use Whoosh in RAM. from whoosh.filedb.filestore import RamStorage store = RamStorage() ix = store.create_index(...)
downvote count: 0
score: 1

http://stackoverflow.com/a/49005225
has body: As you are trying to create a CSV file, the usual approach is to use Python's CSV library. This correctly handles converting lists of data into correctly delimited rows in a file: import csv with open('Csvc1s.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output) csv_output.writerow(["Time", "Total_network's_Belief", "Total_network's_Disbelief", "Total_network's_Uncertainty"]) csv_output.writerows(zip(timeVar, beliefVar, disbelVar, uncerVar)) zip() is used to combine multiple lists together such that each time it is iterated on, the next element from each list is returned as a list (i.e. in this case a whole row). writerows() takes a list of rows and automatically adds the necessary , between each entry and a \n for each row when writing to the file. Note, this assumes that your four lists of data all have the same length.
score: 0
accepted answer of: http://stackoverflow.com/q/48973817
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85224018
type: Answer
answers question: http://stackoverflow.com/q/48973817

http://stackoverflow.com/a/52269729
has comment: http://stackoverflow.com/comment/97550001
type: Answer
has body: As explained in the accepted answer, this issue can be fixed either by installing older version of TensorFlow (v1.5) or building from source. Between the two, building from source is arguably a preferred route despite the additional effort. Granted that the binary contains the most updated components of TensorFlow. The key is in detecting the CPU flags and enable all the CPU flags for optimization when configuring the build. The following command is used to detect common CPU optimization flags: $ grep flags -m1 /proc/cpuinfo | cut -d ":" -f 2 | tr '[:upper:]' '[:lower:]' | { read FLAGS; OPT="-march=native"; for flag in $FLAGS; do case "$flag" in "sse4_1" | "sse4_2" | "ssse3" | "fma" | "cx16" | "popcnt" | "avx" | "avx2") OPT+=" -m$flag";; esac; done; MODOPT=${OPT//_/\.}; echo "$MODOPT"; } If by executing the command, -mavx and/or -mavx2 is not shown, it can be confirmed that AVX support is missing and the source build should be done with other optimization flags displayed in the output.
downvote count: 1
answers question: http://stackoverflow.com/q/49094597
upvote count: 5
score: 4

http://stackoverflow.com/q/49101560
type: UnansweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/85223121
type: Question
has answer: http://stackoverflow.com/a/49101658
answer count: 1
has title: Anaconda / Spyder new package?
linked to: http://stackoverflow.com/q/47879660
score: 0
tagged with: spyder
tagged with: python
has body: I am trying to install ffmpeg on my Anaconda/Spyder install (Win 10/64 bit). I have it in Anaconda However, Spyder does not recognize it import matplotlib.animation as ani ani.MovieWriterRegistry().list() [] import ffmpeg Traceback (most recent call last): File "&lt;ipython-input-4-16f5f3b4de71&gt;", line 1, in &lt;module&gt; import ffmpeg ModuleNotFoundError: No module named 'ffmpeg' Am I missing a step? I'm obviously rather new to this so any help would be greatly appreciated

http://stackoverflow.com/comment/84960373
type: QuestionComment
has text: Check if your IDE supports input() function.Check this one https://stackoverflow.com/questions/12547683/python-3-eof-when-reading-a-line-sublime-text-2-is-angry
comment on: http://stackoverflow.com/q/48977548
score: 0
type: Comment

http://stackoverflow.com/a/49034621
answers question: http://stackoverflow.com/q/49033663
downvote count: 0
score: 1
type: Answer
has body: What you're looking for is the websockets protocol: WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection and usually the default way to do with Django is to use the django-channels project: Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Django design patterns and a flexible underlying framework that lets you not only customize behaviours but also write support for your own protocols and needs. You will probably need to spend some time to configure the channels setup and modify your application to use it, but if you're looking to "push" data from backend to the frontend after a certain action has finished, this is probably the way to do it. I would recommend looking into the channels-examples repository for an example chat implementation which uses django-channels.
upvote count: 1

http://stackoverflow.com/comment/85100963
type: QuestionComment
has text: `prod_weight = prod_weight = ...` are you sure about this?
score: 0
comment on: http://stackoverflow.com/q/49042729
type: Comment

http://stackoverflow.com/a/49043602
score: 0
has body: It solved after I execute send_activation_mail by using threading threading.Thread(target=self.send_activation_mail(request=request, user=user)).start()
type: Answer
answers question: http://stackoverflow.com/q/49042917

http://stackoverflow.com/comment/85158986
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49076483
has text: The header is user defined. i, j, k, and strings like "Data Field" or "dataset test" are all user defined.
score: 0

http://stackoverflow.com/comment/85004063
has text: `with open('something', 'w') as f: f.write('something')` @MattHill
comment on: http://stackoverflow.com/a/48999248
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85107242
score: 0
type: QuestionComment
type: Comment
has text: the last report from my reporter gave 99% for 3 of CPU cores (8 cores) and 44% MEM usage (32GB)
comment on: http://stackoverflow.com/q/49051245

http://stackoverflow.com/q/49108541
type: UnansweredQuestion
has title: Pyspark TextParsingException while loading a file
tagged with: python
has comment: http://stackoverflow.com/comment/85222442
has comment: http://stackoverflow.com/comment/85222519
type: Question
has comment: http://stackoverflow.com/comment/85223321
has body: I am loading a csv file having 1 million records using pyspark, but getting the error. TextParsingException: Length of parsed input (1000001) exceeds the maximum number of characters defined in your parser settings (1000000) I checked if any of my record in the file has data greater than 1000000 characters, but none of the record is like that. maximum record length in my file is 850. Please help.... CODE SNIPPET: input_df = spark.read.format('com.databricks.spark.csv').option("delimiter","\001").option("quote",u"\u0000").load(INPUT_PATH) input_df.write.mode('overwrite').format('orc').save(TARGET_LOC) SAMPLE DATA A B C -- -- -- a xyz"a 123 b pqr 456 c ABC"z 789
tagged with: pyspark
has comment: http://stackoverflow.com/comment/85222044
score: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85223185
has answer: http://stackoverflow.com/a/49110247
answer count: 1
has comment: http://stackoverflow.com/comment/85222439

http://stackoverflow.com/q/49043744
tagged with: flask
has comment: http://stackoverflow.com/comment/85132376
score: 0
has comment: http://stackoverflow.com/comment/85097117
has comment: http://stackoverflow.com/comment/96204484
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/85098750
has comment: http://stackoverflow.com/comment/85097372
has comment: http://stackoverflow.com/comment/85094804
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85098480
tagged with: python
answer count: 0
has body: from flask import Flask, render_template, request, redirect, url_for, abort import xlsxwriter import testexecute import json import datetime from requests.models import Response #from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy from config import BaseConfig app = Flask(__name__) app.config.from_object(BaseConfig) #bcryptt = Bcrypt(app) db = SQLAlchemy(app) import constants @app.route('/') def index(): return render_template('Index.html') @app.route('/error') def error(): print("error") return render_template('errorPage.html') @app.errorhandler(500) def internal_server_error(e): print("internal_server_error") return render_template('500.html') @app.errorhandler(400) def page_not_found(e): print("page_not_found") return render_template('400.html'), 400 @app.route('/testExecution', methods=['POST']) def invoke_testExecution(): try: testexecute.execute(request) return "Test Started" except: print("Jenkins Exception") return "Test Aborted" #return redirect(url_for('error')) if __name__ == '__main__': app.run(debug=False, host='0.0.0.0') I have Index.html, errorPage.html, 500.html files under the templates directory. 'Index.html' is rendered fine. Messages "error" and "internal_server_error" are getting printed when I am routing to those but the templates "500.html" and "errorPage.html" are not rendered. In case of status 500, the content of 500.html is printed on the browser console but redirection doesn't take place! Please help! 500.html: Server error errorPage.html: We are sorry to inform you that some error occured!! Please Login again!!
has comment: http://stackoverflow.com/comment/85102200
upvote count: 1
downvote count: 1
type: Question
has title: Flask render_template working only with index.html

http://stackoverflow.com/a/49087876
score: 1
has comment: http://stackoverflow.com/comment/85184282
answers question: http://stackoverflow.com/q/49087598
has body: Your MiddleLeftFrame is 800 pixels wide. Your MiddleRightFrame is 1120 pixels. 1120 + 800 = 1920. You're forcing the window to be only 1920 pixels wide, so there's no room for the blue frame. Remove this line and your frame will appear: root.geometry("1920x1080") If your intent is for it to appear at the bottom of the window, spanning the entire width of the window, then call pack on it before you call pack on the left and right sides. Also, I strongly recommend grouping your pack statements together. It makes the code easier to manage in my experience (and I have a lot of experience!). import tkinter from tkinter import * root = tkinter.Tk() root.geometry("1920x1080") TopFrame = Frame(root, width=1920, height=200, bg= "green") MiddleRightFrame = Frame(root, width=1120, height=730, bg="orange") MiddleLeftFrame = Frame(root, width=800, height=730, bg="black") BottomFrame = Frame(root, width=1920, height=150, bg="blue") TopFrame.pack(side=TOP) BottomFrame.pack(side=BOTTOM) MiddleRightFrame.pack(side=RIGHT) MiddleLeftFrame.pack(side=LEFT) root.mainloop() The reason this works is due to the packer algorithm. When you place something on the left or right, it will allocate all of the remaining vertical space on that side. Thus, after you pack something on the left and right and then later pack something on the bottom, the "bottom" is the bottom of the space between the left and right, not the bottom of the window as a whole. Here is the canonical description of how pack works: http://tcl.tk/man/tcl8.5/TkCmd/pack.htm#M26
upvote count: 1
has comment: http://stackoverflow.com/comment/85184052
has comment: http://stackoverflow.com/comment/85184080
type: Answer
has comment: http://stackoverflow.com/comment/85183018
has comment: http://stackoverflow.com/comment/85181967
downvote count: 0

http://stackoverflow.com/q/49102177
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6974695
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/49102536
has body: In an answer to the question "Python Process Pool non-daemonic?" it is shown how to disable the daemon attribute of a process: class NoDaemonProcess(multiprocessing.Process): # make 'daemon' attribute always return False def _get_daemon(self): return False def _set_daemon(self, value): pass daemon = property(_get_daemon, _set_daemon) # We sub-class multiprocessing.pool.Pool instead of multiprocessing.Pool # because the latter is only a wrapper function, not a proper class. class MyPool(multiprocessing.pool.Pool): Process = NoDaemonProcess This allows for a process in a pool to start it's own child process, as explained in the original question. In exchange for the flexibility of starting child processes, what costs is paid? If there were no costs, presumably the standard Pool would have used non-daemonic processes. Note: this question is based on a highly upvoted comment that went unaddressed, so I decided to convert it to a question.
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49102536
has title: Disadvantage to disabling daemon attribute on a Process?

http://stackoverflow.com/comment/85183886
score: 0
type: AnswerComment
type: Comment
has text: I tried with `post` request method using `requests` library and got success but the thing is there are two fields (additionally) to be filled in `latitude` and `longitude` to populate results that is why i tried with this but it seems to be my bad luck.
comment on: http://stackoverflow.com/a/49088642

http://stackoverflow.com/a/49134951
answers question: http://stackoverflow.com/q/49088748
has comment: http://stackoverflow.com/comment/85378154
upvote count: 8
type: AcceptedAnswer
has body: Here is a code working with Python 2.7 (I assume it works with Python 3.6.4 as well - I'm not familiar yet with the change between 2.X and 3.X) #!/usr/bin/env python3 import win32com.client as win32 path_file_name = "YourPath\ToYour\doc.docx" word = win32.gencache.EnsureDispatch("Word.Application") word.Visible = False doc = word.Documents.Open(path_file_name ) doc.Activate() word.ActiveDocument.TrackRevisions = False # Maybe not need this (not really but why not) # Accept all revisions word.ActiveDocument.Revisions.AcceptAll() # Delete all comments if word.ActiveDocument.Comments.Count &gt;= 1: word.ActiveDocument.DeleteAllComments() word.ActiveDocument.Save() doc.Close(False) word.Application.Quit() Let me know if it works out for you.
has comment: http://stackoverflow.com/comment/116657254
has comment: http://stackoverflow.com/comment/116657145
score: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/49088748
downvote count: 0
has comment: http://stackoverflow.com/comment/85404339

http://stackoverflow.com/comment/84966762
comment on: http://stackoverflow.com/a/48965545
score: 0
type: AnswerComment
has text: Thnx for your kind help :) and your second option is good bcz of small code changes but after adding arc_name in add() i am facing an error TypeError: add() got an unexpected keyword argument 'tarinfo'
type: Comment

http://stackoverflow.com/a/49137939
type: Answer
answers question: http://stackoverflow.com/q/49101890
score: 0
accepted answer of: http://stackoverflow.com/q/49101890
type: AcceptedAnswer
has body: Generally, most packages handle config files like this by only providing an example config, and requiring the user to change the filename or move it to a different location so that it won't get overwritten or deleted. Another thing that some packages will do is provide a command line script to help generate the config (e.g. Sphinx, Django) in a user specified location, instead of packaging a config with the project.

http://stackoverflow.com/a/48989130
has comment: http://stackoverflow.com/comment/95568092
upvote count: 26
has comment: http://stackoverflow.com/comment/126436936
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/132570566
type: Answer
answers question: http://stackoverflow.com/q/48980368
score: 25
has comment: http://stackoverflow.com/comment/132570696
has body: Use envs.registry.all(): from gym import envs print(envs.registry.all()) Out: dict_values([EnvSpec(Copy-v0), EnvSpec(RepeatCopy-v0), EnvSpec(ReversedAddition-v0), EnvSpec(ReversedAddition3-v0), EnvSpec(DuplicatedInput-v0), EnvSpec(Reverse-v0), EnvSpec(CartPole-v0), ...]) This returns a large collection of EnvSpec objects, not specifically of the IDs as you asked. You can get those like this: from gym import envs all_envs = envs.registry.all() env_ids = [env_spec.id for env_spec in all_envs] print(sorted(env_ids)) Out: ['Acrobot-v1', 'Ant-v2', 'Ant-v3', 'BipedalWalker-v3', 'BipedalWalkerHardcore-v3', 'Blackjack-v1', 'CarRacing-v0', 'CartPole-v0', 'CartPole-v1', ...]
accepted answer of: http://stackoverflow.com/q/48980368
downvote count: 1

http://stackoverflow.com/q/49019554
has body: I'm curious of what's the point of using return statement. def give_me_five(): five = 5 return five number = give_me_five() print("Here's what I got from give_me_five():", number) Above code shows the following result. Here's what I got from give_me_five(): 5 As you can see, when you can just type 5 in print("Here's what I got from give_me_five():", 5) like this, what's exactly the point of using return statement and why does it need to even make a function to set a value 5?
has comment: http://stackoverflow.com/comment/85044580
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/85044288
upvote count: 1
tagged with: function
has comment: http://stackoverflow.com/comment/85047892
favorite count: 0
has comment: http://stackoverflow.com/comment/85044347
has comment: http://stackoverflow.com/comment/85044629
answer count: 1
tagged with: python-3.x
tagged with: return
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/85044608
tagged with: python
has title: The point of use of return statement
has answer: http://stackoverflow.com/a/49019595

http://stackoverflow.com/q/49090954
favorite count: 0
has body: I got started using AWS Glue for my data ETL. I've pulled in my data sources into my AWS data catalog, and am about to create a job for the data from one particular Postgres database I have for testing. I have read online that when authoring your own job, you can use a Zeppelin notebook. I haven't used Zeppelin at all, but have used Jupyter notebook heavily as I'm a python developer, and was using it a lot for data analytics, and machine learning self learnings. I haven't been able to find it anywhere online, so my question is this "Is there a way to use Jupyter notebook in place of a Zeppelin notebook when authoring your own AWS Glue jobs?"
possible better answer: http://stackoverflow.com/a/68013882
tagged with: python
has answer: http://stackoverflow.com/a/68013882
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49095523
type: Question
tagged with: aws-glue
has title: Is it possible to use Jupyter Notebook for AWS Glue instead of Zeppelin
answer count: 2
accepted answer: http://stackoverflow.com/a/49095523
downvote count: 0
tagged with: jupyter

http://stackoverflow.com/q/49055591
tagged with: python-2.7
answer count: 2
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85120539
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85120486
downvote count: 0
possible better answer: http://stackoverflow.com/a/72242157
has title: Oscillatory integral in python
tagged with: scipy
has body: I wrote the following code to plot the intensity of light exiting an optical components, which is basically a spherical Fourier integral on the incident field, so it has a Bessel function. The argument of which depends on the integrating variable (x) and the plotting variable (r). from sympy import * import matplotlib.pyplot as plt import numpy as np from scipy.integrate import quad from scipy.special import jn #constants mm = 1 um = 1e-3 * mm nm = 1e-6 * mm wavelength = 532*nm klaser = 2*np.pi / wavelength waist = 3.2*mm angle = 2 #degrees focus = 125 * mm ng = 1.5 # refractive index of axicon upperintegration = 5 #integrals def b(angle): radians = angle* np.pi/180 return klaser * (ng-1) * np.tan(radians) def delta(angle): return np.pi/(b(angle)*waist) def integrand(x, r): return klaser/focus * waist**2 * np.exp(-x**2) * np.exp(-np.pi * 1j * x/delta(angle)) * jn(0, waist*klaser*r*x/focus) * x def intensity1D(r): return np.sqrt(quad(lambda x: np.real(integrand(x, r)), 0, upperintegration)[0]**2 + quad(lambda x: np.imag(integrand(x, r)), 0, upperintegration)[0]**2) fig = plt.figure() ax = fig.add_subplot(111) t = np.linspace(-3.5, 3.5, 25) plt.plot(t, np.vectorize(intensity1D)(t)) The issue is that the plot changes drastically as I change the number of points I am using in my linspace, when I plot it. I suspect this may be because of the oscillatory nature of the integral, so the step-size taken can dramatically change the value of the exponent and hence of the integral. How does quad deal with this? Are there better methods to integrate numerically for this particular application?
has answer: http://stackoverflow.com/a/72242157
type: Question
has answer: http://stackoverflow.com/a/49062677
score: 1
accepted answer: http://stackoverflow.com/a/49062677
tagged with: matplotlib

http://stackoverflow.com/q/48992030
type: Question
score: 5
upvote count: 5
downvote count: 0
tagged with: python-embedding
has comment: http://stackoverflow.com/comment/85674197
answer count: 1
has answer: http://stackoverflow.com/a/49014474
has title: Disable built-in module import in embedded Python
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84989201
accepted answer: http://stackoverflow.com/a/49014474
has comment: http://stackoverflow.com/comment/84989118
linked to: http://stackoverflow.com/q/3068139
has body: I'm embedding Python 3.6 in my application, and I want to disable import command in the scripts to prevent users to import any python built-in libraries. I'd like to use only the language itself and my own C++ defined modules. Py_SetProgramName (L"Example"); Py_Initialize (); PyObject* mainModule = PyImport_AddModule ("__main__"); PyObject* globals = PyModule_GetDict (mainModule); // This should work std::string script1 = "print ('example')"; PyRun_String (script1.c_str (), Py_file_input, globals, nullptr); // This should not work std::string script2 = "import random\n" "print (random.randint (1, 10))\n"; PyRun_String (script2.c_str (), Py_file_input, globals, nullptr); Py_Finalize (); Do you know any way to achieve this?

http://stackoverflow.com/a/49063133
answers question: http://stackoverflow.com/q/49052479
has body: To create a string from list's elements: my_list_1 = ['a', 'c', 'e'] my_list_2 = [1, 3, 5] # The "join" works for both when list's element type is "string" or "int" list_1_str = ''.join(map(str, my_list_1)) # output: "ace" list_2_str = ''.join(map(str, my_list_2)) # output: "135"
score: 0
type: Answer

http://stackoverflow.com/comment/85184362
has text: They either don't, or they are patient.
score: 1
comment on: http://stackoverflow.com/q/49089238
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85186769
has text: Can you paste in a large snippet of HTML so we can see more context?
score: 0
comment on: http://stackoverflow.com/q/49090572
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49077020
tagged with: nested-loops
accepted answer: http://stackoverflow.com/a/49077145
answer count: 1
has body: I have a directory output, and it is going to be a series of nested loops where the first item in the list is a sub-directory, which may or may not contain sub-directories themselves. Example: directory=[["$Recycle.Bin","S-1-5-18"],["AutoDesk",["AutoCad","File1","File2","File3"],["Inventor","project1"],["WI","Copyright"]]] This would as a directory look like: $Recycle.Bin -&gt;S-1-5-18 AutoDesk -&gt; AutoCad -&gt;File1 -&gt;File2 -&gt;File3 -&gt; Inventor -&gt;project1 -&gt; WI -&gt;Copyright and the output of the function would be: print the directory name, and then all items in the directory so that I can add them to the GUI. I just can't figure out how to determine if something is an object in a list of another set of nested lists.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49077145
score: 0
has title: Printing the Contents of Nested lists With unknown Depths
type: Question

http://stackoverflow.com/q/49013275
tagged with: virtualenv
answer count: 3
has answer: http://stackoverflow.com/a/56263907
downvote count: 0
tagged with: macos
favorite count: 0
has body: I have the following exec commands in my gradle.build file. exec { workingDir System.getProperty("user.dir") commandLine 'python3.6', 'buildscript.py' } exec { workingDir System.getProperty("user.dir") commandLine 'python3.6', '-m', 'virtualenv', 'env' } exec { workingDir System.getProperty("user.dir") commandLine 'source', 'env/bin/activate' } exec { workingDir System.getProperty("user.dir") commandLine 'pip3.6', 'install', 'pybuilder' } exec { workingDir System.getProperty("user.dir") commandLine 'pyb', '-E', 'env', '-X' } These are all within a build task that runs when executing gradle build. Theoretically this should run a script I created that creates all of the files necessary for building my python program, it should then create a virtual environment, activate it, install pybuilder to it, and then run pybuilder. However, the command: exec { workingDir System.getProperty("user.dir") commandLine 'source', 'env/bin/activate' } Seems to be failing. It claims that the directory/file does not exist despite it working via command line. I'm not sure why this is the case. The whole point of this is to force Pybuilder to install my programs dependencies to the virtual environment I create. pyb -E env should technically be activating the virtual environment for me, but for whatever reason it's not installing my dependencies to that virtual environment. On our Jenkins node this is a problem as we don't want these installed globally, not to mention, I don't have root user privileges anyways. Any help would be greatly greatly appreciated. If you know of another way to get Pybuilder to work correctly, that would be equally good.
has title: How do you activate a virtual environment from Gradle?
upvote count: 1
tagged with: python
tagged with: pybuilder
accepted answer: http://stackoverflow.com/a/56263907
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49017592
tagged with: gradle
type: Question
possible better answer: http://stackoverflow.com/a/49017592
has answer: http://stackoverflow.com/a/71174317

http://stackoverflow.com/q/48978463
tagged with: matrix-factorization
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85080121
tagged with: matrix
has comment: http://stackoverflow.com/comment/85110746
downvote count: 0
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/49061451
tagged with: python
has comment: http://stackoverflow.com/comment/85065697
tagged with: sklearn-pandas
upvote count: 1
possible better answer: http://stackoverflow.com/a/48978617
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48978617
has title: python dict to matrix using implict feedback approach
score: 1
has answer: http://stackoverflow.com/a/49061451
has body: I'm seeking to configure the best model for measuring implicit feedback given my nested dictionary of unique users and the number of plays per artist listened to. I've tried a few values but they appear only cosmetic, and not measurable. Sample data: users artist plays 0 00001411dc427966b17297bf4d69e7e193135d89 korn 12763 1 00001411dc427966b17297bf4d69e7e193135d89 sting 8192 2 00001411dc427966b17297bf4d69e7e193135d89 nirvana 6413 Source code: user_artist_dict = user_artist_plays.groupby('users').apply(lambda user_artist_plays: dict(zip(user_artist_plays.artist, user_artist_plays.plays))).to_dict() I want a matrix factoring 0 plays if user did not listen to artist, and if they had it inserts the plays. My initial intention was to use DictVectorizer with sklearn but it's giving me trouble with artist strings.

http://stackoverflow.com/q/49038899
downvote count: 0
tagged with: kdb+
favorite count: 0
has answer: http://stackoverflow.com/a/49039223
tagged with: python
has title: Kdb database to NumPy array in PyQ
accepted answer: http://stackoverflow.com/a/49039223
tagged with: python-3.x
upvote count: 2
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49039115
has body: I have a splayed Kdb database of symbols, floats, and timestamps. I'd like to convert this to NumPy arrays. However using the following code... &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from pyq import q &gt;&gt;&gt; d = q.load(':alpha/HDB/') &gt;&gt;&gt; a = np.array(d) Returns this error... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/marrowgari/py3/lib/python3.6/site-packages/pyq/_n.py", line 158, in array return numpy.array(list(self), dtype) TypeError: iteration over a K scalar, t=-11 Is this because Kdb symbol types do not have a direct analogue in NumPy? If so, how do I correct this?
has answer: http://stackoverflow.com/a/49039115
tagged with: pyq
type: Question
tagged with: numpy
answer count: 2

google-app-engine-python
type: Tag
tags question: http://stackoverflow.com/q/49045762
tag name: google-app-engine-python

http://stackoverflow.com/a/50135675
has comment: http://stackoverflow.com/comment/95404233
has comment: http://stackoverflow.com/comment/99029674
downvote count: 0
upvote count: 39
answers question: http://stackoverflow.com/q/49120069
has body: Further to you answer, you don't need to convert to csv. pickle.dumps method returns a byte obj. see here: https://docs.python.org/3/library/pickle.html import boto3 import pickle bucket='your_bucket_name' key='your_pickle_filename.pkl' pickle_byte_obj = pickle.dumps([var1, var2, ..., varn]) s3_resource = boto3.resource('s3') s3_resource.Object(bucket,key).put(Body=pickle_byte_obj)
score: 39
type: Answer

http://stackoverflow.com/q/49101595
upvote count: 0
has body: I am trying to grab sports data. allgames= driver.find_element_by_id("games") box=allgames.find_element_by_link_text("Box Score") This works, but it only grabs the box score form the first game (which is from tr data-row="0") I am trying to find a way where I can go to tr data-row="1" and then use .find_element_by_link_text("Box Score") PICTURE OF HTML:
has title: Get to second tr in data row table, Selenium Python
score: -1
favorite count: 0
has answer: http://stackoverflow.com/a/49101614
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49101765
has comment: http://stackoverflow.com/comment/85213978
tagged with: selenium
tagged with: web-scraping
downvote count: 1
type: Question
answer count: 2

http://stackoverflow.com/a/49046381
upvote count: 1
answers question: http://stackoverflow.com/q/49046330
has comment: http://stackoverflow.com/comment/85097506
downvote count: 0
type: Answer
has body: You can use either a modern WSGI environment like Flask or Django, or if the utility is very small, you can take a look at Common Gateway Interface (CGI).
score: 1

http://stackoverflow.com/a/49026381
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49025832
type: Answer
score: 1
upvote count: 1
has body: You can make an image-like array for Z and then just use imshow to display it before the image of the buttons, etc. Note that this only works because your png has an alpha channel. Code: from PIL import Image import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm # Plot the density map using nearest-neighbor interpolation img = plt.imread("image.png") (xSize, ySize, cSize) = img.shape x = np.arange(0,xSize,1) y = np.arange(0,ySize,1) X,Y = np.meshgrid(x,y) Z = 0.6+0.1*np.random.rand(xSize,ySize) Z[0,0] = 0 Z[1,1] = 1 # We need Z to have red, blue and green channels # For a greyscale image these are all the same Z=np.repeat(Z,3).reshape(xSize,ySize,3) fig = plt.figure(figsize=(20,8)) ax = fig.add_subplot(111) ax.imshow(Z, interpolation=None) ax.imshow(img, interpolation=None) fig.savefig('output.png') Output: You can also turn off axes if you prefer. ax.axis('off')
answers question: http://stackoverflow.com/q/49025832

http://stackoverflow.com/comment/85274897
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49035812
has text: I do. I can't force my client thousands miles away to install any extra libraries.
score: 0

http://stackoverflow.com/a/48978186
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48978144
has body: The k[:+1,0] means "from 0 to +1", there is only one element. You need: k[:-1, 0] &lt; k[1:, 0]
downvote count: 0

http://stackoverflow.com/comment/85161630
comment on: http://stackoverflow.com/a/49077765
type: AnswerComment
has text: **This program wouldn't compile**. You have `CowYields` and `200` on separate lines forming incomplete expressions and you have a random `.valueCowYields()` method which isn't defined.
score: 0
type: Comment

http://stackoverflow.com/a/62295828
type: Answer
has body: It is frustrating to not be able to insert directly in sparse format with .loc[]. I'm afraid I only have a workaround. Since the original posting of the question (and version 0.25) pandas has deprecated SparseDataFrame. Instead, it created a data type (SparseDtype) that can be applied to individual series within the DataFrame. In other words, it is no longer "all or nothing". You can: convert a few columns in your DataFrame to dense format while keeping the others sparse, insert your data with .loc[] in the dense columns, and then convert these columns back to sparse. This is obviously a lot less memory intensive than converting the entire DataFrame to dense. Here is a very simple function to illustrate what I mean: def sp_loc(df, index, columns, val): """ Insert data in a DataFrame with SparseDtype format Only applicable for pandas version &gt; 0.25 Args ---- df : DataFrame with series formatted with pd.SparseDtype index: str, or list, or slice object Same as one would use as first argument of .loc[] columns: str, list, or slice Same one would normally use as second argument of .loc[] val: insert values Returns ------- df: DataFrame Modified DataFrame """ # Save the original sparse format for reuse later spdtypes = df.dtypes[columns] # Convert concerned Series to dense format df[columns] = df[columns].sparse.to_dense() # Do a normal insertion with .loc[] df.loc[index, columns] = val # Back to the original sparse format df[columns] = df[columns].astype(spdtypes) return df Simple usage example: # DÉFINITION DATAFRAME SPARSE df1 = pd.DataFrame(index=['a', 'b', 'c'], columns=['I', 'J']) df1.loc['a', 'J'] = 0.42 df1 = df1.astype(pd.SparseDtype(float)) # | I | J # ----+-----+-------- # a | nan | 0.42 # b | nan | nan # c | nan | nan df1.dtypes #I Sparse[float64, nan] #J Sparse[float64, nan] df1.sparse.density # 0.16666666666666666 # INSERTION df1 = sp_loc(df1, ['a','b'], 'I', [-1, 1]) # | I | J # ----+-----+-------- # a | -1 | 0.42 # b | 1 | nan # c | nan | nan df1.sparse…
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49032856
downvote count: 0

http://stackoverflow.com/q/49099548
tagged with: merge
has title: Merge in pandas
score: 1
accepted answer: http://stackoverflow.com/a/49099570
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/53645882
possible better answer: http://stackoverflow.com/a/49099671
has answer: http://stackoverflow.com/a/49099570
has body: What is difference between pd.merge(staff_df, student_df, how='left', left_index=True, right_index=True) and pd.merge(staff_df, student_df, how='left', left_on='Name', right_on='Name')
tagged with: dataframe
type: Question
linked to: http://stackoverflow.com/q/53645882
answer count: 2
tagged with: pandas
upvote count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49099671
tagged with: python

http://stackoverflow.com/comment/85175766
comment on: http://stackoverflow.com/a/49073066
score: 0
type: AnswerComment
has text: unfortunately that does not help. I already tried this before opening a question. It returns empty string. Also for test I tried output.write('test') and getvalue() returned me a result. But when I provide output as an argument to this function outpus is still empty.
type: Comment

http://stackoverflow.com/comment/85148207
has text: I am able to get a graph like this. I don't understand how to pass arguments like position into the spring_layout. I'll add more description to the question to make this clear.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49063113

http://stackoverflow.com/a/49127422
has comment: http://stackoverflow.com/comment/85260702
accepted answer of: http://stackoverflow.com/q/49105056
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85260867
has body: You didn't state which database system you're using, but I'll assume it is MySQL (or MariaDB) and provide an example based on this post. We'll make use of the MySQL function YEARWEEK(). For that purpose we'll create a python class inheriting from Func: from django.db.models import Func, IntegerField class YearWeek(Func): function = 'YEARWEEK' template = '%(function)s(%(expressions)s)' output_field = IntegerField() Now we can make a query like this: from django.db.models import Count from yourapp.models import tbl_data from yourapp.filewhityearweek import YearWeek result = tbl_data.objects.annotate( yearweek=YearWeek('date') ).values('yearweek').annotate( count=Count('date') ).order_by('yearweek') This will return something like this: &lt;QuerySet [{'yearweek': 201801, 'count': 5}, {'yearweek': 201802, 'count': 3}, {'yearweek': 201803, 'count': 2}]&gt; Depending on your data the result will certainly vary. The SQL query produced by Django ORM will look like this: SELECT YEARWEEK('tbl_data'.'date') AS 'yearweek', COUNT('tbl_data'.'date') AS 'count' FROM 'tbl_data' GROUP BY YEARWEEK('tbl_data'.'date') ORDER BY 'yearweek' ASC This should help you to group your entries by calender week. Using YEARWEEK should give you better overview than functions like WEEK as it is returning the year and the calender week.
answers question: http://stackoverflow.com/q/49105056
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85262181
type: Answer
has comment: http://stackoverflow.com/comment/85260724
has comment: http://stackoverflow.com/comment/85260684
has comment: http://stackoverflow.com/comment/85260685

http://stackoverflow.com/comment/84990269
score: 0
type: AnswerComment
type: Comment
has text: Could you add some comments for a beginner like me to understand more? What is re.compile doing there?
comment on: http://stackoverflow.com/a/48992499

http://stackoverflow.com/comment/85233077
has text: the thing is, the other question is answered as soon as conversion is established. But here, there could be a possibility of a different approach. The other question could be about a small file and a simple cell-level conversion might have worked, but here it could be a huge file and a different logic could be better, as in avoiding going through the loops to convert the cells.
score: 0
comment on: http://stackoverflow.com/q/49112642
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48988022
has comment: http://stackoverflow.com/comment/84983090
tagged with: web.py
has comment: http://stackoverflow.com/comment/84982965
has comment: http://stackoverflow.com/comment/84980741
has comment: http://stackoverflow.com/comment/84981287
has title: ModuleNotFoundError: No module named 'gothonweb2' in python
type: Question
tagged with: automated-tests
has body: My error is like (base) C:\Users\lenovo\projects\gothonweb2&gt;python bin/app.py Traceback (most recent call last): File "bin/app.py", line 2, in &lt;module&gt; from gothonweb2 import map ModuleNotFoundError: No module named 'gothonweb2' The project directory is C:\Users\lenovo\projects\gothonweb2 bin __init__.py app.py gothonweb2 __init__.py web.py templates layout.html show_room.html you_died.html tests __init__.py app_tests.py map_tests.py tools.py The code in bin/app.py is : import web from gothonweb2 import map import urllib.request urls=( '/game','GameEngine', '/','Index', ) app=web.application(urls,globals()) #Title hack so that debug mode works with sessions if web.config.get('_session') is None: store=web.session.DiskStore('sessions') session=web.session.Session(app,store,initializer={'room':None}) web.config._session=session else: session=web.config._session render=web.template.render('templates/',base="layout") class Index(object): def GET(self): #this is use to"setup"the session with starting values session.room=map.START web.seeother("/game") class GameEngine(object): def GET(self): if session.room: return render.show_room(room=session.room) else: return render.you_died() def POST(self): form=web.input(action=None) #there is a bug here,can you fix it? if session.room and form.action: session.room=session.room.go(form.action) web.seeother("/game") if __name__=="__main__": app.run() I got the error just as above. Also the project's path and the import gothonweb2 part are also above. I don't know why it returns 'No module named 'gothonweb2''. Can someone help me?
score: 0
has comment: http://stackoverflow.com/comment/84980527
tagged with: python-module
tagged with: python
has comment: http://stackoverflow.com/comment/84981222
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/49075566
has comment: http://stackoverflow.com/comment/85157210
accepted answer of: http://stackoverflow.com/q/49075473
score: 0
answers question: http://stackoverflow.com/q/49075473
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85157107
has body: pip3 install numpy pip install numpy use above command in terminal and install numpy for python 3.6 then try again.

http://stackoverflow.com/q/49116544
has body: I am trying to do classification between dogs and cats; for this I use a CNN model, but when I place the Image matrix to tf.placeholder, I get an error that "placeholder return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)", but I don't understand the problem. How can I fix this? My code: import os import warnings import glob import h5py import tensorflow as tf import math as mt import numpy as np import cv2 as cv from matplotlib import pyplot from tflearn.data_utils import image_preloader from random import shuffle import tflearn as tfl warnings.simplefilter("ignore") path="E:\data\minimum" path1='E:\data\\train.txt' path2='E:\data\\testing.txt' path3='E:\data\\validation.txt' training=0.7 testing=0.2 validation=0.1 list=os.listdir(path) shuffle(list) lenght=len(list) file=open(path1,'w') train=list[0: int(training*lenght)] for i in train: if(i[0:3]=='cat'): file.write(path + '/'+ i + ' 0\n') elif(i[0:3]=='dog'): file.write(path + '/'+ i + ' 1\n') file.close() file=open(path3,'w') train=list[0: int(validation*lenght)] for i in train: if(i[0:3]=='cat'): file.write(path + '/'+ i + ' 0\n') elif(i[0:3]=='dog'): file.write(path + '/'+ i + ' 1\n') file.close() file=open(path2,'w') train=list[0: int(testing*lenght)] for i in train: if(i[0:3]=='cat'): file.write(path + '/'+ i + ' 0\n') elif(i[0:3]=='dog'): file.write(path + '/'+ i + ' 1\n') file.close() X_train, Y_train =image_preloader(path1, image_shape=(50,50),mode='file', categorical_labels=True,normalize=True) X_test, Y_test =image_preloader(path2, image_shape=(50,50),mode='file', categorical_labels=True,normalize=True) X_val, Y_val =image_preloader(path3, image_shape=(50,50),mode='file', categorical_labels=True,normalize=True) print ("Dataset") print ("Number of training images {}".format(len(X_train))) print ("Number of testing images {}".format(len(X_test))) print ("Number of validation images {}".format(len(X_val))) print ("Shape of an image {}" .format(X_train[1].shape)) print ("Shape of label:{…
favorite count: 0
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/49120329
tagged with: tensorflow
linked to: http://stackoverflow.com/q/44664285
type: Question
score: 1
tagged with: deep-learning
has title: placeholder return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
downvote count: 0
answer count: 1

http://stackoverflow.com/a/48996046
accepted answer of: http://stackoverflow.com/q/48995959
has comment: http://stackoverflow.com/comment/84997775
answers question: http://stackoverflow.com/q/48995959
upvote count: 3
has body: You can write an generator that uses range def my_cycle(start, stop, step=1): while True: for x in range(start, stop, step): yield x c = my_cycle(0, 10)
has comment: http://stackoverflow.com/comment/84997414
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/q/49116676
has comment: http://stackoverflow.com/comment/85240135
has title: appending indices to numpy array
type: Question
tagged with: numpy
tagged with: arrays
accepted answer: http://stackoverflow.com/a/49118756
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85239957
has comment: http://stackoverflow.com/comment/85244762
has comment: http://stackoverflow.com/comment/85238743
tagged with: python
has answer: http://stackoverflow.com/a/49118756
type: AnsweredQuestion
has body: I make a variable corr_matrix by iterating over rows and columns and correlating values. import numpy as np import random enc_dict = {k: int(random.uniform(1,24)) for k in range(24)} ret_dict = {k: int(random.uniform(1,24)) for k in range(24)} corr_matrix=np.zeros((24,24)) ind_matrix = np.zeros((24,24)) data = np.random.rand(24,24) for enc_row in range(0,24): for ret_col in range(0,24): corr_matrix[enc_row, ret_col] = np.corrcoef(data[enc_row,:], data[ret_col,:])[0,1] if enc_dict[enc_row] == ret_dict[ret_col]: ind_matrix = np.append(ind_matrix, enc_row, ret_col) I want to store the indices in the matrix where enc_dict[enc_row] == ret_dict[ret_col] as a variable to use for indexing corr_matrix. I can print the values, but I can't figure out how to store them in a variable in a way that allows me to use them for indexing later. I want to: make a variable, ind_matrix that is the indices where the above statement is true. I want to use ind_matrix to index within my correlation matrix. I want to be able to index the whole row as well as the exact value where the above statement is true (enc_dict[enc_row] == ret_dict[ret_col]) I tried ind_matrix = np.append(ind_matrix, enc_row, ret_col) which gives me the correct values but it has a lot of 0s before the #s for some reason. Also it doesn't allow me to call each pair of points together to use for indexing. I want to be able to do something like corr_matrix[ind_matrix[1]]

http://stackoverflow.com/q/48989490
has comment: http://stackoverflow.com/comment/84983438
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48989819
type: Question
tagged with: minimax
score: 0
has title: Trouble with Python generators in recursive implementation of minimax
answer count: 1
has body: I am working on an implementation of minimax algorithm to solve 2048. I am facing problems when iterating over a list of objects, and passing this value to recursive functions. The code is : def MAXIMIZE(state,deep): if deep == 10: return (None,greed(state)) tup = (None, -1000000) #maxChild, maxUtility moves = state.getAvailableMoves() #children by moves children = [] children.append(state.clone().move(m) for m in moves) for child in children: temp,utility = MINIMIZE(child,deep + 1) if utility &gt; tup[1]: tup = (child, utility) return tup def MINIMIZE(state,deep): if deep == 10: return (None, greed(state)) tup = (None, +10000000) cells = state.getAvailableCells() # this is where I get an error - "'generator' object has no attribute 'getAvailableCells'" children = [] children.append(state.clone().setCellValue(cell, 2) for cell in cells) for child in children: temp,utility = MAXIMIZE(child,deep + 1) if utility &lt; tup[1]: tup = (child,utility) return tup In the MINIMIZE function the line - cells = state.getAvailableCells() gives "'generator' object has no attribute 'getAvailableCells'" Can anyone please help me figure this out? (I am a student of physics and have limited knowledge of Python. I went to various existing questions but couldn't understand much.)
favorite count: 0
tagged with: python
tagged with: generator
type: AnsweredQuestion
tagged with: recursion
has answer: http://stackoverflow.com/a/48989819

http://stackoverflow.com/a/49062532
has comment: http://stackoverflow.com/comment/85131230
has comment: http://stackoverflow.com/comment/85179334
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85159577
has comment: http://stackoverflow.com/comment/85130284
has comment: http://stackoverflow.com/comment/85130658
has comment: http://stackoverflow.com/comment/85132777
has comment: http://stackoverflow.com/comment/85130760
answers question: http://stackoverflow.com/q/49062176
has comment: http://stackoverflow.com/comment/85131201
has comment: http://stackoverflow.com/comment/85130767
has comment: http://stackoverflow.com/comment/85130734
upvote count: 1
has comment: http://stackoverflow.com/comment/85174690
has body: Edit: one can also use merge to solve the problem. 10 times faster than the old approach. (Need to make sure "visit_date" and "calendar_date" are of the same format.) # don't need to `set_index` for date_info_df but select columns needed. merged_df.merge(date_info_df"calendar_date", "day_of_week", "holiday_flg", left_on="visit_date", right_on="calendar_date", how="left") # outer should also work The desired result will be at "day_of_week_y" and "holiday_flg_y" column right now. In this approach and the map approach, we don't use the old "day_of_week" and "holiday_flg" at all. We just need to map the results from data_info_df to merged_df. merge can also do the job because data_info_df's data entries are unique. (No duplicates will be created.) You can also try using pandas.Series.map. What it does is Map values of Series using input correspondence (which can be a dict, Series, or function) # set "calendar_date" as the index such that # mapping["day_of_week"] and mapping["holiday_flg"] will be two series # with date_info_df["calendar_date"] as their index. mapping = date_info_df.set_index("calendar_date") # this line is optional (depending on the layout of data.) merged_df.visit_date = pd.to_datetime(merged_df.visit_date) # do replacement here. merged_df["day_of_week"] = merged_df.visit_date.map(mapping["day_of_week"]) merged_df["holiday_flg"] = merged_df.visit_date.map(mapping["holiday_flg"]) Note merged_df.visit_date originally was of string type. Thus, we use merged_df.visit_date = pd.to_datetime(merged_df.visit_date) to make it datetime. Timings date_info_df dataset and merged_df provided by karlphillip. date_info_df = pd.read_csv("full_date_info_data.csv") merged_df = pd.read_csv("full_data.csv") merged_df.visit_date = pd.to_datetime(merged_df.visit_date) date_info_df.calendar_date = pd.to_datetime(date_info_df.calendar_date) cols = ["day_of_week", "holiday_flg"] visit_date = pd.to_datetime(merged_df.visit_date) # merge method I proprose on the top. %timeit …
has comment: http://stackoverflow.com/comment/85151816
has comment: http://stackoverflow.com/comment/85134181

http://stackoverflow.com/a/70055772
upvote count: 2
answers question: http://stackoverflow.com/q/49048111
has comment: http://stackoverflow.com/comment/134363147
downvote count: 0
has body: In my personal experience I've been using the OpenCV method. Try this code: import cv2 as cv def get_dur(filename): video = cv.VideoCapture(filename) fps = video.get(cv.CAP_PROP_FPS) frame_count = video.get(cv.CAP_PROP_FRAME_COUNT) seconds = frame_count / fps minutes = int(seconds / 60) rem_sec = int(seconds % 60) return f"{minutes}:{rem_sec}" print(get_dur("dafuck.mp4"))
type: Answer
score: 2

http://stackoverflow.com/comment/85629376
type: Comment
has text: This is incredible, I had mashed together a solution but wasn't happy with it so dropped the idea. This has re-inspired me! Thank you, Jason
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49308491

http://stackoverflow.com/comment/85008459
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49001385
has text: @rajn See my EDIT-1
score: 0

http://stackoverflow.com/comment/95099472
comment on: http://stackoverflow.com/a/49107899
score: 5
type: AnswerComment
has text: Also `twine check dist/*` per https://packaging.python.org/guides/making-a-pypi-friendly-readme/
type: Comment

http://stackoverflow.com/comment/85147830
type: Comment
has text: Thank you for your reply. However, it should print the IDs for each line, not only once..
type: AnswerComment
comment on: http://stackoverflow.com/a/49071245
score: 0

http://stackoverflow.com/q/49084530
accepted answer: http://stackoverflow.com/a/49084676
answer count: 3
has body: Basically, I'm messing around in Python (3) and I'm trying to define some functions to do some common tasks in single lines, using as less memory as possible For example, in video games, you might want a character to turn some degrees left/right, but not 0 degrees. So, given an integer x, how could you return a random integer between -x and +x` (inclusive) which isn't 0? Note, I'm going for one-liners using minimum memory. I'm posting an answer but I'd also like to know how other people would approach this. EDIT: This isn' school homework or anything, I'm just designing a video game and defining a few functions which will come in handy. I said no 'If's because I was wondering if it was possible, and if so, how. Thanks :-)
has answer: http://stackoverflow.com/a/49084777
downvote count: 0
has title: How can I randomly choose a number without using an 'If'?
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49084531
tagged with: python
has answer: http://stackoverflow.com/a/49084676
has answer: http://stackoverflow.com/a/49084531
has comment: http://stackoverflow.com/comment/85174519
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/85016261
type: Comment
type: QuestionComment
score: 0
has text: how do you define "maximum matrix size"?
comment on: http://stackoverflow.com/q/49005887

http://stackoverflow.com/q/48966135
has comment: http://stackoverflow.com/comment/84942292
favorite count: 0
has comment: http://stackoverflow.com/comment/84938299
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48969457
upvote count: 3
has comment: http://stackoverflow.com/comment/84941297
type: Question
has body: I am using Pandas Read Sql in Python for executing sql-statements in IBM DB2 and saving the response in pandas dataframes. Now I am trying to execute a sql-statement containing a non ASCII character, a letter from the Swedish alphabet: 'Å' (others are Å, Ä and Ö) but I am getting this error: "DatabaseError: Execution failed on sql 'SELECT * FROM DATA_CONFIG WHERE TAG_NAME='Å'': ibm_db_dbi::Error: Error occure during processing of statement" This is my code: import ibm_db import ibm_db_dbi import pandas as pd def sqlToFrame(sql): # Function for creating pandas dataframes from SQL-statements con = ibm_db.connect(connection_string, "", "") conn = ibm_db_dbi.Connection(con) return pd.read_sql(sql, conn) df = sqlToFrame("SELECT * FROM DATA_CONFIG WHERE TAG_NAME='Å'") I've tried executing the statement in the IDE in the IBM DB2 interface which works perfectly fine. Therefore I am figuring that the problem might be connected to how I establish the connection/the DB2 driver pandas uses. I have tried finding a way to set an encoding but can't find anything. How can I solve this? I also know this is possible because another package that builds upon ibm_db accept these characters. The characters are a from the ISO-8859-1 series
tagged with: ibm-cloud
has comment: http://stackoverflow.com/comment/84938433
tagged with: db2
has comment: http://stackoverflow.com/comment/84938451
has comment: http://stackoverflow.com/comment/84938916
accepted answer: http://stackoverflow.com/a/48969457
tagged with: pandas
tagged with: sql
answer count: 1
downvote count: 0
has title: Python Pandas Read SQL from IBM DB2 with non ASCII characters

http://stackoverflow.com/comment/84966934
type: QuestionComment
has text: AGT(M)MultiPlay B [ XX - XXXXXXXXXX - XXXXXX ] The game name here would be "MultiPlay Big Time 2" but due to the character limit it gets cut off.
comment on: http://stackoverflow.com/q/48980746
score: 0
type: Comment

http://stackoverflow.com/comment/106362219
type: Comment
comment on: http://stackoverflow.com/q/49064705
has text: This line `canvas = Image.new("RGB", (total_width, total_height), white)` please where is "Image" coming from?
score: 0
type: QuestionComment

http://stackoverflow.com/q/49072183
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/49072968
score: 0
answer count: 1
tagged with: python-3.x
has title: JSON - How to iterate nested dictionaries in a list
tagged with: python
has answer: http://stackoverflow.com/a/49072968
type: AnsweredQuestion
has body: I have the following JSON data in a file: { "Generic": { "main": [{ "one": "Main 1", "two": "Main 2" }], "rows": [ { "row1": "This is row 1-1", "row2": "This is row 2-1", "row3": "This is row 3-1" }, { "row1": "This is row 1-2", "row2": "This is row 2-2", "row3": "This is row 3-2" } ] } } I can access the values like so: import json with open(r'C:\generic.json') as json_data: json_data = json.load(json_data) for x in sorted(json_data): print (x) print ('main:') print (json_data[x]['main'][0]['one']) print (json_data[x]['main'][0]['two']) print ('rows:') print (json_data[x]['rows'][0]['row1']) print (json_data[x]['rows'][0]['row2']) print (json_data[x]['rows'][0]['row3']) print ('') for y in json_data[x]: print (json_data[x]['rows'][0]['row1']) This returns: My problem is how do I iterate all of the nested dictionaries in "rows" - in this case there are 2. You can see my sad attempt at for y in json_data[x]: Note: I access the "rows" data in the the 1st loop to show that it is accessible - but I need to figure out how to access those rows in a 2nd loop. Any help will be greatly appreciated :) EDIT: I am closer with the following - I am SO close but not sure what little piece I am missing: for x in sorted(json_data): print (x) print ('main:') print (json_data[x]['main'][0]['one']) print (json_data[x]['main'][0]['two']) print ('rows:') print (json_data[x]['rows'][0]['row1']) print (json_data[x]['rows'][0]['row2']) print (json_data[x]['rows'][0]['row3']) print ('') for r in json_data[x]['rows']: print (json_data[x]['rows'][0]['row1']) print (json_data[x]['rows'][0]['row2']) print (json_data[x]['rows'][0]['row3']) The for r in json_data[x]['rows']: recognizes the correct number of "rows" - whether 2 or 5o - but just returns the values from the 1st dictionary over and over :(
type: Question

http://stackoverflow.com/q/48967660
upvote count: 2
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48967794
has body: I have a 3D elastic collision simulation. I'd like to clear all of the sphere objects from my program from a button press. The documentation indicates that I should do the following: def clear_balls(): for ball in balls: ball.visible = False del ball This successfully makes the balls invisible in the scene, but they still take up memory and collide with balls that still exist. I want it completely removed. Trying this with a unique ball name this isn't part of a list as some have suggested still results in the same issue.
type: Question
tagged with: vpython
accepted answer: http://stackoverflow.com/a/48967794
tagged with: python-2.7
answer count: 1
score: 1
favorite count: 0
has title: VPython 6 - Object won't delete

http://stackoverflow.com/a/48965779
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48965137
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48965137
has body: Check if your are running the same version of the library and elasticsearch. Set something like elasticsearch>=6.0.0,&lt;7.0.0 in requirements.txt, depending on you ES version. You can get more info about requirements.txt here, and here about the versions available of the library. Use pip unistall to remove the elastic library and reinstall it in the correct version (related to your elasticsearch cluster version) with pip install -r requirements.txt
downvote count: 0
has comment: http://stackoverflow.com/comment/84946941
type: Answer

http://stackoverflow.com/a/62655876
has comment: http://stackoverflow.com/comment/119479697
score: 5
has body: Using groupby.agg() "aggrgeate" function: * DataFrameGroupBy.agg(arg, *args, **kwargs): aggregate using one or more operations over the specified axis. Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply df = pd.DataFrame({'numbers': [1, 2, 3, 6, 9], 'colors': ['red', 'white', 'blue', 'red', 'white']}, columns=['numbers', 'colors']) df.groupby('colors', as_index=True).agg({'numbers' : {"unique" : lambda x: set(x), "nunique" : lambda x : len(set(x))}})
answers question: http://stackoverflow.com/q/48979604
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84981690
type: Comment
type: QuestionComment
score: 1
has text: What are you mapping from and to?
comment on: http://stackoverflow.com/q/48988490

http://stackoverflow.com/comment/85209493
type: Comment
score: 0
has text: Oh sorry, I forgot about Frank. That's a root level file entry, so it should sit in the root directory.
type: QuestionComment
comment on: http://stackoverflow.com/q/49100389

http://stackoverflow.com/q/49034250
answer count: 1
downvote count: 0
tagged with: keras
has body: From the Keras Preprocessing ImageDataGenerator module, the flow_from_directory method is used to create an Iterator from a directory containing sub-directories of images. The Iterator runs indefinitely creating batches of images. My question is, does it iterate through every sample per epoch? For example, if I have 300 image total, and my batch size is 30, if I do 10 steps, does it iterate through every single sample once? Or is each step an independent random sample from the entire dataset? If we do iterate through every sample, what happens when I have a sample size not divisible by batch size (like 304 images)? At step 11, does the iterator know to get the last 4 samples first, then get another 26 samples from the whole dataset?
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Does Keras flow_from_directory iterate through every sample in a directory?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49059978
has comment: http://stackoverflow.com/comment/98887609
score: 2

http://stackoverflow.com/q/49063058
tagged with: pyspark
answer count: 11
tagged with: apache-spark
has answer: http://stackoverflow.com/a/62580213
has answer: http://stackoverflow.com/a/50007414
has answer: http://stackoverflow.com/a/73711851
has answer: http://stackoverflow.com/a/53221639
upvote count: 19
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55921339
has body: I have installed pyspark with python 3.6 and I am using jupyter notebook to initialize a spark session. from pyspark.sql import SparkSession spark = SparkSession.builder.appName("test").enableHieSupport.getOrCreate() which runs without any errors But I write, df = spark.range(10) df.show() It throws me an error --> Py4JError: An error occurred while calling o54.showString. Trace: py4j.Py4JException: Method showString([class java.lang.Integer, class java.lang.Integer, class java.lang.Boolean]) does not exist at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318) at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326) at py4j.Gateway.invoke(Gateway.java:272) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:214) at java.lang.Thread.run(Thread.java:745) I dont know why I am facing this issue. If I do, from pyspark import SparkContext sc = SparkContext() print(sc.version) '2.1.0'
tagged with: python
has answer: http://stackoverflow.com/a/49066051
has answer: http://stackoverflow.com/a/49911526
has answer: http://stackoverflow.com/a/60285385
has answer: http://stackoverflow.com/a/58792538
downvote count: 0
has answer: http://stackoverflow.com/a/61046589
has answer: http://stackoverflow.com/a/64719095
score: 19
type: Question
has title: Py4J error when creating a spark dataframe using pyspark

http://stackoverflow.com/comment/85136966
type: Comment
has text: Oh, I didn't know if statements could be used like that, now I can do for i in dictionary if condition else range(begin, end): .... Thank you very much for your answer :)
comment on: http://stackoverflow.com/a/49065742
type: AnswerComment
score: 0

http://stackoverflow.com/comment/136905135
comment on: http://stackoverflow.com/a/49039555
type: AnswerComment
score: 0
type: Comment
has text: It would be useful to convert a relative path to an absolute one. `import os` and `os.path.abspath("mydir/myfile.txt")` will accomplish this.

http://stackoverflow.com/a/49012288
answers question: http://stackoverflow.com/q/49010871
has body: As you say, adding .all() gives the result, so you need to add that to your dynamic lookup: field_value = getattr(self, field).all()
accepted answer of: http://stackoverflow.com/q/49010871
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/49029198
possible better answer: http://stackoverflow.com/a/49029237
score: 0
has answer: http://stackoverflow.com/a/49029237
has title: Django user object can not display
tagged with: object
has answer: http://stackoverflow.com/a/49029242
type: AnsweredQuestion
has body: The goal is to show a users images on their profile page. The current error message I am getting is "'Images' object is not iterable". views.py def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user': user, 'images': Images.objects.get(pk=pk)} return render(request, 've/cp/profile.html', args) profile.html {% if images %} {% for img in images %} &lt;img src="{{ img.image.url }}" class="float-left" style="max-width: 150px"&gt; {% endif %} {% else %} models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
accepted answer: http://stackoverflow.com/a/49029242
type: Question
answer count: 2
tagged with: django
tagged with: python

http://stackoverflow.com/a/48973813
has comment: http://stackoverflow.com/comment/112028319
has body: Since hello.py and world.py are in the same folder (aka package), you should import the Hello class in world.py as follow: from .hello import Hello As described in this thread: What does a . in an import statement in Python mean? The . is here to indicate the import from the current package.
has comment: http://stackoverflow.com/comment/84953118
type: Answer
answers question: http://stackoverflow.com/q/48973742
downvote count: 2
has comment: http://stackoverflow.com/comment/84966697
score: 5
upvote count: 7

http://stackoverflow.com/comment/85063186
type: AnswerComment
comment on: http://stackoverflow.com/a/49028483
type: Comment
has text: @ jezrael After double checking the data your solution is what I was looking for. Thanks!!
score: 0

http://stackoverflow.com/comment/85061384
has text: Welcome to SO! Please read [the following article](https://stackoverflow.com/help/how-to-ask) and edit your question accordingly
comment on: http://stackoverflow.com/q/49028537
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85081632
has text: The dictionary is this: dic {'C': '2', 'D': '2', 'E': '2', 'I': '2', 'M': '0'} I want an array of keys whose value is 2. So the result needs to be an array ['C','D','E','I']
comment on: http://stackoverflow.com/a/49038038
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49004407
has comment: http://stackoverflow.com/comment/85022736
type: Answer
answers question: http://stackoverflow.com/q/49004246
has body: The problem with the code you have posted lies in the use of os.path.join. In the documentation it says for os.path.join(path, *paths): If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component. In your case, the component /**/*.jpg is an absolute path, as it starts with a /. Consequently your initial input /Path/to/parent directory is being truncated by the call to the join function. (https://docs.python.org/3.5/library/os.path.html#os.path.join) I have locally tested the joining part with python3 and for me it is the case, that using os.path.join(any_path, "/**/*.pdf") returns the string '/**/*.pdf'. The fix for this error is: import glob2,os all_header_files = glob2.glob(os.path.join('Path/to/parent directory','**/*.jpg')) This returns the path 'Path/to/parent directory/**/*.jpg'
has comment: http://stackoverflow.com/comment/85022556
has comment: http://stackoverflow.com/comment/85013343
has comment: http://stackoverflow.com/comment/85013375
score: 0

http://stackoverflow.com/q/48982873
type: UnansweredQuestion
tagged with: python
has title: create stack using 2 queues
score: 1
has comment: http://stackoverflow.com/comment/84970610
tagged with: stack
has body: Hey guys I am having trouble with my first assignment in my data structures class, and was hopping someone could provide some insight on what I am doing wrong. I must create a stack that utilizes 2 queues for data storage. import Queue_PlistLR as queueList import Queue_PlistLR as queueList class Stack_2Queues(): def __init__(self, name, salary): self.items = [] self.name = name self.salary = salary def isEmpty(self): return len(self.items) == 0 def push(self, e): self._data.append(e) def pop(self): if self.is_empty: raiseEmpty("Stack is empty") return self._data.pop() def size(self): return len(self.items) def to_String(self): str_i = "" for e in self.items: str_i+=str(e)+" " return str_i.strip() def length(self): return len() def enqueue(self, item): self.items.append(item) def dequeue(self): if self.isEmpty(): raise Empty('Queue is empty') return self.items.pop(0) def employeeName(self): print("The employee is: ", self.name) def employeeSalary(self): print("Employees salary is", self.salary) s1 = Stack_2Queues = [["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000]] s1.employeeName() s1.employeeSalary() ***I know this is wrong, for the most part. but my question is this. For the stack I want to create 2 queues, one for employeeName and the other for employeeSalary, using 1 stack. Also when I try printing the name and salary from the stack (to see if it works) and I get "list has no attribute" error.*** So, here are my questions: 1) Excuse my illiteracy as this may sound stupid, but is my s1 variable the form of a stack? 2) Why am I getting the list has no attribute since I defined all methods, and called them?
upvote count: 1
tagged with: queue
type: Question
has answer: http://stackoverflow.com/a/48984188
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48993743
has answer: http://stackoverflow.com/a/59596090
linked to: http://stackoverflow.com/q/7867537
has body: Please help me with selecting a value from the dropdown. I was able to login to the website but unable to select a value from the dropdown list after logging in. I had tried few solutions/suggestions found online, but couldn't get that to work. Please see below for the code and error with HTML. HTML: Pixels Inches Millimeters Centimeters Code: from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys usernameStr = 'username' passwordStr = 'password' browser = webdriver.Chrome() browser.maximize_window() browser.get('mywebsite/') username = browser.find_element_by_id('username') username.send_keys(usernameStr) password = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID,'password'))) password.send_keys(passwordStr) logInButton = browser.find_element_by_id('login_button') logInButton.click() file_input1 = browser.find_element_by_id('reference') file_input2 = browser.find_element_by_id('candidate') file_input1.send_keys("filelocation on my drive") file_input2.send_keys("filelocaton on my drive") s1= Select(browser.find_element_by_id('highlightunits')) print(s1.options) for option in s1.options: s1.select_by_visible_text('Inches') Error: [<selenium.webdriver.remote.webelement.WebElement (session="3903b52d4ab75592fbd965a21424f192", element="0.5058773595053347-4")>, <selenium.webdriver.remote.webelement.WebElement (session="3903b52d4ab75592fbd965a21424f192", element="0.5058773595053347-5")>, <selenium.webdriver.remote.webelement.WebElement (session="3903b52d4ab75592fbd965a21424f192", element="0.5058773595053347-6")>, <selenium.webdriver.remote.webelement.WebElement (session="3903b52d4ab75592fbd965a21424f192", element="0.5058773595053347-7")>] Traceback (most recent call last): File "C:\Users\Des…
tagged with: dropdown
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84993328
has answer: http://stackoverflow.com/a/48994672
tagged with: select
has comment: http://stackoverflow.com/comment/85234190
tagged with: selenium
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84996684
type: Question
has title: Selecting value from dropdown using Python + Selenium
tagged with: automation
has answer: http://stackoverflow.com/a/70891232
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84995750

http://stackoverflow.com/q/49059592
score: 0
answer count: 2
has body: I am having an issue finding text inside this element. There are no errors when the driver starts. Is my syntax correct? (hidden) Have Tried driver.find_elements_by_xpath("//*[@id='contact-link']/span[2][contains(text(),' (hidden) ')]")
has answer: http://stackoverflow.com/a/49059738
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: xpath
tagged with: selenium-chromedriver
accepted answer: http://stackoverflow.com/a/49059738
tagged with: selenium
type: Question
has title: Issue finding xpath
possible better answer: http://stackoverflow.com/a/49064377
has answer: http://stackoverflow.com/a/49064377
has comment: http://stackoverflow.com/comment/85124507

http://stackoverflow.com/comment/85013997
score: 0
type: QuestionComment
type: Comment
has text: to be honest if you're going to be comparing every item with the next one you need to check if you're out of bounds. Otherwise, you could do `for item in start_sequence`, skip the rest of the code only the first time, store the current item in a variable and in the next iteration compare that variable to the new item the loop has taken
comment on: http://stackoverflow.com/q/49004682

http://stackoverflow.com/comment/85025915
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49010193
score: 0
has text: @Oli I'm sorry but that's not enough reason. If you can't create a [mcve] to the question you're asking, then the chances are you'll learn nothing from the answers that fix your code. Which makes the question a waste of time including your own.

http://stackoverflow.com/q/49046757
tagged with: segments
type: Question
upvote count: 2
tagged with: numpy
favorite count: 0
has title: timeit on separate cells different to a combined cell
tagged with: python
has body: I was performing some code timing of cells in jupyter notebook where I was writing to segments of a numpy array and found that breaking up the code produces a different processing time, compared to original combined code. The folowing is a minimal example code. First setting up some values: import numpy as np V=10000 K=1000 zrs=np.random.random(V) Then timing full code: %%timeit a=np.zeros(V*K) for n in range(0,K): a[n*V:(n+1)*V]=zrs this returns: 45.6 ms ± 2.82 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) However, if I run the code in separate cells, I get: %%timeit a=np.zeros(V*K) 307 µs ± 2.33 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) and, first declaring 'a': a=np.zeros(V*K) then running timeit on the second part of the code: %%timeit for n in range(0,K): a[n*V:(n+1)*V]=zrs 9.52 ms ± 214 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) To conclude running complete code i get ~46ms and running the code in separate segments I get ~10ms! Why? I am confused! What can I expect when running the code? Help appreciated :) Python 3.6.3, jupyter notebook 5.0.0
tagged with: jupyter-notebook
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/85102870
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85103605
tagged with: timeit

grayscale
tags question: http://stackoverflow.com/q/49116389
type: Tag
tag name: grayscale

http://stackoverflow.com/comment/124066747
has text: @[Sander Heinsalu](https://stackoverflow.com/users/2137029/sander-heinsalu) That probably depends on your OS. Apparently "Preferences" with MacOS and "Settings" with Windows.
comment on: http://stackoverflow.com/a/49097897
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85086336
comment on: http://stackoverflow.com/a/49039785
has text: Added some screenshots. It seems to be using ssh! Doesn't seem to make much sense.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85097188
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49046242
has text: You are matching consonants but not vowels.

http://stackoverflow.com/comment/85015317
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48996036
has text: Ok, will check that
score: 0

http://stackoverflow.com/comment/85244134
has text: Thanks! Only one small tweak: it was printing the entire array on a single row. `if not values: print('No data found.') else: df = DataFrame(data=values) writer = pd.ExcelWriter('Data.xlsx') df.to_excel(writer, 'Raw Data') writer.save()` I tried making the index property false, which hides the row index. Is there a way to do the column index, too? Thanks so much!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49118996

http://stackoverflow.com/a/48984994
has comment: http://stackoverflow.com/comment/84976184
has body: You do need to tell OpenCV that you're reading a color image, for example with this: image = imread(argv[1], CV_LOAD_IMAGE_COLOR); If you don't use it like that it will load the image grayscale by default. Please change the subject as this is not Matplotlib error but OpenCV. There are plenty of examples on the OpenCV documentation: https://docs.opencv.org/2.4/doc/tutorials/introduction/display_image/display_image.html
has comment: http://stackoverflow.com/comment/84976236
score: 0
has comment: http://stackoverflow.com/comment/84976167
answers question: http://stackoverflow.com/q/48984312
type: Answer
has comment: http://stackoverflow.com/comment/84975759

http://stackoverflow.com/a/49121222
score: 9
upvote count: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Yes, it's possible to learn from the negative examples -- it's implemented in spaCy because it's a key feature of our commercial annotation tool, Prodigy: https://prodi.gy To mark a span as "not PERSON", you can makes its label !PERSON. That should be all you need to do. There's currently no easy way to encode constraints like "not PERSON and not ORG" -- you would have to customise the cost functions, within spacy/syntax/ner.pyx The model can learn from annotations like "not PERSON" because spaCy's NER and parser both use transition-based imitation learning algorithms. At each word we're trying to predict which action to take, to transform the current state. The supervision comes from an oracle that tells us which actions will introduce new errors. If we know that some span of text isn't a person, the oracle can use that to mark some of the actions as costly. We'll have multiple zero-cost actions, but that's normal --- it happens a lot in the normal training anyway. You can learn more about how the entity recogniser works in this video: https://www.youtube.com/watch?v=sqDHBH9IjRU
accepted answer of: http://stackoverflow.com/q/49121064
answers question: http://stackoverflow.com/q/49121064

http://stackoverflow.com/a/48989384
answers question: http://stackoverflow.com/q/48989295
score: 0
has body: You can try let param = "anyThing" let request = NSMutableURLRequest(url: NSURL(string: "http://192.168.1.13:8000/api/?filters=\(param)")! as URL
type: Answer

http://stackoverflow.com/q/48974470
score: 1
type: Question
has comment: http://stackoverflow.com/comment/100084039
downvote count: 0
tagged with: .net
favorite count: 0
answer count: 1
has title: python for .net Module not found Error no module named Numpy
has answer: http://stackoverflow.com/a/74418456
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am trying to call Python functions from C# with Python.Runtime. I have used this example from the internet. When I try to run it , it says. no module named Numpy. Numpy is working very well under Python. Where am I going wrong? class Program { static void Main(string[] args) { using (Py.GIL()) { dynamic np = Py.Import("numpy"); dynamic sin = np.sin; Console.WriteLine(np.cos(np.pi * 2)); Console.WriteLine(sin(5)); double c = np.cos(5) + sin(5); Console.WriteLine(c); dynamic a = np.array(new List&lt;float&gt; { 1, 2, 3 }); // dynamic b = np.array(new List&lt;float&gt; { 6, 5, 4 }, Py.kw("dtype", np.int32)); Console.WriteLine(a.dtype); // Console.WriteLine(b.dtype); // Console.WriteLine(a * b); dynamic pd = Py.Import("pandas"); dynamic plt = Py.Import("matplotlib"); } Console.ReadKey();

http://stackoverflow.com/comment/85188813
comment on: http://stackoverflow.com/q/48991022
type: Comment
type: QuestionComment
has text: When I execute this code, balk1 is printed correct on the canvas. Circel1 is NOT
score: 0

http://stackoverflow.com/q/49028871
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85063739
has title: Tsne: fatal error C1083: Cannot open include file: 'cblas.h': No such file or directory
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: openblas
score: 2
has comment: http://stackoverflow.com/comment/105533618
has body: I want to install tsne in python. Running the command: pip install tsne results in the following error: tsne/bh_sne_src/quadtree.cpp(12): fatal error C1083: Cannot open include 'cblas.h': No such file or directory I have tried to install openBLAS through by following these instructions https://github.com/arrayfire/arrayfire/wiki/CBLAS-for-Windows. However, this did not resolve the problem.
type: Question
has comment: http://stackoverflow.com/comment/85062886
linked to: http://stackoverflow.com/q/39643043
downvote count: 0
has comment: http://stackoverflow.com/comment/85064657
has comment: http://stackoverflow.com/comment/85065071
favorite count: 0

http://stackoverflow.com/comment/126736178
comment on: http://stackoverflow.com/a/49597001
type: AnswerComment
score: 0
type: Comment
has text: I did the same as colin, changing the file name from _gdbm.cpython-39-x86_64-linux-gnu.so to _gdbm.cpython-310-x86_64-linux-gnu.so and setting permissions to rwxrwxr-x using chmod 775 _gdbm.cpython-310-x86_64-linux-gnu.so

http://stackoverflow.com/comment/85242833
score: 0
type: Comment
has text: @kjolnir Also, the words seem kind of sorted but not fully. When I glanced at them they seemed sorted but when I checked against `sorted(...)` they didn't seem to match. Maybe make a copy and use `random.shuffle` on them.
comment on: http://stackoverflow.com/a/49101740
type: AnswerComment

http://stackoverflow.com/q/49020334
has comment: http://stackoverflow.com/comment/85045927
has comment: http://stackoverflow.com/comment/85047827
has comment: http://stackoverflow.com/comment/85543136
has title: Trying to display image as black and white pixels only with matplotlib in Python
tagged with: python
type: Question
has body: I read a source file which contains coordinates and pixel values (-1 is white and 1 is black) as follows: x y pixel_value 0 0 -1 0 1 1 0 2 -1 I store the pixels in a numpy array called my_array (size: 100x100), and before I start performing some analysis on the picture I print it using the command: plt.imshow(my_array, cmap="Greys") The problem is that the image that is printed is not just black and white pixels, it also shows some gray levels. I have tried changing the -1s back to 0 sweeping thru the array, but the resulting image still shows gray pixels. I am really baffled by this. Are these just artificial artifacts, or are they for real ? Why does the zoom in the original png file does not show any gray values no matter how close I get ? Examination of all the values in the original list and array shows only the integers 1 and -1. Any suggestions are appreciated.
score: 0
has comment: http://stackoverflow.com/comment/85056336
has comment: http://stackoverflow.com/comment/85047842
tagged with: matplotlib
tagged with: numpy
answer count: 0
type: UnansweredQuestion

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/49013010
tag name: qpushbutton

http://stackoverflow.com/comment/85163235
has text: https://matplotlib.org/users/annotations.html -- the annotation is in a different coordinate system?
score: 0
comment on: http://stackoverflow.com/q/49078309
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49115367
downvote count: 0
type: Answer
has body: Here is a vectorized approach using argsort. It uses a strategy similar to your avoid-full-scan idea: import numpy as np def find_gt(ref, data, incl=True): out = np.empty(len(ref) + len(data) + 1, int) total = (data, ref) if incl else (ref, data) out[1:] = np.argsort(np.concatenate(total), kind='mergesort') out[0] = -1 split = (out &lt; len(data)) if incl else (out &gt;= len(ref)) if incl: out[~split] -= len(data) split[0] = False return np.maximum.accumulate(np.where(split, -1, out))[split] + 1 def find_intervals(ref, data, span, incl=(True, True)): index_min = find_gt(ref, data, incl[0]) index_max = len(ref) - find_gt(-ref[::-1], -span-data[::-1], incl[1])[::-1] return index_min, index_max ref = np.sort(np.random.randint(0,20000,(10000,))) data = np.sort(np.random.randint(0,20000,(10000,))) span = 2 idmn, idmx = find_intervals(ref, data, span, (True, True)) print('checking') for d,mn,mx in zip(data, idmn, idmx): assert mn == len(ref) or ref[mn] &gt;= d assert mn == 0 or ref[mn-1] &lt; d assert mx == len(ref) or ref[mx] &gt; d+span assert mx == 0 or ref[mx-1] &lt;= d+span print('ok') It works by indirectly sorting both sets together finding for each time in one set the preceding time in the other this is done using maximum.reduce the preceding steps are applied twice, the second time the times in one set are shifted by span
score: 1
answers question: http://stackoverflow.com/q/49106371
upvote count: 1

http://stackoverflow.com/q/48963659
tagged with: celery
type: Question
score: 1
has comment: http://stackoverflow.com/comment/84937785
has answer: http://stackoverflow.com/a/62140142
has comment: http://stackoverflow.com/comment/84936861
has comment: http://stackoverflow.com/comment/84937741
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84938458
has title: Django celery beat attributeError: 'NoneType' object has no attribute 'localize'
favorite count: 0
tagged with: redis
tagged with: python
has comment: http://stackoverflow.com/comment/84938166
has body: I'm trying to get periodic tasks running with my Django project as per this tutorial. When running celery beat with the command below: celery -A proj beat -l info -S django I get the following error: celery beat v4.0.2 (latentcall) is starting. __ - ... __ - _ LocalTime -&gt; 2018-02-24 13:42:37 Configuration -&gt; . broker -&gt; redis://localhost:6379// . loader -&gt; celery.loaders.app.AppLoader . scheduler -&gt; django_celery_beat.schedulers.DatabaseScheduler . logfile -&gt; [stderr]@%INFO . maxinterval -&gt; 5.00 seconds (5s) [2018-02-24 13:42:37,244: INFO/MainProcess] beat: Starting... [2018-02-24 13:42:37,245: INFO/MainProcess] Writing entries... [2018-02-24 13:42:37,255: CRITICAL/MainProcess] beat raised exception &lt;type 'exceptions.AttributeError'&gt;: AttributeError("'NoneType' object has no attribute 'localize'",) Traceback (most recent call last): File "...lib/python2.7/site-packages/celery/apps/beat.py", line 107, in start_scheduler service.start() File "...lib/python2.7/site-packages/celery/beat.py", line 528, in start humanize_seconds(self.scheduler.max_interval)) File "...lib/python2.7/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "...lib/python2.7/site-packages/celery/beat.py", line 572, in scheduler return self.get_scheduler() File "...lib/python2.7/site-packages/celery/beat.py", line 567, in get_scheduler lazy=lazy, File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 183, in __init__ Scheduler.__init__(self, *args, **kwargs) File "...lib/python2.7/site-packages/celery/beat.py", line 204, in __init__ self.setup_schedule() File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 191, in setup_schedule self.install_default_entries(self.schedule) File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 290, in schedule self._schedule = self.all_as_schedule() File "...lib/python2.7/site-packages/django_celery_beat/sc…
has comment: http://stackoverflow.com/comment/84937961
has comment: http://stackoverflow.com/comment/84937779
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84937617
tagged with: django

http://stackoverflow.com/q/48993046
has comment: http://stackoverflow.com/comment/84991375
score: 0
answer count: 1
has body: I need some kinds of advice. In my models I have teachers, students and courses. Each teacher has its own courses. I was wondering how can I allow students to visualize my courses, as a teacher. In the teacher classroom (teacher control panel), I listed his courses, and near each course I made an enroll students button. So when that is clicked on, it will redirect to the course's slug page and there he will be able to search for his students (like classroom/engineering/enroll). This is what I done so far. Now I was thinking of some kind of boolean value checkbox near each student name and when all desired students are checked, below he will have an Enroll button, which will allow those students to visualize that course page. My problem is, how do I implement this enroll exactly ? What is a good approach ? Please advice me.
has title: Need advice on implementing feature regarding Django models
accepted answer: http://stackoverflow.com/a/49003783
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49003783
has comment: http://stackoverflow.com/comment/84993006
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/49003113

http://stackoverflow.com/comment/85170442
score: 0
comment on: http://stackoverflow.com/a/49082449
has text: on file can be different number of dataframes between 5 and 10 but structure of file sesame separator "!" headers row starts whit "*"
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85164688
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49079298
type: Comment
has text: @wjandrea OP didn't specify a version, but is using Python 3 per the print statement. If you're using 3, there's no reason you should still be on 3.4.

http://stackoverflow.com/comment/85160050
has text: I found something much more straightorward, but def +1 for this.
comment on: http://stackoverflow.com/a/49077126
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48986740
answer count: 1
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10507230
duplicate of: http://stackoverflow.com/q/10507230
type: Question
has body: my .txt file is below Pyhton is open source language its a freeware it has lot of in built modules python is easiest what should I do to insert two lines below its freeware lines and move the remaining data below that inserted lines, as shown below, Pyhton is open source language its a freeware Hi my name is shubham it has lot of in bult modules python is easiest I have tried following code but its appending the new lines at last in file file_to_write = r"file.txt" with open(file_to_write,'a') as fw: fw.write('Hi\n') fw.write('my name is shubham')
has title: How can I insert number of lines in between the .txt file and move or append its data below that inserted lines using python?
has answer: http://stackoverflow.com/a/48986938
score: 0

http://stackoverflow.com/comment/85537394
score: 0
type: Comment
type: QuestionComment
has text: Yeah, it's resolver, my bad.
comment on: http://stackoverflow.com/q/49084322

glob
tags question: http://stackoverflow.com/q/49086903
tags question: http://stackoverflow.com/q/49047402
tags question: http://stackoverflow.com/q/49009354
tags question: http://stackoverflow.com/q/49092307
tag name: glob
type: Tag

http://stackoverflow.com/comment/85184323
score: 1
comment on: http://stackoverflow.com/q/49089349
has text: what is your `lablels_list`? Basically, you should just add input and desired output to the question
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49014523
type: Answer
downvote count: 0
score: 1
has body: Using sliding window algorithm and the third-party more_itertools.windowed tool: import statistics as stats import more_itertools as mit lst = [3, 5, 2, 7, 5, 3, 6, 8, 4] [stats.mean(sorted(w)[1:]) for w in mit.windowed(lst, 3)] # [4, 6, 6, 6, 5.5, 7, 7] See also @Maarten Fabré's related post.
answers question: http://stackoverflow.com/q/49000803
upvote count: 1

http://stackoverflow.com/a/56139746
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49045762
downvote count: 0
has body: For Python 2.7, you can use pg8000, but it lacks some features and, in my experience, a little unstable. For Python 3.7, you can use psycopg2. Seems that the docs examples are for MySQL and not for PostgreSQL, but you can see them here.

http://stackoverflow.com/comment/84999029
type: Comment
type: QuestionComment
has text: Put a timestamp in the filename. You can use the `str.format()` method to substute the time into the command line.
score: 0
comment on: http://stackoverflow.com/q/48996831

http://stackoverflow.com/a/49055880
has comment: http://stackoverflow.com/comment/85117102
has comment: http://stackoverflow.com/comment/85116518
score: 1
has comment: http://stackoverflow.com/comment/85118055
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49055559
type: Answer
accepted answer of: http://stackoverflow.com/q/49055559
downvote count: 0
has comment: http://stackoverflow.com/comment/85116971
has body: First lets convert the dictionary of lists into a dictionary of sets. SystemDictu4 = {'System 1': ['test1@test.com', 'test2@test.com', 'test5@test.com'], 'System 2': ['test1@test.com', 'test7@test.com', 'test55@test.com'], 'System 3': ['test1@test.com', 'test23@test.com', 'test55@test.com'], 'System 4': ['test1@test.com', 'test23@test.com', 'test55@test.com']} System = {k,set(v) for k,v in SystemDictu4.items()} I recommend using a set since you will only need a single instance of each email address per system key. Once we have the larger system converted to a dictionary of sets, then we can use the nature of a set to unite the information from other systems. def add_dict(SystemDictFrom, SystemDictTo, number_of_systems): for system in sorted(SystemDictFrom, key = lambda a: len(SystemDictFrom.get(a)))[:number_of_systems]: if system in SystemDictTo: SystemDictTo[system].union(SystemDictFrom[system]) else: SystemDictTo[system] = SystemDictFrom[system] In the function above, I'm using SystemDictFrom as the dictionary of lists or sets that will add values to the larger dictionary, SystemDictTo. You might call that function with the following: # This will add the three least populated systems from SystemDicto3 to SystemDictu4 add_dict(SystemDicto3, SystemDictu4, 3)
has comment: http://stackoverflow.com/comment/85117275
has comment: http://stackoverflow.com/comment/85117340

http://stackoverflow.com/a/49044250
answers question: http://stackoverflow.com/q/49043009
score: 0
type: Answer
has body: You can also do it in one line. cust = {'lat': 40, 'lon': 80} out = sorted(sdata, key=lambda data: distance(data['lat'], data['lon'], cust['lat'], cust['lon'])) print(out) Output: [{'lat': 40.42, 'lon': 86.123}, {'lat': 37.82, 'lon': 86.142}, {'lat': 39.66, 'lon': 87.11}, {'lat': 38.88, 'lon': 87.251}, {'lat': 39.78, 'lon': 89.336}, {'lat': 41.35, 'lon': 90.21}]

http://stackoverflow.com/comment/85082883
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49038229
has text: It just comes up with "not in users" when relying on the 'user' variable being global, and when I put user in () it said that it was missing (missing 1 positional argument)
score: 0

http://stackoverflow.com/q/49051558
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/973439
linked to: http://stackoverflow.com/q/29010203
type: Question
has body: How can I set DONT_FRAGMENT flag in IP header using python sockets? The following code socket.setsockopt(socket.IPPROTO_IP, socket.IP_DONTFRAG, 1) gives me this error: AttributeError: 'module' object has no attribute 'IP_DONTFRAG' Anyone has an idea? def create_sender_session(self): logging.debug("Create Sender Session") if (self.send_ip_ver == 6 or self.resp_ip_ver == 6): self.sender_socket = socket.socket( socket.AF_INET6, socket.SOCK_DGRAM) self.sender_socket.setsockopt( socket.IPPROTO_IPV6, socket.IPV6_TCLASS, self.tos) self.sender_socket.setsockopt( socket.IPPROTO_IPV6, socket.IPV6_UNICAST_HOPS, self.ttl) else: self.sender_socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) self.sender_socket.setsockopt( socket.SOL_IP, socket.IP_TTL, self.ttl) self.sender_socket.setsockopt( socket.IPPROTO_IP, socket.IP_TOS, self.tos) self.sender_socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sender_socket.bind((self.send_addr, self.send_port)) logging.info('Sender started: {}:{}'.format( self.send_addr, self.send_port))
answer count: 2
has answer: http://stackoverflow.com/a/78849911
downvote count: 0
has comment: http://stackoverflow.com/comment/126813721
tagged with: setsockopt
has answer: http://stackoverflow.com/a/71720511
has comment: http://stackoverflow.com/comment/126864071
has comment: http://stackoverflow.com/comment/85132920
favorite count: 0
has comment: http://stackoverflow.com/comment/85107974
type: UnansweredQuestion
tagged with: sockets
tagged with: python
tagged with: ip-protocol
has title: How to set socket option IP_DONTFRAG in python?

http://stackoverflow.com/comment/85205630
score: 0
type: Comment
type: QuestionComment
has text: You could also, use a list of `15` `int` (*after all there are no unsigned integers in python AFAIK*) items and interpret it in [tag:c] the way you need, or simple pass a pointer back and fort. Are you familiar with python extensions in [tag:c]?
comment on: http://stackoverflow.com/q/49100167

http://stackoverflow.com/a/48997248
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48996597
upvote count: 1
answers question: http://stackoverflow.com/q/48996597
has body: You may use re.sub: re.sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. with a regex that matches stopwords as whole words and email-like substrings. from nltk.corpus import stopwords result = re.sub(r"[\w.-]+@[\w.-]+|\b(?:{})\b".format("|".join(set(stopwords.words('english')))), '', Xtrain_tfidf) Note the r'' prefix that defines a raw string literal where \ defines a literal backslash and \b is thus treated as a word boundary, not a backspace char. The pattern will match: [\w.-]+@[\w.-]+ - 1+ word, . or - chars, followed with @ and then again 1+ word, . or - chars | - or \b(?:and|or|not|a|an|is|the|of|like)\b - any of the alternatives in the non-capturing alternation group as whole words as \b is a word boundary.

http://stackoverflow.com/q/49030691
has answer: http://stackoverflow.com/a/49031600
has title: Assign one list with variables to other list with data
tagged with: python
has comment: http://stackoverflow.com/comment/85066687
has comment: http://stackoverflow.com/comment/85065735
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85065849
has comment: http://stackoverflow.com/comment/85065782
has answer: http://stackoverflow.com/a/49030941
has body: I want to assign folder names on dirs list to variables from vars list. Main problem is that var have stable number of items, but dirs can be changed by user. import os, sys path = "C:\BAR_PREK" dirs = os.listdir( path ) vars = ['VAR0.Value', 'VAR1.Value', 'VAR1.Value', 'VAR3.Value', 'VAR4.Value', 'VAR5.Value', 'VAR6.Value'] I was written stupid code like this: VAR0.Value = dirs[0] VAR1.Value = dirs[1] VAR2.Value = dirs[2] &lt;...&gt; But if we get empty dirs[x] value, it causes an error.
has comment: http://stackoverflow.com/comment/85065762
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/49055741
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/75986759
type: UnansweredQuestion
tagged with: python
has body: Introduction : I am working on audio fingerprinting and having some doubts regarding peak detection in the spectrogram, my input is a wav file with spectrogram as : The method I'm implementing is given here Problem : The peaks returning from the get_2Dpeaks() method are not overlapping with the above spectrogram. On different files the plot changes drastically. for the above file used, output of get_2D_peaks() is : It seems like I'm not fitting the signal data well, does anyone have any ideas or thoughts on how can I find the peaks in the spectrogram and also plot them ?
score: 2
upvote count: 2
tagged with: signal-processing
type: Question
has title: Finding peaks in audio spectrogram
tagged with: audio-fingerprinting

http://stackoverflow.com/q/49103333
tagged with: permutation
has comment: http://stackoverflow.com/comment/85211849
favorite count: 0
tagged with: combinatorics
has comment: http://stackoverflow.com/comment/85211915
has comment: http://stackoverflow.com/comment/85211836
tagged with: python
has comment: http://stackoverflow.com/comment/85212099
has comment: http://stackoverflow.com/comment/85212041
tagged with: big-o
score: 2
has body: I'm attempting to compute the number of possible permutations of pixels in an hdmi display which I know to be discrete and finite, however I'm having trouble conceptualizing the big-O notation and/or processing power needed. I have the following function that works for 4 digit numbers: def permutations(num): var = num for i in range(num): var *= 3 return var I need to apply this function to a number 2073600, however my python interpreter stops. Is there a way this can be easily done or the function adapted to use concurency?
has comment: http://stackoverflow.com/comment/85211832
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85211929
upvote count: 2
has answer: http://stackoverflow.com/a/51219495
accepted answer: http://stackoverflow.com/a/51219495
has comment: http://stackoverflow.com/comment/85212030
type: Question
has comment: http://stackoverflow.com/comment/85211778
has comment: http://stackoverflow.com/comment/85211997
has title: How long would it take or is it possible to calculate permutations in python given a 6 digit number?
tagged with: math
has comment: http://stackoverflow.com/comment/85211907
has comment: http://stackoverflow.com/comment/85212000
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85211954

http://stackoverflow.com/a/49100762
upvote count: 1
score: 1
has body: You might be looking for re.split: import re article_dict = {} with open('inp.txt') as f: for line in f.readlines()[1:-1]: info = re.split(r'=',line.strip()) article_dict[info[0]] = info[1] I'm assuming you will need to get rid of the braces and commas at the end, which is just a simple task of replacing or slicing. {'title': '{An epidemiological study to establish the prevalence of urinary symptoms and felt need in the community: the Leicestershire MRC Incontinence Study},', 'author': '{Perry, Sarah and Shaw, Christine and Assassa, Philip and Dallosso, Helen and Williams, Kate and Brittain, Katherine R and Mensah, Fiona and Smith, Nigel and Clarke, Michael and Jagger, Carol and others},', 'journal': '{Journal of public health},', 'volume': '{22},', 'number': '{3},', 'pages': '{427--434},', 'year': '{2000},', 'publisher': '{Oxford University Press}'}
answers question: http://stackoverflow.com/q/49100697
downvote count: 0
type: Answer

http://stackoverflow.com/a/48980381
has comment: http://stackoverflow.com/comment/84966109
has comment: http://stackoverflow.com/comment/84966323
has body: If your words don't have any spaces, or you can change the separator value between word and value to something unique, you can use pandas. Example script: import pandas as pd df = pd.read_csv(r"test.txt", sep=' ', header=None, names=['Word', 'Value']) print(df.head()) # returns: # # Word Value # 0 tasty 2.52 # 1 gracious 2.52 # 2 joyful 2.64 Then if you need the values to pass to something else, df.values returns a numpy array of the values: print(df.values) # returns: # # [['tasty', 2.52] # ['gracious', 2.52] # ['joyful', 2.64]] edit: Since you can't use pandas, just open the file and iterate through the lines directly. You'll have to implement error catching as needed, but here's a simple example: with open('test.txt', 'r') as f: contents = f.readlines() {word: value for word, value in [line.rstrip('\n').split(' ') for line in contents]}
score: 0
has comment: http://stackoverflow.com/comment/84966280
type: Answer
answers question: http://stackoverflow.com/q/48980291
has comment: http://stackoverflow.com/comment/84965945
has comment: http://stackoverflow.com/comment/84966190

http://stackoverflow.com/q/48988841
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I want to access column 3 values i.e Total_network's_Disbelief column based on indexes from index list and have to find out average of that values. from OutCSV.csv link. index contains values [0, 7, 14, 21, 28, 35, 42, 49, 56]. list1 contains first column Time in csv file col=3 values=[] with open('OutCSV.csv') as csvfile: reader = csv.DictReader(csvfile) for x in range(0,highest): if list1[x] == 70: index.append(x) #print(index) for x in range(0,len(index)): print(index[col]) values.append(int(index[col])) csum = sum(values) cavg = sum(values)/len(values) print("Sum of column %d: %f" % (col, csum)) print("Avg of column %d: %f" % (col, cavg))
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85009649
score: 0
has title: how to access column values based on other column values in CSV and find average of it
has answer: http://stackoverflow.com/a/49002729
answer count: 1
accepted answer: http://stackoverflow.com/a/49002729

http://stackoverflow.com/q/49101935
has comment: http://stackoverflow.com/comment/85221733
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85227797
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49230188
downvote count: 1
type: Question
has title: Polynomial regression in Python using sklearn, numpy and matplotlib
has comment: http://stackoverflow.com/comment/85210853
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85219861
has answer: http://stackoverflow.com/a/49230188
score: 0
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85226759
tagged with: python
has body: I'm trying to make a small program that will plot a graph with best fit line and that will predict the COST value based on inputted SIZE value. I always get this error, and I do not know what it means: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). No handles with labels found to put in legend. This is the graph that I get (red), and I think that curve should look like green curve that i have draw. And finally, program makes prediction only when I exit the graph. What am I doing wrong? This is the code: import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt size=[[1],[2],[3],[4],[5],[7],[9],[10],[11],[13]] cost=[[10],[22],[35],[48],[60],[80],[92],[111],[118],[133]] def predict(size,cost,x): dates=np.reshape(size,(len(size),1)) svr_poly=SVR(kernel="poly",C=1e3, degree=2) svr_poly.fit(size,cost) plt.scatter(size,cost, color="blue") plt.plot(cost, svr_poly.predict(cost), color="red") plt.xlabel("Size") plt.ylabel("Cost") plt.title("prediction") plt.legend() plt.show() predictedcost=predict(size,cost,7) print(predictedcost)

http://stackoverflow.com/q/48997028
score: -1
tagged with: python-3.x
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/84999975
has answer: http://stackoverflow.com/a/48997099
has comment: http://stackoverflow.com/comment/84999672
has answer: http://stackoverflow.com/a/48997098
has comment: http://stackoverflow.com/comment/84999426
has body: I am looking for a way to split a complex windows command string like: "C:\\DOCUME~1\\&lt;USER&gt;~1\\LOCALS~1\\Temp\\is-M186E.tmp\\one.exe C:\\two.exe\" Track=\"0011011000\"\"" (one process starting another process with options) in order to obtain the first executable file name, e.g. one.exe. Since those strings come from various logs, they can be very complex and I don't know if there will be white spaces in the directory names. Does anyone have a clue on how to do this? I am using python 3 on a linux machine. Edit: OK sorry, I was misleading, I don't know a priori the file extension. It may not be an .exe
has comment: http://stackoverflow.com/comment/84999502
upvote count: 0
has comment: http://stackoverflow.com/comment/84999522
type: UnansweredQuestion
has title: Python split complex windows command string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84999767
tagged with: python

http://stackoverflow.com/q/49037998
answer count: 1
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: In Django, how to make selecting a drop-down option automatically submit a form?
type: Question
tagged with: javascript
tagged with: jquery
has answer: http://stackoverflow.com/a/49038033
accepted answer: http://stackoverflow.com/a/49038033
has body: I'm trying to implement a form which pre-populates fields based on another field. As a starting point, I'd like to make the form 'auto-submit' when an option from a drop-down menu is selected. I've tried the following template: {% csrf_token %} {% for field in form %} {% if field.name == "checkin_type" %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% else %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endif %} {% endfor %} where the view is based on Django's generic CreateView: from django.views import generic from .models import CheckIn class CheckInCreate(generic.CreateView): model = CheckIn fields = '__all__' and the models are from django.db import models from django.urls import reverse class CheckInType(models.Model): title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) def __str__(self): return self.title class CheckIn(models.Model): checkin_type = models.ForeignKey(CheckInType, null=True, on_delete=models.CASCADE) title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) notes = models.TextField(blank=True) # Scheduling requested_date = models.DateField(blank=True, null=True) completed_date = models.DateField(blank=True, null=True) def get_absolute_url(self): return reverse('checkin-detail', kwargs={'pk': self.id}) def save(self, *args, **kwargs): if self.checkin_type: if not self.title: self.title = self.checkin_type.title if not self.description: self.description = self.checkin_type.description super().save(*args, **kwargs) However, if I actually select a drop-down menu option in the browser, nothing happens. Can someone explain why this is not working?
score: 0

http://stackoverflow.com/q/49013793
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85090266
tagged with: pybuilder
has title: PyBuilder can't find src module when running from virtualenv?
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91707769
has body: Here's my build.py: import os import shutil import subprocess from pybuilder.core import use_plugin, init, task, Author use_plugin('python.core') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin('python.install_dependencies') use_plugin('pypi:elasticsearch') authors = [Author('eagle', 'email')] version = '1.0' description = 'Pipeline thing test' requires_python = '&gt;=3.0' default_task = ['install_dependencies', 'publish', 'setup', 'analyze'] @init def initialize(project): project.build_depends_on('elasticsearch') project.set_property('dir_source_unittest_python','tests') project.set_property('dir_source_main_python','src') project.set_property('unittest_module_glob','test_*') project.set_property('coverage_branch_partial_threshold_warn ',80) project.set_property('coverage_threshold_warn',80) project.set_property('coverage_break_build',False) project.set_property('distutils_use_setuptools',True) project.set_property('distutils_classifiers',['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Pipeline', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6']) @task def setup(): subprocess.check_output(['python3.6','target/dist/pythonutilities-1.0/setup.py', 'install']) It's specifically looking for the test directory under projectDir/tests as specified in project.set_property('dir_source_unittest_python','tests') And it does look there and find the correct test file: File "/Users/adc1blz/Desktop/Work/pythonutilities/tests/test_elastic_controller.py", line 4, in &lt;module&gt; But I still receive the following error: ImportError: Failed to import test module: test_elastic_controller Traceback (most recent call last): File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "/Users/adc1blz/Desktop/Work/pythonutil…
downvote count: 0
favorite count: 0
tagged with: build-tools
tagged with: python

http://stackoverflow.com/comment/85015251
score: 0
type: AnswerComment
has text: jpg files are in nested subdirectories which are in NewFolder directory
comment on: http://stackoverflow.com/a/49004537
type: Comment

http://stackoverflow.com/a/49001261
has comment: http://stackoverflow.com/comment/85411089
has body: Okay, you will need to create a marker to defined consecutive records,then groupby and drop duplicates: df['StartDate'] = pd.to_datetime(df['StartDate']) df['EndDate'] = pd.to_datetime(df['EndDate']) consec = (df.groupby('Key').apply(lambda x: x.StartDate - x.EndDate.shift(1) &gt;= pd.Timedelta('3 day')) .cumsum().reset_index(drop=True)) (df.groupby(['Key',consec]) .agg({'StartDate':'min','EndDate':'max'}) .reset_index() .drop_duplicates('Key', keep='last') .drop('level_1', axis=1)) Output: Key StartDate EndDate 0 A 2015-01-01 2018-12-31 2 B 2016-07-15 2018-12-31
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85074584
type: Answer
has comment: http://stackoverflow.com/comment/85086950
accepted answer of: http://stackoverflow.com/q/49000384
upvote count: 3
has comment: http://stackoverflow.com/comment/85086857
answers question: http://stackoverflow.com/q/49000384
has comment: http://stackoverflow.com/comment/85074449
has comment: http://stackoverflow.com/comment/85414781

http://stackoverflow.com/comment/85172042
has text: Possible duplicate of [Python BeautifulSoup give multiple tags to findAll](https://stackoverflow.com/questions/20648660/python-beautifulsoup-give-multiple-tags-to-findall)
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49083438

http://stackoverflow.com/a/49333151
accepted answer of: http://stackoverflow.com/q/48997389
type: Answer
answers question: http://stackoverflow.com/q/48997389
score: 5
upvote count: 5
downvote count: 0
type: AcceptedAnswer
has body: If you set the language in the setting of your app in wit console to Persian, that should works! You can alternatively use: curl -XPOST 'https://api.wit.ai/speech' -i -L -H 'Authorization: Bearer YOURAPPTOKEN' -H "Content-Type: audio/wav" --data-binary "@sample.wav" which returns the JSON of the recognized text, intent, and entities.

http://stackoverflow.com/comment/85159220
has text: I suppose I should extend my question to ask: Can I avoid this initial excessive memory usage with a parameter setting of `genfromtxt`, or from using a different function? I was initially using pandas to read the data file and that was even worse (slower and used even more memory).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49076386
type: QuestionComment

http://stackoverflow.com/q/48992197
upvote count: 3
has comment: http://stackoverflow.com/comment/84990517
possible better answer: http://stackoverflow.com/a/48992496
type: Question
has comment: http://stackoverflow.com/comment/84990358
score: 3
has comment: http://stackoverflow.com/comment/84989654
has title: Remove only the last occurance of the words from string
answer count: 2
has comment: http://stackoverflow.com/comment/84989477
has comment: http://stackoverflow.com/comment/84989701
downvote count: 0
accepted answer: http://stackoverflow.com/a/48993130
tagged with: string
has answer: http://stackoverflow.com/a/48992496
favorite count: 0
linked to: http://stackoverflow.com/q/40239249
has comment: http://stackoverflow.com/comment/84990117
has body: I have a string and an array of phrases. input_string = 'alice is a character from a fairy tale that lived in a wonder land. A character about whome no one knows much about' phrases_to_remove = ['wonderland', 'character', 'no one'] Now what I want to do is, remove the last occurrences of the words in the array phrases_to_remove from the input_string. output_string = 'alice is a character from a fairy tale that lived in a. A about whome knows much about' I've written down a method that takes in the input string and either an array or just a string to replace and have used the rsplit() to replace the phrases. def remove_words_from_end(actual_string: str, to_replace, occurrence: int): if isinstance(to_replace, list): output_string = actual_string for string in to_replace: output_string = ' '.join(output_string.rsplit(string, maxsplit=occurrence)) return output_string.strip() elif isinstance(to_replace, str): return ' '.join(actual_string.rsplit(to_replace, maxsplit=occurrence)).strip() else: raise TypeError('the value "to_replace" must be a string or a list of strings') The issue with the code is, I can't remove the words that have a space mismatch. For example wonder land and wonderland. Is there a way I can do it without compromising much on performance?
has comment: http://stackoverflow.com/comment/84989731
tagged with: python
has answer: http://stackoverflow.com/a/48993130
has comment: http://stackoverflow.com/comment/84989570
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84989627
has comment: http://stackoverflow.com/comment/84990254

http://stackoverflow.com/q/49085712
has comment: http://stackoverflow.com/comment/85177206
type: Question
upvote count: 2
answer count: 1
downvote count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/85366395
tagged with: python
has comment: http://stackoverflow.com/comment/85176827
has answer: http://stackoverflow.com/a/49085722
type: UnansweredQuestion
score: 1
has title: Replacing all characters of a given string with a specific single character python with no loops
duplicate of: http://stackoverflow.com/q/33664190
has body: str0 = input("Enter str: ") str0 = str0.replace(str0, '_') print(str0) I need to replace each one of the characters without using loops or conditions

http://stackoverflow.com/q/48997418
linked to: http://stackoverflow.com/q/8905501
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/49003956
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has title: What is the most efficient way to get the upper triangle of a symmetric matrix in Tensorflow/Keras?
has comment: http://stackoverflow.com/comment/85012303
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49003956
has body: I have an intermediate model that outputs symmetric arrays. Those arrays are then used as input to another model. I'd like to just flatten the arrays and discard the lower triangles, since they're symmetric. Is there a best/most efficient way to do this? Edit: I want the triangle extraction to be handled similar to any other Keras layer, so that the output of the first model can be input directly to the second model and trained end-to-end.
tagged with: tensorflow
type: Question

vector
tags question: http://stackoverflow.com/q/49001478
type: Tag
tag name: vector
tags question: http://stackoverflow.com/q/49071248
tags question: http://stackoverflow.com/q/49039518
tags question: http://stackoverflow.com/q/49059089
tags question: http://stackoverflow.com/q/48980544
tags question: http://stackoverflow.com/q/48984575
tags question: http://stackoverflow.com/q/48985352
tags question: http://stackoverflow.com/q/49013930

http://stackoverflow.com/comment/84976105
score: 0
has text: I think pass by reference is something you should read about
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48985817

http://stackoverflow.com/comment/85107501
comment on: http://stackoverflow.com/a/49021430
score: 1
type: AnswerComment
has text: On Python 3.6, the `kwargs['encoding']` configuration is absolutely critical because it configures Popen() to use replace the 'ascii' codec with the 'UTF-8' codec. I need this same functionality on 3.5 if possible, but the 'encoding' key word was added in 3.6.
type: Comment

http://stackoverflow.com/q/49048124
has comment: http://stackoverflow.com/comment/85149207
type: AnsweredQuestion
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/85101597
has title: Python/Tkinter: multiple windows opened sequentially (and sharing information?)
type: Question
has answer: http://stackoverflow.com/a/49052441
has body: I'm trying to use two windows with Tkinter: One welcome window appears, and when a button is clicked, another window opens (and the welcome window closes). However, currently the first window doesn't show up so the program can't verify the condition and move on to the second one. (It shows up if the condition isn't there, but in which case both windows appear at the same time) welWindow=New_Toplevel_1(Tk()) #wait until welWindow.getGo()==1 while welWindow.getGo()!=1: time.sleep(1) #my variables get values from welWindow's variables welWindow.destroy() labWindow=(Tk()) labWindow.mainloop() The destroy function in my New_Toplevel_1 class: def destroy(self): self.top.destroy() (top is the Tk() used in the constructor) As you have probably guessed I am very new to this, all tips/recommendations are welcome :)
has comment: http://stackoverflow.com/comment/85111186
answer count: 1
has comment: http://stackoverflow.com/comment/85101286
accepted answer: http://stackoverflow.com/a/49052441
tagged with: python
linked to: http://stackoverflow.com/q/17466561

http://stackoverflow.com/a/48973036
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/84951258
accepted answer of: http://stackoverflow.com/q/48973021
answers question: http://stackoverflow.com/q/48973021
has body: Because you are spelling(making it all caps) it wrong Try: sess = requests.Session()
upvote count: 4

http://stackoverflow.com/a/49063052
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has body: This works if you convert all your dates form dtype string to datetime. df1['date'] = pd.to_datetime(df1['date']) df2['End Dates'] = pd.to_datetime(df2['End Dates']) df2['Start Dates'] = pd.to_datetime(df2['Start Dates']) df1['HDD'] = df1['HDD'].astype(float) df1.groupby(pd.cut(df1['date'], df2['Start Dates'])).agg({'HDD': sum}) Output: HDD date (2015-01-01, 2015-02-15] 7.5 (2015-02-15, 2015-03-14] 36.0 (2015-03-14, 2015-04-14] NaN Adding labels: df1.groupby(pd.cut(df1['date'], df2['Start Dates'], labels=df2.iloc[:-1,1])).agg({'HDD': sum}) Output: HDD date One 7.5 Two 36.0 Three NaN
has comment: http://stackoverflow.com/comment/85143600
type: Answer
has comment: http://stackoverflow.com/comment/85131968
accepted answer of: http://stackoverflow.com/q/49062669
answers question: http://stackoverflow.com/q/49062669
score: 5

http://stackoverflow.com/comment/85188572
score: 0
type: Comment
type: QuestionComment
has text: On which line is the error on?
comment on: http://stackoverflow.com/q/49091621

http://stackoverflow.com/q/49049616
has comment: http://stackoverflow.com/comment/85126096
tagged with: python
has comment: http://stackoverflow.com/comment/85117707
has comment: http://stackoverflow.com/comment/85107778
linked to: http://stackoverflow.com/q/44138026
type: Question
has body: This will work fine if I have to change value of option by giving the original reference of v variable import tkinter as tk root = tk.Tk() optionList = ('a', 'b', 'c') v = tk.StringVar() v.set(optionList[0]) # Here is the initially selected value om = tk.OptionMenu(root, v, *optionList) om.pack() v.set(optionList[2]) # This one will be the final selected value root.mainloop() But the problem is when we try to get the element by widget.winfo_children() and set it's value as follows: import tkinter as tk root = tk.Tk() optionList = ('a', 'b', 'c') v = tk.StringVar() v.set(optionList[0]) # Here is the initially selected value om = tk.OptionMenu(root, v, *optionList) om.pack() v.set(optionList[2]) # This one will be the final selected value _list = root.winfo_children() print(len(_list)) for item in _list : item.set('a') root.mainloop() Than it will give error as AttributeError: 'OptionMenu' object has no attribute 'set' Reference code from that answer
score: 0
has comment: http://stackoverflow.com/comment/85122030
has title: Change menu option of passed widget in tkinter
tagged with: tkinter
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85176633
comment on: http://stackoverflow.com/q/49085469
score: 0
type: Comment
type: QuestionComment
has text: Related: [Using np.view() with changes to structured arrays in numpy 1.14](https://stackoverflow.com/q/48267058/190597) and [this github issue](https://github.com/numpy/numpy/issues/10409)

http://stackoverflow.com/a/48972449
has body: as @Milad in the comment mentioned, you first need to initialize s as empty dictionary first data={} data['Tom']={} data['Tom']['name'] = 'Tom Marvolo Riddle' data['Tom']['email'] = 'iamlordvoldermort.com'
answers question: http://stackoverflow.com/q/48972043
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/49005531
has comment: http://stackoverflow.com/comment/85016545
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/49005507
answers question: http://stackoverflow.com/q/49005507
has comment: http://stackoverflow.com/comment/85015991
has comment: http://stackoverflow.com/comment/85015867
upvote count: 7
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85015939
has body: You are passing in the result of calling doSomething(). Pass in the function without calling it: set_interval(doSomething, 5) In Python, functions are just objects, just like strings or lists or integers. You can pass them around just the same. You probably want to store the returned thread object, so you can later on stop the thread again: t = set_interval(doSomething, 5) # ... t.stop()
has comment: http://stackoverflow.com/comment/85015851

http://stackoverflow.com/a/49029237
downvote count: 0
score: 1
has body: {% if images %} &lt;img src="{{ img.image.url }}" class="float-left" style="max-width: 150px"&gt; {% else %} // other code {% endif %} as you are using get which doesnt return a queryset, thus its not iterable if you had used filter then the for loop would have taken place
upvote count: 1
answers question: http://stackoverflow.com/q/49029198
type: Answer

http://stackoverflow.com/comment/85034735
has text: This even more makes me think that it's a server-side issue: client sends the 'close' frame and the server should also respond with a close frame, terminating the connection without delay. I used another websocket python lib which worked fine and I have this problem since I switched to ws4py (for ssl support)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49014285

contextmenu
tags question: http://stackoverflow.com/q/49058060
tag name: contextmenu
type: Tag

http://stackoverflow.com/a/48983156
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48982975
has body: you have to convert your nonce to a bytes directly. Not the string representation via https://stackoverflow.com/a/45586011/1562285 b = int2bytes(nonce) b'\xf0\x8c\x98\xca\xf1\xfd\x82\xe8\xce\xa9\x82]\xbf\xf0O\xd0' base64.b64encode(b) b'8IyYyvH9gujOqYJdv/BP0A=='

http://stackoverflow.com/q/48993596
score: 0
has comment: http://stackoverflow.com/comment/84993093
has body: The code I am using is: import requests k=requests.get('https://zebramo.com/search/product-scope/merrell?extended=true&amp;is_sold=false&amp;include_vacation=false&amp;max_price=100&amp;order_by=price&amp;order_direction=asc',headers=headerZ,stream=True) m=k.content print(m) When I check the page in Google Chrome ==>Inspect ==> Network I see that the return variable I get matches the first "Response" of the URL, but the responses or the outputs of .js files underneath do not exist within my content m. Because the same URL works in the Google Chrome, I tried to make a not-very-informed effort replicating the various headers info from the browser with no success. (In case there is not a straight answer I will also appreciate recommendations on the right direction, thanks.)
has title: request.get returns a subset
tagged with: python
has comment: http://stackoverflow.com/comment/84994767
answer count: 0
type: UnansweredQuestion
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84994393
type: Question

http://stackoverflow.com/comment/85091551
has text: Yes. Hopefully my recent edit makes that more clear.
score: 0
comment on: http://stackoverflow.com/a/49040788
type: AnswerComment
type: Comment

time-series
tags question: http://stackoverflow.com/q/48992001
type: Tag
tags question: http://stackoverflow.com/q/48999328
tags question: http://stackoverflow.com/q/49110904
tags question: http://stackoverflow.com/q/48973632
tags question: http://stackoverflow.com/q/49100622
tag name: time-series
tags question: http://stackoverflow.com/q/49039491
tags question: http://stackoverflow.com/q/49059341
tags question: http://stackoverflow.com/q/48999145

http://stackoverflow.com/comment/85036926
has text: Thanks. I wasn't able to use the NumPy functions directly, but the triu source code led me to an efficient implementation with a Lambda layer.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49003956

http://stackoverflow.com/comment/85188949
score: 0
type: Comment
type: QuestionComment
has text: Just did! Thanks for the advice
comment on: http://stackoverflow.com/q/49081417

http://stackoverflow.com/comment/85209408
score: 0
has text: @Maxim So I would have no choice but to train the model using data one by one if I want the input of the model to have variable timesteps?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49097124

http://stackoverflow.com/comment/85043695
has text: That works but is there another way from the code that I have provided?
score: 0
comment on: http://stackoverflow.com/a/49019194
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48980548
upvote count: 1
has body: This might help def censor(text, word): a = text.split() for i, v in enumerate(a): if v == word: a[i] = "*"*len(v) return ' '.join(a) print censor("Hello World", "World") Output: Hello *****
answers question: http://stackoverflow.com/q/48980503
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/48977754
answer count: 1
tagged with: flappy-bird-clone
tagged with: pygame
favorite count: 0
has title: Pygame Collision Bug
has body: I'm quite new to pygame and came across a bug that i just can't fix on my own. I'm trying to program a Flappy Bird game. The Problem is that the collision detection works, but it also messes with my sprites. If i manage to get past the first obstacle while playing, then the gap resets itself randomly. But the gap should always be the same, just on another position. If i remove the collision detection, it works perfectly fine. Any ideas? import pygame import random randomy = random.randint(-150, 150) class Bird(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25,25)) self.image.fill((255,255,255)) self.rect = self.image.get_rect() self.rect.center = (100, 200) self.velocity = 0.05 self.acceleration =0.4 def update(self): self.rect.y += self.velocity self.velocity += self.acceleration if self.rect.bottom &gt; 590: self.velocity = 0 self.acceleration = 0 class Pipe1(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((85, 500)) self.image.fill((255, 255, 255)) self.rect = self.image.get_rect() self.rect.center = (500, randomy) self.randomyupdate = random.randint(-150, 150) def update(self): self.rect.x -= 2 if self.rect.x &lt; -90: self.randomyupdate = random.randint(-150, 150) self.rect.center = (450, self.randomyupdate) class Pipe2(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((85, 500)) self.image.fill((255, 255, 255)) self.rect = self.image.get_rect() self.rect.center = (500, (randomy +640)) def update(self): self.rect.x -= 2 self.randomyupdate = Pipe1.randomyupdate if self.rect.x &lt; -90: self.rect.center = (450, (self.randomyupdate + 640)) pygame.init() pygame.mouse.set_visible(1) pygame.key.set_repeat(1, 30) pygame.display.set_caption('Crappy Bird') clock = pygame.time.Clock() Bird_sprite = pygame.sprite.Group() Pipe_sprite = pygame.sprite.Group() Bird = Bird() Pipe1 = Pipe1() Pipe2 = Pipe…
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48978596
accepted answer: http://stackoverflow.com/a/48978596
downvote count: 0

http://stackoverflow.com/a/48977689
type: Answer
accepted answer of: http://stackoverflow.com/q/48976670
upvote count: 2
has body: The package you are using from https://github.com/BillMills/python-package-example is using an import style not supported in Python 3. You can see in python-package-example/__init__.py that import somePython is used to import a submodule, but python 3 will assume somePython exists as a top level module. See PEP-328 for a better explanation. A Python 3 compatible example package can be found at https://github.com/kennethreitz/samplemod. Notice that in sample/__init__.py submodules are imported using a relative import (indicated by the leading '.'): from .core import hmm If you wanted to modify python-package-example to be compatible you would need to change its __init__.py to use an absolute import: import myPackage.somePython as somePython or a relative import: from . import somePython
answers question: http://stackoverflow.com/q/48976670
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85222774
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49107874
has text: Works like a charm! Thank you so much

http://stackoverflow.com/comment/85224779
has text: Ok give me a minute and I will put it as answer
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49099232

selenium
tags question: http://stackoverflow.com/q/49058060
tags question: http://stackoverflow.com/q/49041461
tags question: http://stackoverflow.com/q/49031746
tags question: http://stackoverflow.com/q/49098401
tags question: http://stackoverflow.com/q/49083012
tags question: http://stackoverflow.com/q/49010895
tags question: http://stackoverflow.com/q/48985758
tags question: http://stackoverflow.com/q/49078700
tags question: http://stackoverflow.com/q/49019183
tags question: http://stackoverflow.com/q/49044610
tags question: http://stackoverflow.com/q/48999392
tags question: http://stackoverflow.com/q/49102430
tags question: http://stackoverflow.com/q/48998281
tags question: http://stackoverflow.com/q/49054985
tags question: http://stackoverflow.com/q/48977155
tags question: http://stackoverflow.com/q/48998130
tags question: http://stackoverflow.com/q/49079184
tags question: http://stackoverflow.com/q/49042698
tags question: http://stackoverflow.com/q/49074333
tags question: http://stackoverflow.com/q/49073298
tags question: http://stackoverflow.com/q/49048339
tags question: http://stackoverflow.com/q/49077851
tags question: http://stackoverflow.com/q/49107734
tags question: http://stackoverflow.com/q/49028909
tags question: http://stackoverflow.com/q/49094168
tags question: http://stackoverflow.com/q/49018497
tags question: http://stackoverflow.com/q/49101595
tags question: http://stackoverflow.com/q/49040386
tags question: http://stackoverflow.com/q/49120065
tags question: http://stackoverflow.com/q/49090339
tags question: http://stackoverflow.com/q/49104102
tags question: http://stackoverflow.com/q/48988336
tags question: http://stackoverflow.com/q/49057247
tags question: http://stackoverflow.com/q/49073842
tags question: http://stackoverflow.com/q/48969578
tags question: http://stackoverflow.com/q/48993743
tags question: http://stackoverflow.com/q/49005382
tags question: http://stackoverflow.com/q/49118596
tag name: selenium
tags question: http://stackoverflow.com/q/49119922
tags question: http://stackoverflow.com/q/49042607
tags question: http://stackoverflow.com/q/48995222
tags question: http://stackoverflow.com/q/49090572
tags question: http://stackoverflow.com/q/48971290
tags question: http://stackoverflow.com/q/49051111
tags question: http://stackoverflow.com/q/49059592
tags question: http://stackoverflow.com/q/49108298
tags question: http://stackoverflow.com/q/48999829
tags question: http://stackoverflow.com/q/49083499
tags question: http://stackoverflow.com/q/49082933
tags question: http://stackoverflow.com/q/49036162
tags question: http://stackoverflow.com/q/48966662
tags question: http://stackoverflow.com/q/49041839
tags question: http://stackoverflow.com/q/49057075
tags question: http://stackoverflow.com/q/48970015
tags question: http://stackoverflow.com/q/48968852
tags question: http://stackoverflow.com/q/48966355
tags question: http://stackoverflow.com/q/48975560
tags question: http://stackoverflow.com/q/49089744
tags question: http://stackoverflow.com/q/49035255
tags question: http://stackoverflow.com/q/49101649
tags question: http://stackoverflow.com/q/49088524
tags question: http://stackoverflow.com/q/48986204
tags question: http://stackoverflow.com/q/49056755
tags question: http://stackoverflow.com/q/49053624
tags question: http://stackoverflow.com/q/49115992
type: Tag
tags question: http://stackoverflow.com/q/49038429
tags question: http://stackoverflow.com/q/49015686
tags question: http://stackoverflow.com/q/48989169
tags question: http://stackoverflow.com/q/49032878
tags question: http://stackoverflow.com/q/49080744
tags question: http://stackoverflow.com/q/49047938
tags question: http://stackoverflow.com/q/49065872
tags question: http://stackoverflow.com/q/48975874
tags question: http://stackoverflow.com/q/49020361
tags question: http://stackoverflow.com/q/49071664
tags question: http://stackoverflow.com/q/48995037
tags question: http://stackoverflow.com/q/49101874
tags question: http://stackoverflow.com/q/49007982

http://stackoverflow.com/q/48988322
tagged with: datetime
tagged with: python
has title: simple conversion between custom date/time formats in python (2.7)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84981264
accepted answer: http://stackoverflow.com/a/48988390
linked to: http://stackoverflow.com/q/311627
type: Question
has body: I have looked far and wide to answer my question/solve my problem but I'm stuck. I need to import a table of data, the first column of which, is composed of date/times like '20180214_145712'. Eventually I would like to export this data to a format that I think will work well with MS Excel i.e. '2018-02-14 14:57:12'. Now I found a scrap of code that seems to do exaclty this: import datetime d = datetime.datetime(2018, 2, 14, 14, 57, 12) '{:%Y-%m-%d %H:%M:%S}'.format(d) Now when I input the first data/time value from my data file like so: import datetime d = datetime.datetime(int(data[0][0][0:4]), int(data[0][0][4:6]), int(data[0][0][6:8]), int(data[0][0][9:11]), int(data[0][0][11:13]), int(data[0][0][13:15]) '{:%Y-%m-%d %H:%M:%S}'.format(d) I get an error in my Jupyter notebook: File "&lt;ipython-input-72-d0bef0623630&gt;", line 4 '{:%Y-%m-%d %H:%M:%S}'.format(d) ^ SyntaxError: invalid syntax At this point I don't know how to proceed any further. The format identifiers seem to be fine, I think my input data is fine i.e. just integers. I checked on SO forum and found a useful post about the datetime module (other question on SO). Any pointers would be useful. Rich
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48988390

pyside
tags question: http://stackoverflow.com/q/49020267
tags question: http://stackoverflow.com/q/49035495
tags question: http://stackoverflow.com/q/48980344
type: Tag
tags question: http://stackoverflow.com/q/49081290
tag name: pyside
tags question: http://stackoverflow.com/q/49113983
tags question: http://stackoverflow.com/q/49049828
tags question: http://stackoverflow.com/q/48996790

http://stackoverflow.com/comment/85038330
type: AnswerComment
comment on: http://stackoverflow.com/a/49016208
has text: @Psionman The nullhandler is fine - it just does not produce any output. See answer, and use it to debug what/where which one is set to what..ever.
score: 0
type: Comment

http://stackoverflow.com/comment/91561086
type: Comment
has text: I created *tabel*, as a simplified version of pandas. It's entirely based on numpy but abstracts away the details of dealing with multiple datatypes. and numpy is usually faster in get/set scenarios like yours. https://pypi.org/project/tabel/
score: 0
comment on: http://stackoverflow.com/q/49053252
type: QuestionComment

http://stackoverflow.com/q/49055298
favorite count: 0
has body: Sorry, I'm pretty sure that somebody else may have asked this question already but I did not find it. I'd like to keep track the number of times I've seen this specific item like Input : [88,88,27,0,88] Desired Output : [1,2,1,1,3] I'm looking for something especially good in terms of performance. I'm ok with Numpy or Pandas solutions.
has comment: http://stackoverflow.com/comment/85115111
has answer: http://stackoverflow.com/a/49055402
tagged with: python
downvote count: 1
answer count: 4
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85115198
tagged with: group-by
linked to: http://stackoverflow.com/q/2600191
has answer: http://stackoverflow.com/a/49055417
type: Question
upvote count: 4
has title: Counter occurrences within the same item in python
tagged with: counter
has comment: http://stackoverflow.com/comment/85115119
possible better answer: http://stackoverflow.com/a/49055403
accepted answer: http://stackoverflow.com/a/49055417
has answer: http://stackoverflow.com/a/49055403
has answer: http://stackoverflow.com/a/49055630

http://stackoverflow.com/q/49093623
accepted answer: http://stackoverflow.com/a/49093688
score: 1
possible better answer: http://stackoverflow.com/a/49093961
type: Question
answer count: 2
has body: I have an app which adds coroutines to an already-running event loop. The arguments for these coroutines depend on I/O and are not available when I initially start the event loop - with loop.run_forever(), so I add the tasks later. To demonstrate the phenomenon, here is some example code: import asyncio from threading import Thread from time import sleep loop = asyncio.new_event_loop() def foo(): loop.run_forever() async def bar(s): while True: await asyncio.sleep(1) print("s") #loop.create_task(bar("A task created before thread created &amp; before loop started")) t = Thread(target=foo) t.start() sleep(1) loop.create_task(bar("secondary task")) The strange behaviour is that everything works as expected when there is at least one task in the loop when invoking loop.run_forever(). i.e. when the commented line is not commented out. But when it is commented out, as shown above, nothing is printed and it appears I am unable to add a task to the event_loop. Should I avoid invoking run_forever() without adding a single task? I don't see why this should be a problem. Adding tasks to an event_loop after it is running is standard, why should the empty case be an issue?
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/49093688
downvote count: 0
favorite count: 0
upvote count: 1
tagged with: python
has title: Strange behaviour when task added to empty loop in different thread
has answer: http://stackoverflow.com/a/49093961
type: AnsweredQuestion

http://stackoverflow.com/q/49031454
tagged with: pip
type: Question
has body: I'm new to python and i have been trying to install brew 0.1.4. I get the following error. C:\Users\sys&gt;pip install brew Collecting brew Using cached brew-0.1.4.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\sys\AppData\Local\Temp\pip-build-m49ufx8l\brew\setup.py",line 22, in &lt;module&gt; with open('requirements.txt') as fid: FileNotFoundError: [Errno 2] No such file or directory:'requirements.txt' Command "python setup.py egg_info" failed with error code 1 in C:\Users\sys\AppData\Local\Temp\pip-build-m49ufx8l\brew\ I have tried the freeze method to create the requirements file but still get the same error. Help me resolve this. $ pip freeze &gt; requirements.txt
score: 0
answer count: 1
has title: brew 0.1.4 installation for python pip error
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49031547
accepted answer: http://stackoverflow.com/a/49031547

http://stackoverflow.com/comment/85173168
type: QuestionComment
comment on: http://stackoverflow.com/q/49083012
has text: Sorry the pwd is thecoingood1
score: 0
type: Comment

http://stackoverflow.com/q/49002709
score: 7
type: Question
has title: ResultSet object has no attribute 'find_all'
linked to: http://stackoverflow.com/q/24108507
answer count: 2
upvote count: 7
has body: i always met one problem, when I scraping one web page. AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? anyone can tell me how to solve this? my code as below: import requests r = requests.get('https://www.example.com') from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'}) records = [] for result in results: name = results.find('div', attrs={'class':'name'}).text price = results.find('div', attrs={'class':'price'}).text[13:-11] records.append((name, price,)) I want to ask a close question.If I want to scrap multiple pages.the pattern like below,I use the code as below,but still scrap the first page only Can you solve this issue. import requests for i in range(100): url = "https://www.example.com/a/a_{}.format(i)" r = requests.get(url) from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'})
downvote count: 0
possible better answer: http://stackoverflow.com/a/70580238
has comment: http://stackoverflow.com/comment/107580987
favorite count: 0
linked to: http://stackoverflow.com/q/49105772
has answer: http://stackoverflow.com/a/70580238
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49002922
tagged with: attributeerror
accepted answer: http://stackoverflow.com/a/49002922

http://stackoverflow.com/comment/85055502
type: QuestionComment
comment on: http://stackoverflow.com/q/49025275
has text: Possible duplicate of [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary)
score: 0
type: Comment

linux-mint
type: Tag
tags question: http://stackoverflow.com/q/48991022
tag name: linux-mint
tags question: http://stackoverflow.com/q/48984042

http://stackoverflow.com/comment/84971564
comment on: http://stackoverflow.com/q/48979895
type: Comment
type: QuestionComment
has text: How have you detected that `rcvr` and `xmtr` block each other? Can you show a small _runnable_ example that still demonstrates the problem? (For example, using `asyncio.start_server` to start a trivial server and `nc` to connect to it.)
score: 1

http://stackoverflow.com/comment/85068871
has text: Possible duplicate of https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables
type: QuestionComment
comment on: http://stackoverflow.com/q/49032045
type: Comment
score: 0

http://stackoverflow.com/q/49035660
accepted answer: http://stackoverflow.com/a/49043058
type: AnsweredQuestion
score: 3
downvote count: 0
has body: I would like to create plot images from a NetCDF at each time step. My NetCDF files look like this: netcdf file:/C:/home/data/cmorph/test/reduced_cmorph_adjusted_spi_pearson_01.nc { dimensions: time = UNLIMITED; // (240 currently) lat = 120; lon = 360; variables: float spi_pearson_01(time=240, lat=120, lon=360); :_FillValue = NaNf; // float :valid_min = -3.09; // double :valid_max = 3.09; // double :long_name = "Standard Precipitation Index (Pearson Type III distribution), 1-month scale"; :_ChunkSizes = 1, 120, 360; // int int time(time=240); :units = "days since 1800-01-01 00:00:00"; :_ChunkSizes = 1024; // int :_CoordinateAxisType = "Time"; float lat(lat=120); :units = "degrees_north"; :_CoordinateAxisType = "Lat"; float lon(lon=360); :units = "degrees_east"; :_CoordinateAxisType = "Lon"; // global attributes: :title = "CMORPH Version 1.0BETA Version, daily precip from 00Z-24Z"; :history = "Wed Feb 28 07:30:01 2018: C:\\home\\miniconda\\Library\\bin\\ncks.exe --dmn lon,0,,4 --dmn lat,0,,4 CMORPH_V1.0_ADJ_0.25deg-DLY_00Z_1998_2017.nc cmorph_reduced_adjusted.nc"; :NCO = "4.7.1"; :_CoordSysBuilder = "ucar.nc2.dataset.conv.DefaultConvention"; } I like the plots produced by Panoply but I haven't worked out how to script it (I don't want to go through the GUI for this since I'll have roughly 1500 plots to create). I'm not wedded to Panoply per se, so if someone has a better idea please advise. I could hammer this out in matplotlib but it'd take me quite a while and wouldn't look as good as the Panoply plots. I'm trying to avoid doing much if any of the plotting myself, but maybe there's something out there that provides easy plotting of NetCDFs which can be called from a script (I typically use Python and Bash).
has title: NetCDF: How can I script plotting at each time step?
favorite count: 0
has answer: http://stackoverflow.com/a/49043828
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49043058
tagged with: plot
possible better answer: http://stackoverflow.com/a/49043828
upvote count: 3
answer count: 2
tagged with: netcdf

http://stackoverflow.com/comment/85182519
type: Comment
type: QuestionComment
has text: `random.choice()` will always generate a random item in constant time according to [the comments/answers on this question](https://stackoverflow.com/questions/40143157/q-what-is-big-o-complexity-of-random-choicelist-in-python3?rq=1).. so even if you shuffle the list and then choose items, the shuffle will add extra time and all of the choices will be constant time?
comment on: http://stackoverflow.com/q/49088430
score: 0

http://stackoverflow.com/comment/85125331
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49059974
has text: Like `someList.append()` will modify a list.
score: 0

http://stackoverflow.com/a/49123421
type: Answer
answers question: http://stackoverflow.com/q/49120376
score: 1
upvote count: 1
has body: You need to get the page source (send a request to page) for every different URL. You are missing that part in your crawler() function. Adding those lines outside the function, won't call them recursively. def crawler(url, depth): if depth == 0: return None html = urlopen(url) # You were missing soup = BeautifulSoup(html, 'html.parser') # these lines. links = soup.find("div",{"id" : "bodyContent"}).findAll("a", href=re.compile("(/wiki/)+([A-Za-z0-9_:()])+")) print("Level ", depth, url) for link in links: if ':' not in link['href']: crawler("https://en.wikipedia.org"+link['href'], depth - 1) url = "https://en.wikipedia.org/wiki/Big_data" crawler(url, 3) Partial Output: Level 3 https://en.wikipedia.org/wiki/Big_data Level 2 https://en.wikipedia.org/wiki/Big_Data_(band) Level 1 https://en.wikipedia.org/wiki/Brooklyn Level 1 https://en.wikipedia.org/wiki/Electropop Level 1 https://en.wikipedia.org/wiki/Alternative_dance Level 1 https://en.wikipedia.org/wiki/Indietronica Level 1 https://en.wikipedia.org/wiki/Indie_rock Level 1 https://en.wikipedia.org/wiki/Warner_Bros._Records Level 1 https://en.wikipedia.org/wiki/Joywave Level 1 https://en.wikipedia.org/wiki/Electronic_music Level 1 https://en.wikipedia.org/wiki/Dangerous_(Big_Data_song) Level 1 https://en.wikipedia.org/wiki/Joywave Level 1 https://en.wikipedia.org/wiki/Billboard_(magazine) Level 1 https://en.wikipedia.org/wiki/Alternative_Songs Level 1 https://en.wikipedia.org/wiki/2.0_(Big_Data_album)
accepted answer of: http://stackoverflow.com/q/49120376
type: AcceptedAnswer
downvote count: 0

pyspark
tags question: http://stackoverflow.com/q/49064162
tags question: http://stackoverflow.com/q/49043614
tags question: http://stackoverflow.com/q/49060960
tags question: http://stackoverflow.com/q/49089601
tags question: http://stackoverflow.com/q/49120965
tags question: http://stackoverflow.com/q/48981511
tags question: http://stackoverflow.com/q/49039956
tags question: http://stackoverflow.com/q/48993176
tags question: http://stackoverflow.com/q/48986212
tags question: http://stackoverflow.com/q/49098114
tags question: http://stackoverflow.com/q/49061130
tags question: http://stackoverflow.com/q/49059508
tags question: http://stackoverflow.com/q/48973611
tags question: http://stackoverflow.com/q/49010335
tags question: http://stackoverflow.com/q/49073915
tags question: http://stackoverflow.com/q/48979245
tags question: http://stackoverflow.com/q/48996488
tags question: http://stackoverflow.com/q/49019091
tags question: http://stackoverflow.com/q/49103077
tags question: http://stackoverflow.com/q/49119718
tags question: http://stackoverflow.com/q/48979579
tags question: http://stackoverflow.com/q/49079133
tags question: http://stackoverflow.com/q/49108541
tags question: http://stackoverflow.com/q/49019323
tags question: http://stackoverflow.com/q/49072727
type: Tag
tags question: http://stackoverflow.com/q/49116437
tags question: http://stackoverflow.com/q/49078434
tags question: http://stackoverflow.com/q/49064338
tags question: http://stackoverflow.com/q/49048212
tags question: http://stackoverflow.com/q/49063058
tags question: http://stackoverflow.com/q/49039294
tags question: http://stackoverflow.com/q/49113498
tags question: http://stackoverflow.com/q/49046909
tags question: http://stackoverflow.com/q/49020056
tags question: http://stackoverflow.com/q/49051910
tags question: http://stackoverflow.com/q/48992497
tags question: http://stackoverflow.com/q/49110803
tags question: http://stackoverflow.com/q/48994798
tags question: http://stackoverflow.com/q/48979362
tags question: http://stackoverflow.com/q/49011430
tags question: http://stackoverflow.com/q/49025442
tags question: http://stackoverflow.com/q/49035644
tags question: http://stackoverflow.com/q/49031748
tags question: http://stackoverflow.com/q/48986917
tags question: http://stackoverflow.com/q/49100218
tags question: http://stackoverflow.com/q/48994810
tags question: http://stackoverflow.com/q/49114841
tags question: http://stackoverflow.com/q/49023893
tag name: pyspark
tags question: http://stackoverflow.com/q/49120835

http://stackoverflow.com/a/48964514
score: 1
accepted answer of: http://stackoverflow.com/q/48964492
has body: You can easily do that since pip supports installation from a version control system, see here. This assumes that the package you wish to install has a setup.py file. pip install git+git://github.com/BillMills/python-package-example.git Git (Mostly extraction form here) Pip supports cloning over git, git+http, git+https, git+ssh, git+git and git+file. [-e] git://git.myproject.org/MyProject#egg=MyProject [-e] git+http://git.myproject.org/MyProject#egg=MyProject [-e] git+https://git.myproject.org/MyProject#egg=MyProject [-e] git+ssh://git.myproject.org/MyProject#egg=MyProject [-e] git+git://git.myproject.org/MyProject#egg=MyProject [-e] git+file://git.myproject.org/MyProject#egg=MyProject -e git+git@git.myproject.org:MyProject#egg=MyProject You can also ask to install from a specific branch, commit hash, or tag name if you want a beta version or a branch that is targeted to your specific distribution etc by using @ and passing over the name of the branch/commit hash/tag name: Branch: [-e] git://git.myproject.org/MyProject.git@master#egg=MyProject Commit Has: [-e] git://git.myproject.org/MyProject.git@da39a3ee5e6b4b0d3255bfef95601890afd80709#egg=MyProject Tag: git://git.myproject.org/MyProject.git@v1.0#egg=MyProject Here is a real-world use-case (Git): Let's say that we wish to install the following Python package that is available on GitHub here. Simply I will run: pip install git+git://github.com/BillMills/python-package-example.git And here is the result: (test) pc-207-126:Desktop rafael$ pip install git+git://github.com/BillMills/python-package-example.git Collecting git+git://github.com/BillMills/python-package-example.git Cloning git://github.com/BillMills/python-package-example.git to /private/var/folders/c_/8qcnm5sj3kg7_f887qv473tm0000gn/T/pip-mx1vcsod-build Collecting numpy (from python-package-example==0.1) Downloading numpy-1.14.1-cp36-cp36m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.7MB) 100% |██████…
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48964492
type: Answer
upvote count: 1

http://stackoverflow.com/comment/85079813
score: 1
has text: You may need to get your IT people to solve firewall or other barriers.
comment on: http://stackoverflow.com/q/49037211
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49104925
upvote count: 1
answers question: http://stackoverflow.com/q/49104670
score: 1
downvote count: 0
type: Answer
has body: You can try inbuilt _asdict method to get the result as Dict. Ref: Online Docs Sample code: for row in selectAA1: print(row._asdict())

http://stackoverflow.com/q/49073887
tagged with: sql-server
has title: How to inner join with PyODBC
type: Question
tagged with: python
tagged with: pyodbc
score: -1
has comment: http://stackoverflow.com/comment/85155558
has comment: http://stackoverflow.com/comment/85155808
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/49076077
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49074033
upvote count: 0
has body: UPDATE I updated my code and the error I am receiving. I'm not exactly sure how to use INNER JOIN with Python's pypyODBC. I am getting an error that says "Cannot find either column "UT" or the user-defined function or aggregate, "UT.userID", or the name is ambigous." I've tried specifying the table in the SELECT statement. Any suggestions on how I can fix this? import pypyodbc def intercard(): firstname = "Paul" key = "334" try: connection = pypyodbc.connect('Driver={SQL Server};Server=MyServerName;Database=MyDatabaseName;Trusted_Connection=yes;') except pypyodbc.Error as ex: sqlstate = ex.args[0] if sqlstate == '28000': print("You do not have access.") cursor = connection.cursor() SQLCommand = ("SELECT UT.userID, Status, userName " "FROM dbo.StatusTable as ST INNER JOIN dbo.UserTable as UT " # table name "ON ST.userID=UT.userID" "(nolock)" "WHERE userKey LIKE ? AND First Name LIKE ?") Values = ['%' + key + '%', '%' + firstname + '%'] cursor.execute(SQLCommand,Values) results = cursor.fetchone() if results: print(connections + " " + str(results[0]) + " " + str(results[1])) # enters results in entry connection.close() I just want to connect to both the StatusTable and UserTable. ** UPDATE 2 ** I can run the below directly in SQL Server and it works. But I can't get it working in Python... SELECT ST.[userID] FROM [dbo].[StatusTable] as ST INNER JOIN [dbo].[UserTable] as UT ON ST.userID = UT.userID where Name = 'Paul'
has comment: http://stackoverflow.com/comment/85155032
favorite count: 0
has answer: http://stackoverflow.com/a/49076228

http://stackoverflow.com/a/49008229
has comment: http://stackoverflow.com/comment/85021726
accepted answer of: http://stackoverflow.com/q/49008179
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49008179
type: Answer
has comment: http://stackoverflow.com/comment/85020903
has body: You need dict comprehension for separate each values to keys first: my_dict={1:"one,two",2:"three,four"} d = {k: oldk for oldk, oldv in my_dict.items() for k in oldv.split(',')} print (d) {'one': 1, 'three': 2, 'four': 2, 'two': 1} df.A = df.A.replace(my_dict)
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/85020937

http://stackoverflow.com/comment/85069417
has text: The output show only the three attributes from Post, not the autor and the category: - Prueba 1 Post - Descripción Prueba 1 Post - 26 de Febrero de 2018 a las 13:31
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49032171
type: QuestionComment

http://stackoverflow.com/q/49018918
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/48650889
downvote count: 0
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/49019488
favorite count: 0
tagged with: scope
tagged with: reinforcement-learning
tagged with: python
has title: Tensorflow sharing variables under different variable_scope
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
has body: I have three networks, call them V, V_target, and Actor, and I'm trying to achieve the following setup: V and Actor share certain layers. V_target is an exact duplicate of V. For those familiar with deep RL, I'm using this within an actor-critic algorithm with shared layers between the value and policy networks, plus a target network V_target. I tried the following: def shared(...): # define some variables, e.g. W = get_variable('W', ...) def Actor(...): with tf.variable_scope("shared"): shared_out = shared(...) ... actor-specific layers ... def V(...): with tf.variable_scope("shared", reuse=True): shared_out = shared(...) ... V-specific layers... with tf.variable_scope("Policy"): actor_out = Actor(...) with tf.variable_scope("V_main"): V_out = V(...) with tf.variable_scope("V_target"): V_target = V(...) As expected, this doesn't work because the use of the outermost variable_scope prevents sharing between Policy and V_main: the Variable W has name Policy/shared/W in one scope but has name V_main/shared/W under the second scope. Why not use tf.name_scope("Policy") and tf.name_scope("V_main")? If I do that, the shared variables can be defined, but then I don't have a good way to get the variables under V_main and V_target. Specifically, because tf.name_scope does not append anything to names created by tf.get_variable, I cannot use tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES ,'V_main') and tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES ,'V_target') to get both sets of objects for the so-called "target updates". Is there any clever way around this?

http://stackoverflow.com/comment/85063085
has text: Bingo! This is it! Thank you! I should have seen this, but relatively new to python.
comment on: http://stackoverflow.com/q/49029226
score: 0
type: Comment
type: QuestionComment

split
tags question: http://stackoverflow.com/q/49020187
tag name: split
tags question: http://stackoverflow.com/q/49004693
tags question: http://stackoverflow.com/q/48963967
tags question: http://stackoverflow.com/q/49077911
tags question: http://stackoverflow.com/q/49064817
tags question: http://stackoverflow.com/q/48977945
tags question: http://stackoverflow.com/q/48968467
tags question: http://stackoverflow.com/q/49109150
type: Tag
tags question: http://stackoverflow.com/q/49015592
tags question: http://stackoverflow.com/q/49094294

http://stackoverflow.com/q/49076283
type: Question
tagged with: html-table
answer count: 2
possible better answer: http://stackoverflow.com/a/49076439
tagged with: beautifulsoup
score: 0
has answer: http://stackoverflow.com/a/49076439
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85158417
has answer: http://stackoverflow.com/a/49076770
has body: I'm trying to convert a table of this format to a dictionary and having more trouble than I should. The table is of this format: A B C D E F G A value B value C value D value E value F Value G value I am trying to make it to a dictionary which would be like foo["A":"A Value", "B":"B value" ...] Any help would be appreciated
has title: Converting HTML table to dictionary with beautiful soup
accepted answer: http://stackoverflow.com/a/49076770

http://stackoverflow.com/q/48964009
has title: Tensorflow-gpu runs on CPU though I don't have the cpu version installed
has comment: http://stackoverflow.com/comment/84934141
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84937729
has body: I was trying to learn about NN and was using keras on tensorflow backend. Now the tensorflow version that i have is the GPU one. But when i was looking at the task manager, I noticed that my CPU was running at 100% and GPU was not being used. Also I have not installed any tensorflow for cpu. While importing tensorflow i get the following: &gt;&gt;&gt; import tensorflow as tf C:\Users\mridu\AppData\Local\Programs\Python\Python36\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Also, If I run: &gt;&gt;&gt; from tensorflow.python.client import device_lib &gt;&gt;&gt; print(device_lib.list_local_devices()) I get the following output: 2018-02-24 20:01:19.640381: I C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 2018-02-24 20:01:20.245834: I C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1105] Found device 0 with properties: name: GeForce 940MX major: 5 minor: 0 memoryClockRate(GHz): 1.189 pciBusID: 0000:01:00.0 totalMemory: 4.00GiB freeMemory: 3.35GiB 2018-02-24 20:01:20.253903: I C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1195] Creating TensorFlow device (/device:GPU:0) -&gt; (device: 0, name: GeForce 940MX, pci bus id: 0000:01:00.0, compute capability: 5.0) [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 16468572883557283825 , name: "/device:GPU:0" device_type: "GPU" memory_limit: 3240964915 locality { bus_id: 1 } incarnation: 10646606003076945092 physical_device_desc: "device: 0, name: GeForce 940MX, pci bus id: 0000:01:00.0, compute capabili…
has comment: http://stackoverflow.com/comment/84934316
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/84949076
has comment: http://stackoverflow.com/comment/84934212
has comment: http://stackoverflow.com/comment/84947003
score: 0
has comment: http://stackoverflow.com/comment/84934022

http://stackoverflow.com/comment/85007008
comment on: http://stackoverflow.com/q/49000662
has text: @et clarification: Do you want to add a newline everytime there is a space, or one newline everytime there are multiple spaces in a row
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85081178
type: QuestionComment
has text: Welcome. Be sure to take the [tour]. Please use tag [tag:fortran] for all Fortran questions,
comment on: http://stackoverflow.com/q/49037919
score: 0
type: Comment

http://stackoverflow.com/comment/137010034
type: AnswerComment
type: Comment
has text: `discord.Message.author` is type `Union[discord.Member,discord.abc.User]`, neither of which seem to have a `server` attribute.
comment on: http://stackoverflow.com/a/49085527
score: 0

http://stackoverflow.com/comment/85139836
comment on: http://stackoverflow.com/a/49067371
type: AnswerComment
has text: yes, that's another thing my program keeps doing. it excludes the initial input as you say. however, I tried putting the first anyNumber statement within the while loop but it keeps giving me an error. So I'm not sure how to include it within the while loop. Unfortunately my tutor is taking forever to reply to me hence I'm on stackoverflow
score: 0
type: Comment

http://stackoverflow.com/comment/85212099
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49103333
has text: @Evert the issue is that those factors are't nearly as important to the combinatoric problem of when all frames are repetitious. My goal is to find the point it which all frames are accounted for, maybe including a small error or deviation for the time when repetition begins and normalizes.

http://stackoverflow.com/comment/85242929
comment on: http://stackoverflow.com/a/49118662
has text: @metersk: then push the handling of the response into the coroutine you gather. You may want to use some kind of rate limiting to prevent overloading your network if you are going to do that many requests.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48980611
tagged with: python-3.6
has title: File Recursion in Python
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84966354
has answer: http://stackoverflow.com/a/48980706
has comment: http://stackoverflow.com/comment/84966339
has body: I have a Folder A, which has 100 subfolders, each of those has 3-6 subfolders one of which holds a bunch of txt files. I need to do file recursion to get those. Since I want to give something for people to build off of: import path rootdir = path(*Folder A location*) file_list = [f for f in rootdir.glob('**/*') if f.is_file()] # For absolute paths instead of relative the current dir file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()] My goal is to take these .txt files containing tables and gather the data from them.
type: Question

http://stackoverflow.com/q/49027906
possible better answer: http://stackoverflow.com/a/49028312
has title: & together a list of boolean DataFrames
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49027984
favorite count: 0
type: Question
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/49027984
tagged with: python
has answer: http://stackoverflow.com/a/49028312
has body: I have a pandas DataFrame: import pandas as pd import numpy as np from random import sample, randrange from functools import reduce N = 200 df = pd.DataFrame({'Rating': np.random.choice(range(100), N), 'Treatment': np.random.choice(range(1, 10), N), 'Trial': np.random.choice(range(1, 20), N), 'Name': np.random.choice(list("ABCDEF"), N), 'Target': np.random.choice(list("JKLMNOP"), N), 'Part': np.random.choice(list("WXYZ"), N), }) In my application, the user can make a selection, but for now let's select some random values: &gt;&gt;&gt; categories = [sorted(df[column].unique()) for column in df.columns.values] &gt;&gt;&gt; print(categories) [['A', 'B', 'C', 'D', 'E', 'F'], ['W', 'X', 'Y', 'Z'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 78, 79, 80, 82, 84, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], ['J', 'K', 'L', 'M', 'N', 'O', 'P'], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]] &gt;&gt;&gt; selected = [sample(category, k=3) for category in categories] &gt;&gt;&gt; print(selected) [['F', 'D', 'C'], ['X', 'Z', 'W'], [36, 35, 16], ['O', 'N', 'P'], [8, 1, 9], [7, 11, 8]] Now I want to select the row(s) in my DataFrame where, for each column, the value of the cell is in the selection. What I came up with is: &gt;&gt;&gt; df[reduce((lambda x, y: x &amp; y), [df[column].isin(selection) for (column, selection) in zip(df.columns.values, selected)])] Name Part Rating Target Treatment Trial 173 D Z 35 O 9 7 This works, but it doesn't look very pythonic. Is there a better way to do this?

http://stackoverflow.com/q/49023851
downvote count: 0
answer count: 1
favorite count: 0
tagged with: dxf
tagged with: bspline
has answer: http://stackoverflow.com/a/49033853
tagged with: python
has body: I'm attempting to draw the raster representation of spline curves extracted from DXF files. I've extracted the data from the DXF files using the ezdxf library and I'm using the Python Wand library (ImageMagick) to draw the images. Wand has a spline function but what it draws doesn't always match the curves from the DXF files. This is no surprise since the Wand spline function doesn't have inputs for the knots or the degree of the DXF spline curve. The following images show what the DXF shapes look like. The Wand spline function works well with one example but not another. The first is a spline oval Oval Example. The second is a spine rectangle Rectangle Example. The data points and knots from the DXF files for these shapes have been extracted and used in the following sample code which creates sample bitmaps. Even though the knots and degree aren't taken into account the oval renders well test_image_oval.bmp. The rectangle is misshaped at all sides and corners test_image_rect.bmp. The control points are plotted in red The knots are included but not used. from wand.image import Image from wand.color import Color from wand.drawing import Drawing ############################################ point_list_oval = [ (5.0, 1.5, 0), (5.0, 0.6715728753, 0), (3.8807118745, 0.0, 0), (2.5, 0.0, 0), (1.1192881255, 0.0, 0), (0.0, 0.6715728753, 0), (0.0, 1.5, 0), (0.0, 2.3284271247, 0), (1.1192881255, 3.0, 0), (2.5, 3.0, 0), (3.8807118745, 3.0, 0), (5.0, 2.3284271247, 0), (5.0, 1.5, 0)] knots_oval = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0] ############################################ point_list_rect = [(3.75, 0.0, 0), (3.75, 0.0, 0), (0.25, 0.0, 0), (0.25, 0.0, 0), (0.1125, 0.0, 0), (0.0, 0.1125, 0), (0.0, 0.25, 0), (0.0, 0.25, 0), (0.0, 5.75, 0), (0.0, 5.75, 0), (0.0, 5.8875, 0), (0.1125, 6.0, 0), (0.25, 6.0, 0), (0.25, 6.0, 0), (3.75, 6.0, 0), (3.75, 6.0, 0), (3.8875, 6.0, 0), (4.0, 5.8875, 0), (4.0, 5.75, 0), (4.0, 5.75, 0), (4.0, 0.25,…
type: AnsweredQuestion
tagged with: wand
accepted answer: http://stackoverflow.com/a/49033853
score: 1
upvote count: 1
tagged with: scipy
type: Question
has title: Generating Spline Curves with Wand and Python

http://stackoverflow.com/comment/85059953
comment on: http://stackoverflow.com/q/49027768
score: 0
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest details added sorry !

http://stackoverflow.com/a/49096374
answers question: http://stackoverflow.com/q/49096281
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85197875
has comment: http://stackoverflow.com/comment/85199869
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85197684
has comment: http://stackoverflow.com/comment/85197809
accepted answer of: http://stackoverflow.com/q/49096281
has body: Does that mean my input layer should have 4 input features (3 for the generated hot vector and one for the numeric value)? Yes. This means that the input layer has 4 features. It seems easier to just change the category to a number IE: A=1, B=2, C=3 and then have just 2 features, what is the right way and why? It is easier to change A=1, B=2, C=3. However it tells the neural network that C is somehow greater than B which is somehow greater than A. To understand the problem with this, let us assume that your Category was actually color of an object. Treating colors as numbers will imply that either red is greater than blue or blue is greater than red, which is highly unintiutive. We know that neural networks are just concatenated mathematical functions, they will treat colors that are assigned bigger numbers as bigger colors, so it is a wrong approach to assign numbers to colors. Therefore, it makes sense to represent each of the color by a separate feature. It helps to think of these 0's and 1's as probabilities related to each feature value. For example value of red being 1 indicates that the probability that this object is red is 1. Value of 0 indicates 0 probability.

http://stackoverflow.com/q/49026183
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85058252
accepted answer: http://stackoverflow.com/a/49097238
downvote count: 0
has title: Parsing an xml in python to find xpaths of all elements (nodes)
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85063602
answer count: 1
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49097238
type: AnsweredQuestion
has body: I have an xml file- https://github.com/schogini/jVoiD/blob/master/Modules/jVoidCustomers/src/main/webapp/WEB-INF/spring/webcontext/DispatcherServlet-context.xml I am using the following code to parse a xml file- from lxml import etree xslt_root = etree.parse("/Users/cbuser1/CodeBlueFabricator/src/poc/PythonParser/mvc-config.xml") print(xslt_root) I get the result of my program as- &lt;lxml.etree._ElementTree object at 0x10e95bcc8&gt; Now I need to loop through this object and get the xpath of every element in it. (every single element inside the xml file). Any ideas?
score: 1

http://stackoverflow.com/a/48981580
accepted answer of: http://stackoverflow.com/q/48981557
type: Answer
upvote count: 2
has body: You access the .columns field and then calculate your columns like: Code: df.columns = ['Data_{}'.format(int(i)+1) for i in df.columns] Test Code: df = pd.read_fwf(StringIO(u""" MAC 0 1 2 3 4 5 ID1 1 1 2 3 3 4 ID2 6 6 7 7 8 9 ID3 1 2 3 3 4 5"""), header=1).set_index('MAC') print(df) df.columns = ['Data_{}'.format(int(i)+1) for i in df.columns] print(df) Results: 0 1 2 3 4 5 MAC ID1 1 1 2 3 3 4 ID2 6 6 7 7 8 9 ID3 1 2 3 3 4 5 Data_1 Data_2 Data_3 Data_4 Data_5 Data_6 MAC ID1 1 1 2 3 3 4 ID2 6 6 7 7 8 9 ID3 1 2 3 3 4 5
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48981557
downvote count: 0

http://stackoverflow.com/comment/85134428
type: QuestionComment
score: 1
has text: This only works for binary classification. Are you sure the `y` contains only two classes.
comment on: http://stackoverflow.com/q/49055410
type: Comment

http://stackoverflow.com/comment/85110908
comment on: http://stackoverflow.com/q/49052983
type: Comment
type: QuestionComment
score: 1
has text: yes it works when i use the python console : python3. import PyPDF2 works perfect

http://stackoverflow.com/comment/85070953
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49032269
has text: I'd be surprised if it was a Django 2.0 issue. I can't see any issues with your current view, and I'm not in a position to test it, so I don't have any other suggestions. Note that overriding `__init__` in class based views is unusual, usually you'd override other methods instead.
score: 0

http://stackoverflow.com/comment/85153090
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49016505
type: Comment
has text: Hey I just realized what you mean by implementing using the built in functions. After using cross_val_score(model,x,y,cv=5), I got the kfold to work. I'm still not sure why my implementation doesn't work. Thanks for your help.

http://stackoverflow.com/comment/85026566
has text: The only times where isinstance() is necessary is when checking inheritance of a given class compared to another, as you well said and referenced. type() shall be only used to check whether an instance is exactly of a given base type. thanks to @zmo here's the link https://stackoverflow.com/questions/21894575/isinstancefoo-bar-vs-typefoo-is-bar
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49010949
score: 1

http://stackoverflow.com/q/49112027
has comment: http://stackoverflow.com/comment/85245847
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/51136295
has title: Tensorflow function tf.image.crop_and_resize is not working as expected
tagged with: tensorflow
type: Question
answer count: 2
has body: I have the next snippet of code. import numpy as np from scipy.misc import imread import tensorflow import matplotlib.pyplot as plt img = imread('dog.jpg') plt.imshow(img) plt.show() h, w, _ = img.shape cnr = tensorflow.image.crop_and_resize(np.expand_dims(img, 0), np.array([[0., 0.5, 0., 0.5]]), [0], (h/2, w/2)) plt.imshow(img[0:h/2, 0:w/2, :]) plt.show() with tensorflow.Session() as sess: a = sess.run(cnr) plt.imshow(a[0]) plt.show() If I understand the method crop_and_resizecorrectly, the first plt.imshow should show the original image and the next two calls should show the same portion of the image, since I am cropping the image and resizing to the same shape (so not resizing should be taking place here). However, the last call to plt.show only shows a purple image. What am I doing wrong?
has answer: http://stackoverflow.com/a/49120452
tagged with: image
score: 0

http://stackoverflow.com/comment/99912226
comment on: http://stackoverflow.com/a/56331382
type: AnswerComment
score: 0
type: Comment
has text: I ran into the same issue but found client.max_message_size gave me the correct upper bound (~4MB whereas max_bson_size is ~16MB).

http://stackoverflow.com/q/49036807
has answer: http://stackoverflow.com/a/49036946
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49037253
has title: If statement that keeps characters only
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/49036867
has comment: http://stackoverflow.com/comment/85079089
has answer: http://stackoverflow.com/a/49036851
type: Question
possible better answer: http://stackoverflow.com/a/49036851
answer count: 6
tagged with: string
has comment: http://stackoverflow.com/comment/85078547
score: 0
tagged with: letter
tagged with: python
has answer: http://stackoverflow.com/a/49036867
favorite count: 0
has answer: http://stackoverflow.com/a/49036904
has answer: http://stackoverflow.com/a/49036836
has body: Let's say we have a list list_a = [a,b,C,.,/,!,d,E,f,] I want to append to a new list only the letters of the alphabet. So the new list will be list_b = [a,b,C,d,E,f]. So far I have tried the following: list_b = [] for elements in list_a: try: if elements == str(elements): list_b.append(elements) except ValueError: #Catches the Error when the element is not a letter continue However, when I print the list_b it has all the elements of list_a, it doesn't do the job I expected. Also, a comma in the example above brings an error. Any ideas ?
has comment: http://stackoverflow.com/comment/85078889
has comment: http://stackoverflow.com/comment/85078622
has comment: http://stackoverflow.com/comment/85078585
linked to: http://stackoverflow.com/q/3640359
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/49061483
has body: I'm using Django with the REST Framework. I'm defining an APIView and in it, I create an ORM object using create(). One of the fields I pass the create function is failing, saying it's not a valid keyword argument. This is a new field I'm adding. The field exists in the model and the serializer. Another similar new field is NOT failing. Traceback: Internal Server Error: /api/new_thing Traceback (most recent call last): File "/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/local/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) File "/other_app/rest_apis.py", line 336, in post flag=false File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create obj = self.model(**kwargs) File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'doohickeys' is an invalid keyword argument for this function API View: class NewThing(APIView): renderer_classes = (JSONRenderer,) serializer_class = StuffSerializer @detail_route(methods=['POST']) def post(self, request, pk, format=None): # do stuff whatsits_list = [] # list of ORM objects doohickeys_list = [] # list of ORM objects thing = Thing…
has comment: http://stackoverflow.com/comment/85168654
answer count: 1
has answer: http://stackoverflow.com/a/49064698
has title: Django REST framework: "invalid keyword argument" error but field exists in the model
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85128379
has comment: http://stackoverflow.com/comment/85130456
type: Question
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/85128105
score: 0

http://stackoverflow.com/a/48967278
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48967207
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48967207
has body: If the +0000 is fixed you can add it to the format string like: Code: pd.to_datetime(df['Datetime'], format='%d/%m/%Y %I:%M:%S %p +0000', utc=True) Test Code: df = pd.DataFrame([ '11/09/2011 11:33:00 PM +0000', '11/09/2011 11:33:00 PM +0000', '11/09/2011 11:33:00 PM +0000', ], columns=['Datetime']) print(df) df['Datetime'] = pd.to_datetime( df['Datetime'], format='%d/%m/%Y %I:%M:%S %p +0000', utc=True) print(df) Results: Datetime 0 11/09/2011 11:33:00 PM +0000 1 11/09/2011 11:33:00 PM +0000 2 11/09/2011 11:33:00 PM +0000 Datetime 0 2011-09-11 23:33:00+00:00 1 2011-09-11 23:33:00+00:00 2 2011-09-11 23:33:00+00:00

http://stackoverflow.com/comment/85220659
type: AnswerComment
has text: Ok @Pam the code worked well, but the number of columns in csv file are too exceeded, so I want to remove zero columns before writting in csv file. (I've put an instance of input in the question)
type: Comment
comment on: http://stackoverflow.com/a/49070833
score: 0

http://stackoverflow.com/q/49099392
tagged with: python
tagged with: selenium-webdriver
has body: I am writing a script that interacts with a website using requests - at some point the cookies need to transferred into selenium as a part of the work needs to be done on a webdriver. import requests from bs4 import BeautifulSoup import time import cfscrape from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException scraper = cfscrape.create_scraper() headers = {'Referer': 'https://www.off---white.com/en/GB/login'} payload = { 'utf8':'✓', 'authenticity_token':'', 'spree_user[email]': LOGIN_EMAIL, 'spree_user[password]': PASSWORD, 'spree_user[remember_me]': '0', 'commit': 'Login' } r = scraper.post('https://www.off---white.com/en/GB/login', data=payload, headers=headers) if r.status_code != 200: print('Failed to log in') else: print('Successfully logged in!') cookiesexport = scraper.cookies driver = webdriver.Chrome() driver.get("https://www.off---white.com/en/GB") time.sleep(10) driver.add_cookie(cookiesexport) time.sleep(2) driver.get("https://www.off---white.com/en/GB/checkout/payment") When I run the code above I get the following error: TypeError: Object of type 'RequestsCookieJar' is not JSON serializable I presume this is due to scraper.cookies not being in JSON format. My question is how do I export the cookies in JSON format?
has comment: http://stackoverflow.com/comment/85204107
tagged with: python-requests
has comment: http://stackoverflow.com/comment/85204791
type: Question
has comment: http://stackoverflow.com/comment/85204253
score: 0
has title: Exporting session.cookies as JSON
has comment: http://stackoverflow.com/comment/85206427
answer count: 1
has comment: http://stackoverflow.com/comment/85205409
has comment: http://stackoverflow.com/comment/85204621
has comment: http://stackoverflow.com/comment/85205159
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85205225
has answer: http://stackoverflow.com/a/49100608

http://stackoverflow.com/a/49005287
score: 1
accepted answer of: http://stackoverflow.com/q/49004624
type: AcceptedAnswer
downvote count: 0
has body: You need something like this df1 = pd.read_csv('CSV-1.csv') df2 = pd.read_csv('CSV-2.csv') Merge both dataframes df3 = df1.merge(df2, on="filename", how="outer",suffixes=('-1', '-2')) Remove the rows with same number of changes df3 = df3[df3['number_of_changes-1'] != df3['number_of_changes-2']] Fill NAs with 0 and sort by filename df3.fillna(0, inplace=True) df3 = df3.sort_values(by ='filename').reset_index(drop=True) output: filename number_of_changes-1 number_of_changes-2 0 B 10.0 15.0 1 C 10.0 0.0 2 D 0.0 30.0 3 E 5.0 10.0 4 F 15.0 0.0
answers question: http://stackoverflow.com/q/49004624
type: Answer
upvote count: 1

http://stackoverflow.com/comment/85187698
has text: I edited the question in case it was unclear: I'm trying to generate a 2d array, which is what I'm stuggling with. I'm passing eveything through .lower(), so case shouldn't be an issue.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49088626
type: Comment

http://stackoverflow.com/a/48983761
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48983657
downvote count: 0
score: 1
has body: You haven't call function in which you have defined properties. Just call function by adding _price_inputs() to your code at last: from tkinter import * import tkinter.messagebox def message(): text='''sfjkasjdfkjasdfjsdjfjsdlfjasd fjsdkfjksadjfsajdjfl sdfasdjflsjdlfsldjflsjd''' tkinter.messagebox.showinfo("showing",text) def _price_inputs(): win2 = Tk() win2.title("Transactions for the project Botique") win2.geometry("1600x800+0+0") win2.configure(bg="black") framex = Frame(win2,width=1600,bg="RoyalBlue4",height=100,relief=GROOVE).pack(side=TOP) frame1 = Frame(win2,width=1000, height=400,bg="white", relief=SUNKEN).pack(side=RIGHT,fill=Y) frame2 = Frame(win2, width=775,height=100,bg="white", relief=FLAT).pack(side=BOTTOM) frame3 = Frame(win2,width=600,height=430,bg="gray",relief=FLAT).pack(side=LEFT,fill=X) #framex == heading #frame1 == showing the infos #frame2 == bottom_infos #frme3 == adding the buttons and widgets #==++++===========================title============================= lbl1 = Label(framex,font=("arial", 30, "bold"),bg="powder blue",fg="green",text="Hello this is the title of the page",bd=10,relief=GROOVE).pack(side=TOP) btn1 = Button(frame1,font=("arial",20,"bold"),bg="powder blue",fg="white",text="click me").pack() win2.mainloop() _price_inputs()

http://stackoverflow.com/comment/85202888
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49036643
has text: Thanks, this approach has also speeded up the process!

http://stackoverflow.com/comment/84990480
type: Comment
comment on: http://stackoverflow.com/q/48992373
type: QuestionComment
has text: @L_Church think you
score: 0

http://stackoverflow.com/q/49080955
accepted answer: http://stackoverflow.com/a/49098457
type: AnsweredQuestion
tagged with: blockchain
has comment: http://stackoverflow.com/comment/85171777
downvote count: 1
type: Question
has body: I am looking to do some analysis on the Ethereum blockchain, particularly, look for correlations in the data between available hash power and transaction confirmation times. However, I am unable to make sense of how to go about downloading either of the blockchains or extract the transaction and worker information from them. Ideally, I would download the blockchains, then use a python script to extract the relevant information from the blockchain to a CSV file or something like that? Any pointers on how this can be achieved?
upvote count: 5
has answer: http://stackoverflow.com/a/49099307
score: 4
tagged with: ethereum
answer count: 3
has answer: http://stackoverflow.com/a/49098457
possible better answer: http://stackoverflow.com/a/49099307
has comment: http://stackoverflow.com/comment/85167746
has answer: http://stackoverflow.com/a/51287002
favorite count: 0
tagged with: data-analysis
tagged with: python
has title: Extracting information from the Ethereum blockchain with python

http://stackoverflow.com/q/48984287
score: -7
has title: comparing two tab seperated files for multiple column and combine matches
has comment: http://stackoverflow.com/comment/85021106
upvote count: 0
answer count: 1
favorite count: 0
tagged with: command
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84973650
has comment: http://stackoverflow.com/comment/84981656
has body: I need to compare two files for first two columns and select the matched ones with additional information of second file like; input1: 0 1 2 4 5 6 input2: 2 4 xyz 5 4 asv 0 1 qwe output is 2 4 xyz 0 1 qwe i tried this at python but does not work properly; like if there are more 1 at first column it cannot give proper output #!/usr/bin/python import sys f1 = 'file1.txt' f2 = 'file2.txt' if len(sys.argv) == 3: f1 = sys.argv[1] f2 = sys.argv[2] with open(f1) as file_1, open('out.txt', 'w') as of: for l1 in file_1: col_of_f1 = int(l1.split()[0]) with open(f2) as file_2: for l2 in file_2: col_of_f2 = l2.split() if len(col_of_f2) &lt; 1: break col_of_f2 = int(col_of_f2[0]) if col_of_f1 == col_of_f2: of.write(l2) break
downvote count: 7
type: Question
tagged with: perl
has answer: http://stackoverflow.com/a/49217206

http://stackoverflow.com/comment/85084754
type: Comment
type: QuestionComment
score: 1
has text: Welcome to Stack Overflow. Please take the [tour](https://stackoverflow.com/tour) and read about [How to Ask](https://stackoverflow.com/questions/how-to-ask). Thanks for the code snippet, but a more [fleshed out example](https://stackoverflow.com/help/mcve) will make it easier for people to help you.
comment on: http://stackoverflow.com/q/49039465

http://stackoverflow.com/comment/85089633
score: 0
has text: Sorry I'm new to django, could you explain your code a little bit.
type: AnswerComment
comment on: http://stackoverflow.com/a/49042234
type: Comment

http://stackoverflow.com/comment/85002620
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48998583
score: 0
has text: Can't u do this in a for loop and what id df ? will it be an array of size equal to ur input number and u are trying to do & of all the elements ?

http://stackoverflow.com/comment/85040784
has text: It works, its just an error printed on the screen but the assistant works.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49000135

http://stackoverflow.com/comment/84956105
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48975347
has text: @Basj `"How do this properly with Python 2.7?"` What are you trying to do exactly? You haven't described why the prefix is an issue or why the characters are an issue either. You say you want to "output the data to screen before storing anything in the DB" and one answer shows that you can print it to the screen and my answer shows a way you could save it with the characters intact. What is the issue? What is your actual question?
score: 0

http://stackoverflow.com/comment/85037275
has text: @VíctorMartínez: I'm not saying you need a `break`; I'm saying you *don't* need an `else`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49016088
type: Comment
score: 3

http://stackoverflow.com/comment/84943698
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48968886
has text: Possible duplicate of [Deep copy a list in Python](https://stackoverflow.com/questions/17873384/deep-copy-a-list-in-python)
score: 0

http://stackoverflow.com/comment/85132095
has text: The error message in the pip installation command, the error seems to be coming from "sysconfig". Maybe this is relevant: https://github.com/conda/conda/issues/6648
comment on: http://stackoverflow.com/q/49063379
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85123745
type: QuestionComment
comment on: http://stackoverflow.com/q/49058729
score: 0
has text: result is initialized with a literal integer 0 _in python_. In python that does not and should not coerce the return value to a certain type, so numba ensures that the same contract holds true in its produced code
type: Comment

http://stackoverflow.com/comment/85200515
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49093821
has text: Thanks @YannVernier. I got it now like you said, first one is editing same object and second one is just referencing to new object.

http://stackoverflow.com/comment/85248504
comment on: http://stackoverflow.com/q/49047519
score: 0
type: Comment
type: QuestionComment
has text: No worries, Simon. I like that encoding trick. Maybe you should post that as an answer.

http://stackoverflow.com/q/49066293
tagged with: python
has title: Python 2.7 list change in dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49066885
score: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85137594
has comment: http://stackoverflow.com/comment/85137585
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85137663
has body: My dictionary is as below { '34.8': [[0, 0, 0, 0], [0, 0, 0, 0]], '34.6': [[0, 0, 0, 0], [0, 0, 0, 0]], '35.0': [[0, 0, 0, 0], [0, 0, 0, 0]], '34.4': [[0, 0, 0, 0], [0, 0, 0, 0]], '34.2': [[0, 0, 0, 0], [0, 0, 0, 0]], '34.0': [[0, 0, 0, 0], [0, 0, 0, 0]] } and I run code. print '34.6', testDic['34.6'] print '34.8', testDic['34.8'] testDic['34.6'][0][0] = 1234 print testDic but result is { '34.8': [[1234, 0, 0, 0], [0, 0, 0, 0]], '34.6': [[1234, 0, 0, 0], [0, 0, 0, 0]], '35.0': [[1234, 0, 0, 0], [0, 0, 0, 0]], '34.4': [[1234, 0, 0, 0], [0, 0, 0, 0]], '34.2': [[1234, 0, 0, 0], [0, 0, 0, 0]], '34.0': [[1234, 0, 0, 0], [0, 0, 0, 0]]} why change all dic value ?? and how do I change only 1 (such as '34.6') ??
has answer: http://stackoverflow.com/a/49066885
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/240178

http://stackoverflow.com/a/48982693
upvote count: 1
has body: You can combine many Q objects with () signs. I your case I suppose this will work: single_events = crm_models.EventsMeta.objects.filter( (Q(event_type="single") &amp; Q(repeat_start=today)) | (Q(event_type="recurring") &amp; Q(repeat_start__lte=today)) )
accepted answer of: http://stackoverflow.com/q/48982618
answers question: http://stackoverflow.com/q/48982618
has comment: http://stackoverflow.com/comment/84972844
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/49032767
answer count: 2
possible better answer: http://stackoverflow.com/a/49032902
has answer: http://stackoverflow.com/a/49032902
downvote count: 0
has title: How can I apply a vectorized function to the previous element of a numpy array?
accepted answer: http://stackoverflow.com/a/49033113
favorite count: 0
linked to: http://stackoverflow.com/q/49532575
upvote count: 2
has comment: http://stackoverflow.com/comment/85070177
tagged with: python
tagged with: vectorization
linked to: http://stackoverflow.com/q/48864790
has body: I want to apply a function like this: s[i] = a*x[i] + (1 - a)*s[i-1] where s and x are both arrays of the same length. I don't want to use a for loop as these arrays are very large (>50 mil). I have tried doing something like this def f(a,x): s = [0]*len(x) s[i] = a*x[i] + (1 - a)*s[i-1] return s but of course i isn't defined so this doesn't work. Is there a way to do this using map or numpy.apply_along_axis or some other vectorized method? I haven't come across a method that applies functions to current and previous elements of an array without using for loops, and that is really what I want to understand how to do here. EDIT To be unambiguous, here is the for loop implementation which works but that I want to avoid s = [0]*len(x) a=0.45 for i in range(len(x)): s[i] = a*x[i] + (1-a)*s[i-1] s[0] = x[0] # reset value of s[0]
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85071548
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49033113
tagged with: arrays
has comment: http://stackoverflow.com/comment/85070375
has comment: http://stackoverflow.com/comment/85070485

http://stackoverflow.com/comment/85227798
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49097696
has text: Well, this code patch was refactored in one of the last PRs. Maybe you should compile the latest one and see if it works now. I still highly recommend investigating the bug. It might be that something completely different is (still) wrong.

http://stackoverflow.com/a/49021035
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85047654
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49020509
answers question: http://stackoverflow.com/q/49020509
score: 3
downvote count: 0
has body: It would be easier if you attached the paper, but from what we have, it should be as following: 3@1x5x5 means kernel size is 5-by-5, 1 is the number of channels of the input, 3 is the number of channels of the output. I have not used Keras, but it should look like: model = Sequential() model.add(BatchNormalization(input_shape=(36,36))) model.add(Conv2D(3, (5, 5), activation='relu')) model.add(Conv2D(3, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(3, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors model.add(Dense(75, activation= 'relu')) model.add(Dense(10, activation= 'relu')) model.add(Dense(2, activation= 'softmax')) model.compile(Adam(lr=.01), loss='categorical_crossentropy', metrics=['accuracy'])

http://stackoverflow.com/comment/85098951
type: Comment
has text: Thanks. I tried that and restarted apache but same problem. Also, when I added the WSGIPythonPath parameter it would not restart the Apache server. I did a systemctl status apache2.service and it reports: WSGIPythonPath cannot occur within <VirtualHost> section. I guess I should be adding that parameter to the httpd.conf but there isn't one. My virtual host is defined in a conf file that is registered with apache using the a2ensite command.
comment on: http://stackoverflow.com/a/49043424
score: 0
type: AnswerComment

http://stackoverflow.com/q/49011261
has comment: http://stackoverflow.com/comment/85028083
answer count: 1
accepted answer: http://stackoverflow.com/a/49053835
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
has body: I have a list of person IDs, and for each ID, I want to extract all available information from two different dataframes. In addition, the types of information also have IDs, and I only want specific information IDs for each person ID. Here's how I'm currently doing this: new_table = [] for i in range(ranges): slice = pd.concat([df1[sp.logical_and(df1.person.values == persons[i], df1['info_id'].isin(info_ids))], df2[sp.logical_and(df2.person.values == persons[i], df2['info_id'].isin(info_ids))]], ignore_index=True) if len(list(set(slice['info_ids']))) &lt; amount_of_info_needed: continue else: full_time_range = max(slice['age_days']) - min(slice['age_days']) if full_time_range &lt;= 1460: new_table.append(slice) else: window_end = min(slice['age_days']) + 1460 slice = slice[slice.age_days &lt; window_end+1] if len(list(set(slice['info_id']))) &lt; amount_of_info_needed: continue else: new_table.append(slice) #return new_table new_table = pd.concat(new_table, axis=0) new_table = new_table.groupby(['person', 'info_id']).agg(np.mean).reset_index() new_table.to_sql('person_info_within4yrs', engine, if_exists='append', index=False, dtype={'person': types.NVARCHAR(32), 'value': types.NVARCHAR(4000)}) I read about not using pd.concat in a loop because of quadratic time, but I tried converting the dataframes to arrays and slicing and concatenating those, but that went even slower than using pd.concat. After profiling each line with %lprun, all of the time is being consumed with the pd.concat/logical_and operation in the loop. This code is also faster than using .loc with both dataframes and concatenating two slices together. After the if-else blocks, I append to a list and at the end, turn the list into a dataframe. Edit: Here is an example of what I'm doing. The goal is to slice from both dataframes by person_id and info_id, combine the slices, and append the combined slice to a list, which I will then turn back into a dataframe and export to a SQL table. The if-else blocks…
has comment: http://stackoverflow.com/comment/85028090
type: Question
has comment: http://stackoverflow.com/comment/85028473
has answer: http://stackoverflow.com/a/49053835
has title: Fastest way to combine two slices from two pandas dataframes in a loop?
score: 0
tagged with: pandas

http://stackoverflow.com/a/49100593
has body: The best way, if it suits your use case, is to use collections.Iterable. Because this is such a common task, I tend to wrap it in a function: from collections import Iterable def iterify(obj): return obj if isinstance(obj, Iterable) else [obj] deref = [orig[x].value.flatten() for x in iterify(y)] But note the documentation: Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj).
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49100416
upvote count: 2
downvote count: 1

http://stackoverflow.com/q/48996044
tagged with: mnist
linked to: http://stackoverflow.com/q/16696251
has title: Loading own dataset like MNIST images
has body: I am trying to load my own hand written images and test them in my MNIST model. But, i need to pre process the images first. I have 100 images, 10 of every 10 digits saved on the folder images. I am getting error and i don't know if this code works. Any help? import cv2 from os import listdir from os.path import isfile, join import numpy as np from PIL import Image from scipy import ndimage import math def loadImages(path): imagesList = listdir(path) loadedImages = [] for image in imagesList: gray = cv2.imread("image", cv2.CV_LOAD_IMAGE_GRAYSCALE) gray = cv2.resize(255-gray, (28, 28)) (thresh, gray) = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) while np.sum(gray[0]) == 0: gray = gray[1:] while np.sum(gray[:,0]) == 0: gray = np.delete(gray,0,1) while np.sum(gray[-1]) == 0: gray = gray[:-1] while np.sum(gray[:,-1]) == 0: gray = np.delete(gray,-1,1) rows,cols = gray.shape if rows &gt; cols: factor = 20.0/rows rows = 20 cols = int(round(cols*factor)) gray = cv2.resize(gray, (cols,rows)) else: factor = 20.0/cols cols = 20 rows = int(round(rows*factor)) gray = cv2.resize(gray, (cols, rows)) colsPadding = (int(math.ceil((28-cols)/2.0)),int(math.floor((28-cols)/2.0))) rowsPadding = (int(math.ceil((28-rows)/2.0)),int(math.floor((28-rows)/2.0))) gray = np.lib.pad(gray,(rowsPadding,colsPadding),'constant') shiftx,shifty = getBestShift(gray) shifted = shift(gray,shiftx,shifty) gray = shifted loadedImages.append(gray) return loadedImages def getBestShift(img): cy,cx = ndimage.measurements.center_of_mass(img) rows,cols = img.shape shiftx = np.round(cols/2.0-cx).astype(int) shifty = np.round(rows/2.0-cy).astype(int) return shiftx,shifty path = 'images/' def shift(img,sx,sy): rows,cols = img.shape M = np.float32([[1,0,sx],[0,1,sy]]) shifted = cv2.warpAffine(img,M,(cols,rows)) return shifted imgs = loadImages(path) rgb=np.array(imgs) Error:AttributeError: module 'cv2.cv2' has no attribute 'CV_LOAD_IMAGE_GRAYSCALE'
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84997706
downvote count: 2
linked to: http://stackoverflow.com/q/23339315
has answer: http://stackoverflow.com/a/49034725
type: Question
tagged with: opencv
score: -2

http://stackoverflow.com/q/49059526
type: Question
has answer: http://stackoverflow.com/a/49060352
has body: I am now scraping this website on a daily basis, and am using DeltaFetch to ignore pages which have already been visited (a lot of them). The issue I am facing is that for this website, I need to first scrape page A, and then scrape page B to retrieve additional information about the item. DeltaFetch works well in ignoring requests to page B, but that also means that every time the scraping runs, it runs requests to page A regardless of whether it has visited it or not. This is how my code is structured right now: # Gathering links from a page, creating an item, and passing it to parse_A def parse(self, response): for href in response.xpath(u'//a[text()="詳細を見る"]/@href').extract(): item = ItemLoader(item=ItemClass(), response=response) yield scrapy.Request(response.urljoin(href), callback=self.parse_A, meta={'item':item.load_item()}) # Parsing elements in page A, and passing the item to parse_B def parse_A(self, response): item = ItemLoader(item=response.meta['item'], response=response) item.replace_xpath('age',u"//td[contains(@class,\"age\")]/text()") page_B = response.xpath(u'//a/img[@alt="周辺環境"]/../@href').extract_first() yield scrapy.Request(response.urljoin(page_B), callback=self.parse_B, meta={'item':item.load_item()}) # Parsing elements in page B, and yielding the item def parse_B(self, response): item = ItemLoader(item=response.meta['item']) item.add_value('url_B',response.url) yield item.load_item() Any help would be appreciated to ignore the first request to page A when this page has already been visited, using DeltaFetch.
has title: Ignoring requests while scraping two pages
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49060352
favorite count: 0
tagged with: scrapinghub
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/q/49046616
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85097793
type: UnansweredQuestion
score: -3
linked to: http://stackoverflow.com/q/7014953
tagged with: python
has title: How would I securely prevent a user from getting a string in my script?
linked to: http://stackoverflow.com/q/12042724
downvote count: 3
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85098972
has answer: http://stackoverflow.com/a/49048040
has body: If I was to give a python script to someone to run, they would have to run it with an API key to allow access to the server. Is there any way I can prevent them from seeing the key but still be able to use it.
answer count: 1
has comment: http://stackoverflow.com/comment/85097844

http://stackoverflow.com/q/49083766
has body: I have the following lists making up a dict, consisting of some scraped data from the interwebz: names = ['Progressor GTI + RS10 PR 17/18, alpinski, unisex', 'Alpine Skis The Curv DTX 16/17, alpinski, carving', 'Alpine Skis Dobermann Spitfire Ti 16/17, alpinski', 'Redster G7 + X12 17/18, alpinski, unisex', 'Redster S7 + XT12 17/18, alpinski, unisex', 'Redster WT + Binding 17/18, carvingski, unisex', 'PRO MTN 77 + MBS 10PR 17/18, alpinski, unisex', 'Hero Elite HP NX 12 Konect WTR B80 17/18, carvingski, unisex', 'All Mountain Skis Pinnacle 95 15/16, frikjøringsski', 'Alpine Skis Progressor F17 16/17, alpinski, carving', 'Alpine Skis Pro Mtn 77 16/17, alpinski, all mountain', 'Twintip Skis Domain 17/18, alpinski, jib/park', 'Cloud 9 Woman + Litium 10 17/18, alpinski, dame', 'Redster GT + Lithium 10 17/18, carvingski, unisex', 'Alpine Skis Aspire W 17/18 , alpinski, carving, dame', 'Alpine Skis Speed Zone 7 Express 11 16/17, alpinski', 'Hero Elite All Turn XPRESS 11 B83 17/18, alpinski', 'Balanze Woman + Litium 10 17/18, alpinski, dame', 'Alpine Skis Cloud Nine W Lith 10 , alpinski, dame, all mountain', 'Passion PRO/Xpress 10 Woman B83 17/18, carvingski, dame', 'Avenger 75 m/Adv Pro binding', 'Alpine Skis NRGY 85 (flat) 16/17, alpinski', 'Alpine Skis GT 74 Adv Evo 17/18, alpinski', 'Alpine Skis Sentra S2 Pro Evo 17/18, alpinski, dame', 'Twintip Skis Sight 17/18, parkski', 'Alpine Skis Zenith Xpress B83 16/17, alpinski', 'Alpine Skis Intense 6 W 16/17, alpinski, dame', 'Zenith PRO/Xpress 10 B83 17/18, carvingski', 'Performer XT Fibre + Lithium AW 17/18, alpinski, unisex', 'Alpine Skis Performer Lithium Usx 16/17, bakkeski', 'Team Jr 4.5 binding 100-120 17/18, carvingski, barn/junior', 'Alpine Skis Vantage Jr III XTE7 17/18, bakkeski, junior', 'PCarv Kids Blue 17/18, alpinski, barn/junior', 'PCarv Kids Pink 17/18, alpinski, barn/junior', 'Alpine Skis Team Jr 7.0 binding 16/17, alpinski med binding, junior', 'Redster Jr J2 130-150 + L7 ET 17/18, alpinski, junior', 'Alpine …
upvote count: 3
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49083925
answer count: 2
has answer: http://stackoverflow.com/a/49083844
accepted answer: http://stackoverflow.com/a/49083844
tagged with: pandas
favorite count: 0
possible better answer: http://stackoverflow.com/a/49083925
has title: How to only print dict key/value combinations for a subset of key/value?
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/85045590
has text: I have few questions ... Are you doing predictions by this architecture ?? Did you check you regenerated images with individual deconv layers... How is the addition operation of the individual deconv layers happening.. Is the addition by another layer or just simple addition of tensors ?? In the code i see simple addition of all by `tf.add`... Is this true ??
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49016723

http://stackoverflow.com/comment/85061813
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49028675
has text: yes of course. If individual =1, the above dataset only has 'A' and 'B' values. Now, I want to create all unique combination of these two values (tuple), therefore it should create a list with the tuple (A,B). The next is Individual=2. Here is only has the value 'A' therefore there is no tuple to append to the list. Next its Individual '3', which has the company values 'A' and 'C'. Therefore it should add (A,C) to the list. Etc.
type: Comment

http://stackoverflow.com/q/48996733
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84999400
has comment: http://stackoverflow.com/comment/85057449
tagged with: python
has body: I know this one: Find p-value (significance) in scikit-learn LinearRegression I've never extended a class in python and I'm not sure whether this is the right solution for me (I've tried but getting a TypeError). I'm calculating an elastic net regression with scikitlearn. Since my regressors are in a sparse matrix, Statsmodels package is not an option. Thus, I'm looking for a reliable solution to calculate p-values for each coefficient in my elastic net regression. Is there a solution given by scikitlearn nowadays?
answer count: 0
type: Question
score: 0
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/27928275
has title: p-values for each coefficient ElasticNetCV()
has comment: http://stackoverflow.com/comment/84998834

http://stackoverflow.com/comment/85146913
comment on: http://stackoverflow.com/q/49069317
score: 0
type: Comment
has text: Maybe try `normalize()` to range 0..255 with `NORM_MINMAX` before display.
type: QuestionComment

http://stackoverflow.com/a/48976411
has comment: http://stackoverflow.com/comment/84960104
has comment: http://stackoverflow.com/comment/84958445
has comment: http://stackoverflow.com/comment/84962586
has comment: http://stackoverflow.com/comment/84958394
type: Answer
has comment: http://stackoverflow.com/comment/84960333
answers question: http://stackoverflow.com/q/48974523
has comment: http://stackoverflow.com/comment/84960291
has body: One way to do is to use Queue, which can share details about api-call timestamps with other processes. Below is an example how this could work. It takes the oldest entry in queue, and if it is younger than one second, sleep functions is called for the duration of the difference. from multiprocessing import Pool, Manager, queues from random import randint import time MAX_CONNECTIONS = 10 PROCESS_COUNT = 4 def api_request(a, b): time.sleep(randint(1, 9) * 0.03) # simulate request return a, b, time.time() def parallel_requests(a, b, the_queue): try: oldest = the_queue.get() time_difference = time.time() - oldest except queues.Empty: time_difference = float("-inf") if 0 &lt; time_difference &lt; 1: time.sleep(1-time_difference) else: time_difference = 0 print("Current time: ", time.time(), "...after sleeping:", time_difference) the_queue.put(time.time()) return api_request(a, b) if __name__ == "__main__": m = Manager() q = m.Queue(maxsize=MAX_CONNECTIONS) for _ in range(0, MAX_CONNECTIONS): # Fill the queue with zeroes q.put(0) p = Pool(PROCESS_COUNT) # Create example data data_length = 100 data1 = range(0, data_length) # Just some dummy-data data2 = range(100, data_length+100) # Just some dummy-data queue_iterable = [q] * (data_length+1) # required for starmap -function list_of_lists = p.starmap(parallel_requests, zip(data1, data2, queue_iterable)) print(list_of_lists)
score: 0

union
type: Tag
tags question: http://stackoverflow.com/q/49090488
tag name: union

http://stackoverflow.com/comment/85235769
type: Comment
comment on: http://stackoverflow.com/a/49114882
score: 0
type: AnswerComment
has text: I am working on Python2 that's the reason I was caught up in this tiny issue. I guess I should upgrade to Python3 to avoid running into such issues further.

http://stackoverflow.com/q/49010129
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85024732
tagged with: list
has answer: http://stackoverflow.com/a/68234842
has title: how list actually works in python using for-loop?
accepted answer: http://stackoverflow.com/a/49010221
possible better answer: http://stackoverflow.com/a/49010450
type: Question
has answer: http://stackoverflow.com/a/49010450
tagged with: for-loop
upvote count: 5
has comment: http://stackoverflow.com/comment/85024670
has body: I tried this code, I don't understand how it works a=[1,'a',2,'b','test','exam'] for a[-1] in a: print(a[-1]) output 1 a 2 b test test
score: 4
answer count: 3
has comment: http://stackoverflow.com/comment/85025171
has answer: http://stackoverflow.com/a/49010221
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85024766
tagged with: python
has comment: http://stackoverflow.com/comment/85025085

http://stackoverflow.com/q/49049467
answer count: 0
has comment: http://stackoverflow.com/comment/85103140
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85105443
has comment: http://stackoverflow.com/comment/85105124
has comment: http://stackoverflow.com/comment/85105514
has body: After I use the loss function designed myself,the loss become NAN in the first batch. my network is the Resnet and I think it is alright because I trained it with the softmax loss. And here is my 'loss': def loss2(logits,labels): logit_t = tf.transpose(logits) logits2 = tf.multiply(logits,logits) sum1 = tf.reduce_sum(logits2,1) sum1_t = tf.transpose(sum1) product = tf.matmul(logits,logit_t) sum_2 = sum1 + sum1_t H = sum_2 - product mean = tf.reduce_mean(H) H = tf.exp(-H/mean+1e-10) kv,ki = tf.nn.top_k(H,5) kmin = tf.reduce_min(kv,axis = 1)[:,None] new_mat = tf.where(H&lt;kmin,tf.zeros_like(H),tf.ones_like(H)) H_top = tf.multiply(H,new_mat) H_top_t = tf.transpose(H_top) #H_top_t = tf.transpose(H_top) H_top_sum = tf.reduce_sum(H_top,1) H_top_de = tf.diag(H_top_sum) H_top_deinv = tf.diag(1/H_top_sum) w = [0.6,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04,0.04] #w = [0.6,0.04,0.04,0.04,0.04,0.04,0.04,0.04] w = tf.convert_to_tensor(w) W = tf.diag(w) H_top_devec = tf.matmul(H_top,W) H_top_devec = tf.reduce_sum(H_top_devec,1) H_top_dvinv2 = tf.sqrt(H_top_devec) H_top_dvinv2 = tf.diag(H_top_dvinv2) theta = tf.matmul(H_top_dvinv2,H_top_t) theta = tf.matmul(theta,W) theta = tf.matmul(theta,H_top_deinv) theta = tf.matmul(theta,H_top) theta = tf.matmul(theta,H_top_dvinv2) temp2 = tf.ones_like(w) f = 0.01*(tf.diag(temp2)-theta) y = [[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]] #y=[[1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]] y = tf.convert_to_tensor(y) y = tf.transpose(y) f = tf.matrix_inverse(f) f = tf.matmul(f,y) f_t = tf.transpose(f) omiga = tf.matmul(f_t,(tf.ones_like(theta)-theta)) omiga = tf.matmul(omiga,f) loss1 = omiga+0.01*tf.square(f-y) return loss1 I just want to know,which step in the loss may cause the loss become NAN....And how to find it. please help me! Thanks a lot!!!
tagged with: loss-function
has comment: http://stackoverflow.com/comment/85103276
score: 0
has title: Tensorflow NAN with loss
tagged with: nan
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85167814

http://stackoverflow.com/comment/85221669
comment on: http://stackoverflow.com/q/49108312
has text: I get this error "GetoptError: option --longoption3longvalue3 not recognized"
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/129425420
comment on: http://stackoverflow.com/a/49029210
has text: This answer is only correct if `Y` is an object that does not have the unary operator `__neg__()` implemented. This is obviously untrue for objects that do have it implement (e.g., `Y=np.array([1,2,3]); print(-Y)`
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/49059114
answers question: http://stackoverflow.com/q/49010636
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85133203
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49010636
has body: In your code you have the line: import IHR_TestSuiteConfig.py That won't work because you don't specify modules to import by file name but by module name, e.g.: import IHR_TestSuiteConfig But looking at your screenshot you have a bigger issue of the code being kept in a Settings directory at the same level as your Lib directory containing the code you are importing into. You need to either anchor all of your code up a level so you can do: from ..Settings import IHR_TestSuiteConfig Or you need to manipulate your PYTHONPATH environment variable to put Settings directly on to sys.path (in VS Code you can create a .env file to do this, but it won't' affect running Python from the terminal, only when VS Code runs e.g. Pylint).

http://stackoverflow.com/q/49061406
tagged with: stdout
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/85162891
linked to: http://stackoverflow.com/q/35109086
type: Question
duplicate of: http://stackoverflow.com/q/35109086
has body: I have the following minimal client code: class Client(asyncio.DatagramProtocol): def connection_made(self, transport): print(transport) self._transport = transport req = { 'action': 'join', 'x': 123, 'y': list(range(5)) } self._transport.sendto( dumps(req) # dumps is bencode the dict ) print('sent join') def connection_lost(self, exc): print('lost') loop = asyncio.get_event_loop() loop.stop() raise exc def error_received(self, exc): raise exc def datagram_received(self, data, addr): print('addr', addr) data = parse_packet(data) with open('f', 'a+') as fp: fp.write(str(data) + '\n') print(data) if __name__ == "__main__": loop = asyncio.get_event_loop() listener = loop.create_datagram_endpoint( Client, remote_addr=('127.0.0.1', 9999) ) transport, protocol = loop.run_until_complete(listener) loop.run_forever() transport.close() loop.close() In my console, when I run the client.py, none of the print statements above are shown in console. However, the data sent from my UDP server is being received at the client correctly. The file f contains the content as sent by the server. The same program, when run inside the Sublime Text window (using F7 or Ctrl + B) shows the print statements in build result window.
has comment: http://stackoverflow.com/comment/85163053
score: 0
tagged with: python-asyncio
tagged with: python
tagged with: sublimetext3
answer count: 0
has comment: http://stackoverflow.com/comment/85154251
type: UnansweredQuestion
has title: asyncio DatagramProtocol does not print to console but does so in sublime text window
has comment: http://stackoverflow.com/comment/85163030
has comment: http://stackoverflow.com/comment/85133059

http://stackoverflow.com/comment/85170715
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49082481
has text: That's right I'm using jinja 2 with Flask framework but the problem still persists {% for title, link in dstring.items() %}, I get the same error even the dstring is not string,

http://stackoverflow.com/comment/85180873
comment on: http://stackoverflow.com/q/49087598
score: 0
type: Comment
has text: Yes I am going to make the buttons the exact size of the frame I will use 8 evenly sized buttons each height 150 and width 240
type: QuestionComment

http://stackoverflow.com/comment/85028849
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49011625
score: 0
has text: There is no `self.other_card` in those comparing functions. it should just be `other_card` And probably should access some member of that card. Also `rank` is being compared as Strings....

http://stackoverflow.com/q/49099700
tagged with: python
type: AnsweredQuestion
score: 1
has body: The training features, shape (1032, 5, 5, 122880), go into an LSTM layer. This produces "ValueError: Input 0 is incompatible with layer lstm_16: expected ndim=3, found ndim=2" 1032 is the number of training samples 5x5x122880 is the training sample's bottlenecked features model = Sequential() model.add(CuDNNLSTM(2048,input_shape=train_final_model.shape[:1)) model.add(Dense(2, activation='sigmoid')) It seems as though the Keras ValueError is telling me that I should reshape the training bottlenecked features before running them through the LSTM layer. But doing that: training_bottlenecked_features = np.reshape(train_final_model, (1032,25,122880)) print(training_bottlenecked_features.shape) final_model.add(LSTM(2,input_shape=training_bottlenecked_features.shape[:1])) Yields this: (1032, 25, 122880) "ValueError: Input 0 is incompatible with layer lstm_23: expected ndim=3, found ndim=2" I've played around with the input in several other combinations, so I feel I may be missing something fundamental in the Keras LSTM documentation: https://keras.io/layers/recurrent/ Thank you for any insight you may have.
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49104258
tagged with: lstm
has title: Transfer Learning, adding Keras LSTM layer, (hot dog, not hot dog using binary cross-entropy)
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/49104258

http://stackoverflow.com/comment/85152886
type: Comment
comment on: http://stackoverflow.com/a/49073540
score: 0
type: AnswerComment
has text: hi, but there is this word "AV-Default" i do not want to select. So how can i select contain "AV" but not that "AV-Default"

http://stackoverflow.com/comment/85005805
score: 1
has text: Doesn't directly answer you question, but I prefer to use Click as it is more amenable to this sort of thing: https://stackoverflow.com/a/44349292/7311767
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49000217

http://stackoverflow.com/q/49007626
has comment: http://stackoverflow.com/comment/85019958
upvote count: 3
has body: I'm reading a file directly into pandas with for some odd reason a backslash as delimiter. This is the code: Tried to escape the backslash with escapechar as an argument as I found somewhere but that does not work. How can I read this directly into pandas? raw = pd.read_csv('http://language.media.mit.edu/data/public/unesco_langlang_20120722_iso639-3.txt', escapechar='\\', delimiter = "\\")
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49007797
type: Question
tagged with: pandas
tagged with: python-3.5
has title: Pandas.read_csv: backslash delimiter required?
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49007797
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85019711
tagged with: python

http://stackoverflow.com/a/49078602
has body: If your date columns are called date, you can do something along these lines: data1['date'] = pd.to_datetime(data1['date']) data2['date'] = pd.to_datetime(data2['date']) data1['month'] = data1['date'].dt.month data1['year'] = data1['date'].dt.year data2['month'] = data2['date'].dt.month data2['year'] = data2['date'].dt.year Which would result in something like this: &gt;&gt;&gt; data1 date value month year 0 0 1987-01-01 63.752 1 1987 1 1987-02-01 64.152 2 1987 2 1987-03-01 64.488 3 1987 3 1987-04-01 64.995 4 1987 &gt;&gt;&gt; data2 date value month year 0 0 1987-01-01 1115.10 1 1987 1 1987-01-02 1095.63 1 1987 2 1987-02-01 1036.19 2 1987 3 1987-02-28 1057.08 2 1987 You can then merge those on month and year: data3=data1.merge(data2, on=['month', 'year'])
upvote count: 1
has comment: http://stackoverflow.com/comment/85165482
score: 1
has comment: http://stackoverflow.com/comment/85165649
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49078479

http://stackoverflow.com/q/49103305
favorite count: 0
has answer: http://stackoverflow.com/a/73399149
tagged with: python
upvote count: 2
type: UnansweredQuestion
has title: Converting string to web-safe Base64 format python 3.x
type: Question
tagged with: google-admin-sdk
has body: I am testing how to update user picture using the Admin SDK Directory Service with Python using the following : filename = input('Drag And Drop File\n') image = open(filename,'rb') image_read = image.read() image_encoder = base64.b64encode(image_read) our_str = image_encoder.decode('utf-8') new_str = our_str.replace('/', '_').replace('+', '-').replace('=', '*') def update_photo(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('admin', 'directory_v1', http=http) #Update Photo eventx = { "photoData": new_str, "mimeType": "JPEG" } print('Updating photo') update_photo = service.users().photos().update(userKey='hidden@hiddendomain.com', body=eventx).execute() return update_photo photo_updated = update_photo() print (photo_updated) i am getting this error raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 400 when requesting https://www.googleapis.com/admin/directory/v1/users/hidden@hiddendomain.com/photos/thumbnail?alt=json returned "Invalid value for ByteString: my base64 code reference (https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update),
score: 2
has comment: http://stackoverflow.com/comment/85212171
downvote count: 0
has comment: http://stackoverflow.com/comment/85211910
answer count: 1

http://stackoverflow.com/q/49060262
score: 3
has answer: http://stackoverflow.com/a/49060356
accepted answer: http://stackoverflow.com/a/49060356
has answer: http://stackoverflow.com/a/49060626
has answer: http://stackoverflow.com/a/49060301
answer count: 6
has body: I have these lists: array = ['I love school', 'I hate school', 'I hate bananas', 'today is friday', 'worldcup is great'] #finalArray is initially an empty list finalArray = [] I want to save those indexes of "array" that contain the word "school" into "finalArray". Meaning that "finalArray" should become like this: ['I love school', 'I hate school'] I tried the following code which does not do the job: if "school" in array: finalArray = array.index("school") Why is it not working? Is there a better way to do this?
upvote count: 3
has answer: http://stackoverflow.com/a/49060399
has answer: http://stackoverflow.com/a/49076612
favorite count: 0
tagged with: python
has title: storing indexes of an array which contains a certain word(s) into another array in Python
possible better answer: http://stackoverflow.com/a/49060316
type: AnsweredQuestion
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/49060316
type: Question

dialog
tag name: dialog
tags question: http://stackoverflow.com/q/48989604
type: Tag

http://stackoverflow.com/a/49035073
has body: Here is one way: import pandas as pd, numpy as np df = pd.DataFrame([['A', np.array([np.nan, np.nan, np.nan])], ['B', np.array([111.425818592, -743.060293425, -180.420675659])]], columns=['name', 'array']) df = df[~np.all(list(map(np.isnan, df['array'])), axis=1)] # name array # 1 B [111.425818592, -743.060293425, -180.420675659] Or, if you want to remove rows where any values of the array are NaN: df = df[~np.any(list(map(np.isnan, df['array'])), axis=1)]
answers question: http://stackoverflow.com/q/49034991
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85075739
has comment: http://stackoverflow.com/comment/85075786

http://stackoverflow.com/q/49080517
score: 0
accepted answer: http://stackoverflow.com/a/49080568
answer count: 1
has comment: http://stackoverflow.com/comment/85166810
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85166824
type: AnsweredQuestion
tagged with: list
has body: I want to loop through an object's attributes with a given parameter and replace some elements. Object name is: DATA DATA has these attributes : name[string], version[string] and apps[list of app objects] Apps list includes application objects An app object in apps list has these attributes : app.name [string] ; app.ctrl[list] In ctrl list each item has 5 value : [ value0 , [value1a,value1b] , value2, value3, value4 ] I want to loop through the object elements and find the correct DATA.apps.ctrl list element target and replace value[1][0] and value[1][1] : for app in self.DATA.apps: if self.SelectedAppID.get() == app.name: for control in app.ctrl: if control[0] == self.SelectedCtrl.get(): control[1][0] = valuenew control[1][1] = valuenew I find the application and element I want to change. I think I am replacing it but it does not work. The list remains the same... What am I doing wrong?
upvote count: 1
has answer: http://stackoverflow.com/a/49080568
downvote count: 1
type: Question
has title: How to replace list items where list is an object attribute?
tagged with: replace

http://stackoverflow.com/q/48990614
has comment: http://stackoverflow.com/comment/84985932
tagged with: noise
tagged with: ppm
answer count: 1
has body: I need to add noise to multiple of coloured images (file format is ppm; source: http://benchmark.ini.rub.de/Dataset/GTSRB_Final_Training_Images.zip) in python. The noised output images should be still in colour. I tryed the following: from scipy import misc import numpy as np import cv2 import imageio # Read image ('00000_00030.ppm') from file system image = misc.imread('./00000/00000_00030.ppm', mode="RGB") # Add noise to the input image noised_image = image + 3 * image.std() * np.random.random(image.shape) # Plot original and noisy images import matplotlib.pyplot as plt plt.figure(figsize=(10, 10)) f, axarr = plt.subplots(2, 2) axarr[0, 0].imshow(image) axarr[0, 0].set_title('Original image') axarr[0, 1].imshow(noised_image) axarr[0, 1].set_title('Noised image') plt.show() # Save noised image to file system saved_image = cv2.imwrite("./noised.ppm", noised_image) But first of all the problem is that the noised image won't be plotted correctly in jupyter notebook (see figure 1): figure 1 The second problem is that the RG-channels (Red and Green) were be lost (in saved file): figure 2 So how can I preserve all RGB colors in noised image? After searching for a long time I have the solution now - the saved file preserves now all RGB-colours (See Line 8 in following code; see figure 3): from scipy import misc import numpy as np import cv2 import imageio # Read image ('00000_00030.ppm') from file system # image = misc.imread('./00000/00000_00030.ppm', mode="RGB") image = cv2.imread('./00000/00000_00030.ppm',1) # Add noise to the input image noised_image = image + 3 * image.std() * np.random.random(image.shape) # Plot original and noisy images import matplotlib.pyplot as plt plt.figure(figsize=(10, 10)) f, axarr = plt.subplots(2, 2) axarr[0, 0].imshow(image) axarr[0, 0].set_title('Original image') axarr[0, 1].imshow(noised_image) axarr[0, 1].set_title('Noised image') plt.show() # Save noised image to file system saved_image = cv2.imwrite("./noised1.ppm", noised_image) Fig…
has comment: http://stackoverflow.com/comment/88158570
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/84996585
has title: Add noise to RGB image in python
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48991359
downvote count: 0

http://stackoverflow.com/comment/85075184
type: Comment
has text: Sorry I'm new to this, I tried my best being as accurate as possible.
comment on: http://stackoverflow.com/a/49035095
type: AnswerComment
score: 0

orm
tags question: http://stackoverflow.com/q/48982618
tags question: http://stackoverflow.com/q/49053739
tags question: http://stackoverflow.com/q/49097641
tags question: http://stackoverflow.com/q/49010687
tag name: orm
tags question: http://stackoverflow.com/q/49095668
type: Tag
tags question: http://stackoverflow.com/q/49095187

http://stackoverflow.com/comment/85210107
type: AnswerComment
comment on: http://stackoverflow.com/a/49098971
score: 0
type: Comment
has text: Thanks bigbount, but how can i separate ipv4, ipv6 and MAC address ? Cause all those key name "address". I only want to get connection name and corresponding ipv4, netmask and mac address. For example : Wifi : IPv4 : 192.168.1.10 Netmask : 255.255.255.0 MAC : 34-F3-9A-4C-D0-C4

http://stackoverflow.com/a/60426634
has body: I once got the same error. this error comes when your input size is smaller than your number of down samples(max pooling layer). In other words,for example, when you apply max pooling layer of,say, (2,2) number of times to an input size of, say (256,256,3), there comes a point when your input size becomes (1,1,...) (just an example to understand). And at this point when Maxpool of size(2,2) is applied the input size becomes negative. There are two simple solutions:- Increase your input size, or Decrease your maxpooling layer I personally prefer the 1st solution.
answers question: http://stackoverflow.com/q/49079115
type: Answer
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/a/62585964
type: Answer
has comment: http://stackoverflow.com/comment/111806251
has body: There's a library that already does exactly what you are looking for, i.e. the fluid syntaxt, lazy evaluation and the order of operations is the same with how it's written, as well as many more other good stuff like multiprocess or multithreading Map/Reduce. It's named pyxtension and it's prod ready and maintained on PyPi. Your code would be rewritten in this form: from pyxtension.streams import stream a = stream(range(1, 50)) \ .map(lambda _: _ * 4) \ .filter(lambda _: _ <= 170) \ .filter(lambda _: len(str(_)) == 2) \ .filter(lambda _: _ % 20 == 0) \ .enumerate() \ .map(lambda n_x: f"Result[{n_x[0]}]={n_x[1]}") \ .mkString(" .. ") > a: 'Result[0]=20 .. Result[1]=40 .. Result[2]=60 .. Result[3]=80' Replace map with mpmap for multiprocessed map, or fastmap for multithreaded map.
score: 1
has comment: http://stackoverflow.com/comment/110680307
upvote count: 1
has comment: http://stackoverflow.com/comment/110679966
answers question: http://stackoverflow.com/q/49001986
has comment: http://stackoverflow.com/comment/111807009
downvote count: 0
has comment: http://stackoverflow.com/comment/111768262
has comment: http://stackoverflow.com/comment/111803134

http://stackoverflow.com/q/49018060
has comment: http://stackoverflow.com/comment/85041346
answer count: 1
has comment: http://stackoverflow.com/comment/85041627
has title: Pandas sudden error in code
has comment: http://stackoverflow.com/comment/85041500
tagged with: python
has comment: http://stackoverflow.com/comment/85041376
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49018110
accepted answer: http://stackoverflow.com/a/49018110
type: Question
score: 0
has body: I have this df: A B C D a d a z b c z c My goal is to pull out the column names where df == 'z' so I used: df['ColumnNames'] = df.where(df=='z' ).stack().reset_index().groupby('level_0')['level_1'].apply('+ '.join) It used to work fine; however today I got an error saying: "TypeError: Could not compare ['z'] with block values" Does anyone know why this happens? Many thanks!
tagged with: pandas

http://stackoverflow.com/a/48983585
has body: This is new class syntax vs old class syntax From Python's wiki: A "New Class" is the recommended way to create a class in modern Python. A "Classic Class" or "old-style class" is a class as it existed in Python 2.1 and before. They have been retained for backwards compatibility. This page attempts to list the differences. The syntax for the two types looks the same; "new-style", "old style", "classic", and variants are just descriptions that various people have used; Python hasn't yet settled on a specific official choice for the terminology. The minor syntactic difference is that New Style Classes happen to inherit from object. Regarding @Felix question, consider the following: class A: pass class B(): pass class C(object): pass print A.__mro__ Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> A.__mro__ AttributeError: class A has no attribute '__mro__' print B.__mro__ Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> B.__mro__ AttributeError: class B has no attribute '__mro__' print C.__mro__ (<class '__main__.C'>, <type 'object'>) You explicity have to inhert from object; there is no default inheritance.
downvote count: 0
has comment: http://stackoverflow.com/comment/84971982
answers question: http://stackoverflow.com/q/48983314
type: Answer
has comment: http://stackoverflow.com/comment/84971906
score: 1
upvote count: 1

http://stackoverflow.com/q/49038670
type: Question
tagged with: odoo
tagged with: xml-rpc
has body: I am trying to retrieve image from XMLRPC. I do: record = api.execute_kw(db, uid, pwd, 'product.template', 'read', id, {'fields': ['id', 'name', 'image']}) sub_record = dict((k, record[0][k]) for k in ('id', 'name', 'image')) print sub_record['image'] If I print the image using print sub_record['image'] then I get: [...] [binary] [...] So basically several carriage returns are inserted in the middle of the image base64 string. How can I use that string to display it in an &lt;img&gt; html tag? Do I have to remove these carriage returns first?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49044171
accepted answer: http://stackoverflow.com/a/49044171
has answer: http://stackoverflow.com/a/49044172
tagged with: python
type: AnsweredQuestion
has title: Odoo 10 XMLRPC - Retrieve Image
possible better answer: http://stackoverflow.com/a/49044172

http://stackoverflow.com/comment/85098113
has text: You can read [nested function variable scoping](https://stackoverflow.com/questions/5218895/python-nested-functions-variable-scoping).
comment on: http://stackoverflow.com/q/49046554
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49100462
has body: You can create dummy objPoints using &gt;&gt;&gt; objp = np.zeros((6*9, 3), np.float32) &gt;&gt;&gt; objp[:,:2] = np.mgrid[0:9, 0:6].T.reshape(-1,2) &gt;&gt;&gt; objp array([[ 0., 0., 0.], [ 1., 0., 0.], [ 2., 0., 0.], [ 3., 0., 0.], [ 4., 0., 0.], [ 5., 0., 0.], [ 6., 0., 0.], [ 7., 0., 0.], [ 8., 0., 0.], [ 0., 1., 0.], [ 1., 1., 0.], [ 2., 1., 0.], [ 3., 1., 0.], [ 4., 1., 0.], [ 5., 1., 0.], [ 6., 1., 0.], [ 7., 1., 0.], [ 8., 1., 0.], [ 0., 2., 0.], [ 1., 2., 0.], [ 2., 2., 0.], [ 3., 2., 0.], [ 4., 2., 0.], [ 5., 2., 0.], [ 6., 2., 0.], [ 7., 2., 0.], [ 8., 2., 0.], [ 0., 3., 0.], [ 1., 3., 0.], [ 2., 3., 0.], [ 3., 3., 0.], [ 4., 3., 0.], [ 5., 3., 0.], [ 6., 3., 0.], [ 7., 3., 0.], [ 8., 3., 0.], [ 0., 4., 0.], [ 1., 4., 0.], [ 2., 4., 0.], [ 3., 4., 0.], [ 4., 4., 0.], [ 5., 4., 0.], [ 6., 4., 0.], [ 7., 4., 0.], [ 8., 4., 0.], [ 0., 5., 0.], [ 1., 5., 0.], [ 2., 5., 0.], [ 3., 5., 0.], [ 4., 5., 0.], [ 5., 5., 0.], [ 6., 5., 0.], [ 7., 5., 0.], [ 8., 5., 0.]], dtype=float32) You can then call ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objp, corners, img.shape[::-1],None,None) You don't need to actually provide calibrateCamera with an 'actual' chessboard image.
has comment: http://stackoverflow.com/comment/85206662
has comment: http://stackoverflow.com/comment/85207635
score: 0
has comment: http://stackoverflow.com/comment/85207222
type: Answer
answers question: http://stackoverflow.com/q/49100256

http://stackoverflow.com/a/49328962
has body: You defined embedding vector as 1-d tensor with float zero inside: X = tf.Variable([0.0], name='embedding') According to this manual it should be 2-d tensor with [Number_of_vectors, Dimensions_in_vector] shape, i.e: embedding_var = tf.Variable(tf.zeros([100,10]), name='embedding') Considering Chrome Dev Tools error: TensorBoard requests /info?run=[run_id] to obtain JSON data with embeddings variables. In your case, back-end fails to determine tensorShape and returns tensorName only. Front-end tries to read tensorShape to assess its length property. On this step JS raises Uncaught TypeError since tenshorShape is not defined. It's a bug of tensorboard`s back-end.
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/130679235
answers question: http://stackoverflow.com/q/48968688

http://stackoverflow.com/a/49020221
answers question: http://stackoverflow.com/q/49020187
has comment: http://stackoverflow.com/comment/86703753
downvote count: 0
has body: You can use regex: import re s = ['186.797\t-48', '187.272\t-48', '187.747\t-48', '188.222\t-45', '188.697\t-43', '189.172\t6', '189.646\t-23', '190.121\t12'] L1, L2 = map(list, zip(*[[float(re.findall('[\d\.]+', i)[0]), int(re.findall('[\-\d]+$', i)[0])] for i in s])) Output: [186.797, 187.272, 187.747, 188.222, 188.697, 189.172, 189.646, 190.121] [-48, -48, -48, -45, -43, 6, -23, 12]
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86703832
upvote count: 2

http://stackoverflow.com/comment/91067283
has text: [(x,x**2 + 5) for x in np.arange(10)]
score: 0
comment on: http://stackoverflow.com/q/49074095
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49038809
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85084191
has title: Turtle Graphics: Repeating Squares
upvote count: 1
accepted answer: http://stackoverflow.com/a/49041042
has answer: http://stackoverflow.com/a/49042603
type: Question
has comment: http://stackoverflow.com/comment/85084302
has comment: http://stackoverflow.com/comment/85082935
possible better answer: http://stackoverflow.com/a/49042603
answer count: 2
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49041042
tagged with: python-3.x
tagged with: turtle-graphics
has body: I am trying to create a loop that takes an input by a user and draws however many squares but it increases the size of the squares with each loop, however 2 sides are stay connected. I'll include the graphic to better explain. import turtle squares = 1 while squares &gt;= 1: squares = int(input('How many squares would you like drawn?:')) if squares == 0: print("You must have at-least 1 square.") squares = int(input('How many squares would you like drawn?:')) else: for count in range(squares): turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.forward(30) turtle.left(90) turtle.done()
tagged with: python-turtle
tagged with: python
has comment: http://stackoverflow.com/comment/85084003

http://stackoverflow.com/q/48968668
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: pycharm
upvote count: 2
tagged with: pip
has comment: http://stackoverflow.com/comment/84943007
type: Question
has comment: http://stackoverflow.com/comment/84943041
has answer: http://stackoverflow.com/a/48969154
tagged with: python-3.6
has title: Can't import package installed with PIP
answer count: 1
linked to: http://stackoverflow.com/q/41982661
downvote count: 0
has body: Problem I'm not new to programming, however I am new to Python. I am attempting to import a package called GDAX in regards to Coinbase's GDAX market. I've installed it using pip install gdax, and python -m pip install gdax per solutions I have found online similar to my issue. The package is installed successfully in both cases, however, when I create my new project in PyCharm, and try import gdax, it's not found. I've tried several different keyword searches to find a solution for my problem, but have yet to find one. I've searched for generic tutorials on how to install packages not included in python, and it seems like what I've done to install the package is correct. Any suggestions as to what I'm doing wrong, or what I'm missing?
favorite count: 0
has comment: http://stackoverflow.com/comment/84942886
has comment: http://stackoverflow.com/comment/84943179
accepted answer: http://stackoverflow.com/a/48969154
has comment: http://stackoverflow.com/comment/84946545

http://stackoverflow.com/q/49043922
tagged with: python-3.x
has body: I'm testing graphlabe create with following sf=gl.SFrame(['t1','t2','','t3','','t4']) sf.dropna() accoding to graphlab api the above should remove empty values(na), but actually it does not, and no errors given either. anyone knows why?
tagged with: python
tagged with: graphlab
has answer: http://stackoverflow.com/a/49044066
type: AnsweredQuestion
type: Question
tagged with: python-2.7
score: 0
has title: graphlab create dropna does not work
answer count: 1
accepted answer: http://stackoverflow.com/a/49044066

http://stackoverflow.com/a/49113227
type: Answer
accepted answer of: http://stackoverflow.com/q/49053059
has body: Credit: Based on advice provided by @Tshirtman in the comments thread of the posted question... Summary: The problem with the code had to do with the fact that I had two different DictStore pointing to the same file, which was tripping up the communication between both classes. The solution was to instead use only one DictStore and define that variable in the App class, then reference that particular variable in the child classes [using App.get_running_app()], like so: Define config_file in App class: class MainApp(App): config_file = DictStore('conf2.dat') def build(self): return presentation Reference App variable in child classes: class SequenceBoxLayout_NoEdits(BoxLayout): ... def __init__(self, **kwargs): super(SequenceBoxLayout_NoEdits, self).__init__(**kwargs) self.orientation = "vertical" Clock.schedule_interval(self.create_button, 1) def create_button(self, *args): self.box_share.clear_widgets() app = App.get_running_app() ... for i in range(len(parts)): ... if app.config_file.exists(id_): btn_color = app.config_file[id_]["background_color"] else: app.config_file.put(id_, background_color=color) ... ... class SequenceBoxLayout_NoTag(BoxLayout): ... def __init__(self, **kwargs): super(SequenceBoxLayout_NoTag, self).__init__(**kwargs) self.orientation = "vertical" Clock.schedule_once(self.create_button) def create_button(self, *args): ... app = App.get_running_app() ... for i in range(len(parts)): ... if app.config_file.exists(id_): btn_color = app.config_file[id_]["background_color"] else: app.config_file.put(id_, background_color=color) ... ... def update_buttons_notag(self, button): app = App.get_running_app() ... app.config_file.put(button.id, background_color=(0.86,0.54,0.04,1))
answers question: http://stackoverflow.com/q/49053059
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49049245
downvote count: 0
answers question: http://stackoverflow.com/q/49048294
score: 4
has body: Simple 1 line fix for any who need os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
type: Answer
upvote count: 4

http://stackoverflow.com/comment/84997026
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48995683
has text: It is usually not welcome just to ask for solutions here. You should show your work and ask specific questions.

http://stackoverflow.com/a/49120445
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/104625290
has comment: http://stackoverflow.com/comment/85252412
has comment: http://stackoverflow.com/comment/85252483
type: Answer
accepted answer of: http://stackoverflow.com/q/49120364
has comment: http://stackoverflow.com/comment/85246608
has comment: http://stackoverflow.com/comment/85252564
answers question: http://stackoverflow.com/q/49120364
has comment: http://stackoverflow.com/comment/85252825
has comment: http://stackoverflow.com/comment/85246699
score: 11
downvote count: 0
has comment: http://stackoverflow.com/comment/85252606
has comment: http://stackoverflow.com/comment/104625696
has body: I am using fuzzywuzzy here from fuzzywuzzy import fuzz from fuzzywuzzy import process df2['key']=df2.Name.apply(lambda x : [process.extract(x, df1.Name, limit=1)][0][0][0]) df2.merge(df1,left_on='key',right_on='Name') Out[1238]: Name_x gender key Age Name_y 0 adam Smith M Adam Smith 43 Adam Smith 1 Annie Kim F Anne Kim 21 Anne Kim 2 John Weber M John Weber 55 John Weber 3 Ian Ford M Ian Ford 24 Ian Ford
upvote count: 11
has comment: http://stackoverflow.com/comment/85252668
has comment: http://stackoverflow.com/comment/85252721

http://stackoverflow.com/q/49085633
has comment: http://stackoverflow.com/comment/85177572
answer count: 3
has comment: http://stackoverflow.com/comment/85177284
has comment: http://stackoverflow.com/comment/85178053
downvote count: 1
has answer: http://stackoverflow.com/a/49093701
has comment: http://stackoverflow.com/comment/85176979
tagged with: macos
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85178640
tagged with: homebrew
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/85180457
linked to: http://stackoverflow.com/q/47082736
type: AnsweredQuestion
has body: I had python2 installed on my macOS and I parallel installed python3 (without homebrew). It worked perfect and I could use python3 and pip3 from every directory without problems parallel to python and pip for version 2. Some days ago I did not find pip3 and I had to set an alias to python3 -m ... (I thought I didn't use it before but I had!). Today in the morning I worked with python3 without problems and now python3 got a command not found but I cannot find it on my directories, too. Where is my python3? And why it is gone? The only reason I see is that I installed homebrew about a week ago for installing mutt. Is it possible that the brew upgrade function has destroyed paths or even installations? Would be great to get help from you! Thanks a lot.
has comment: http://stackoverflow.com/comment/85177122
has comment: http://stackoverflow.com/comment/85186866
has comment: http://stackoverflow.com/comment/85176790
has comment: http://stackoverflow.com/comment/85177416
type: Question
has comment: http://stackoverflow.com/comment/85186535
possible better answer: http://stackoverflow.com/a/49863945
has title: Python3 is suddenly gone (on macOS) - used it for at least a year
has answer: http://stackoverflow.com/a/49863945
has comment: http://stackoverflow.com/comment/85192193
has answer: http://stackoverflow.com/a/60066221
score: 10
upvote count: 11
accepted answer: http://stackoverflow.com/a/49093701

http://stackoverflow.com/a/48982198
score: 1
answers question: http://stackoverflow.com/q/48979150
upvote count: 1
type: AcceptedAnswer
has body: TCP sockets always need to be connected before sending data. Establishing the connection involves an actual packet exchange with the peer, i.e. the TCP 3-way handshake. This is also means that the connect can fail if the target cannot be reached. This is not specific to Python but specific to how TCP sockets work. With UDP a socket can be connected but does not need to be. Connecting a UDP socket essentially just sets the target on the local socket but does not involve any actual data transfer. This also means that the connect will usually not fail even but a later data transfer might not be able to reach the target.
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48979150

http://stackoverflow.com/comment/90272153
comment on: http://stackoverflow.com/a/48994441
has text: This is a solution but not the complete solution, what happens when the child thread encounters exception? So we have to handle that too, Solution will be to use a custom thread class instead of default Thread class and handle the exception in there.
type: AnswerComment
type: Comment
score: 4

http://stackoverflow.com/comment/85099916
has text: Yeah, figured that out, started django only 2 months back, so still have to learn a lot. I figured out a way with template tags, will post the result soon.
comment on: http://stackoverflow.com/q/49045348
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48969040
has body: The requests module takes a files argument for uploading multipart encoded files to a URL. change your code to this: file_data = {'filename': data} r = requests.post(api, files=[file_data]) I'll probably write the file to disk, before trying to upload it. so you don't lose everything if something goes wrong.
has comment: http://stackoverflow.com/comment/84943964
has comment: http://stackoverflow.com/comment/84944036
answers question: http://stackoverflow.com/q/48968871
score: 0
type: Answer

http://stackoverflow.com/q/49055769
tagged with: python
has answer: http://stackoverflow.com/a/49055894
type: AnsweredQuestion
has body: I have a DataFrame that contains many years worth of data. I want to make a couple columns containing the previous years' data from the same DataFrame. Here's an example: df = pd.DataFrame({'id': [1,1,1,2,2,2,3,4,5,3,3,3,4], 'yr': [87,88,89,54,55,53,87,87,89,90,91,92,86], 'data': '1-87 1-88 1-89 2-54 2-55 2-53 3-87 4-87 5-89 3-90 3-91 3-92 4-86'.split()}) data id yr 0 1-87 1 87 1 1-88 1 88 2 1-89 1 89 3 2-54 2 54 4 2-55 2 55 5 2-53 2 53 6 3-87 3 87 7 4-87 4 87 8 5-89 5 89 9 3-90 3 90 10 3-91 3 91 11 3-92 3 92 12 4-86 4 86 I'd like to add on another column that shows the previous years' data for that id number. like this: data id yr last_year_data 0 1-87 1 87 NaN 1 1-88 1 88 1-87 2 1-89 1 89 1-88 3 2-54 2 54 2-53 4 2-55 2 55 2-54 5 2-53 2 53 NaN 6 3-87 3 87 NaN 7 4-87 4 87 4-86 8 5-89 5 89 NaN 9 3-90 3 90 NaN 10 3-91 3 91 3-90 11 3-92 3 92 3-91 12 4-86 4 86 NaN I tried to do this with a merge but I got Nan's all the way down in the 2nd half of the merge. Here's my code for that: df['last_year'] = df['yr'].apply(lambda x: x-1 if x &gt; 0 else None) df_test = df.merge(df, how='left',indicator=False,left_on=['id','yr'],right_on=['id','last_year']) I know there's a better way to do this, but I'm not sure what it is. can you help?
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49055894
has title: Python Pandas self merge on previous data
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/84946163
type: Comment
type: QuestionComment
has text: I recommend you correctly indent your .py and .kv, in python and kivy it is very important.
score: 1
comment on: http://stackoverflow.com/q/48969324

http://stackoverflow.com/a/49013885
has body: The problem you are facing is that you have not indented your code properly. In python white-space is very important particularly when working with nested if statements/loops. How does the computer know that you are done with an if statement? Try var=1; while var==1: num=int(input("Enter a number:")) if (isinstance(num, int)): print("your input number:",num) if(num==000): break else: print('incorrect!!!') note the print statement is moved and the if else is now in line
answers question: http://stackoverflow.com/q/49013801
score: 0
type: Answer

http://stackoverflow.com/comment/88783994
type: AnswerComment
type: Comment
has text: @StackEdd I have added a link
comment on: http://stackoverflow.com/a/49075645
score: 0

http://stackoverflow.com/comment/85205409
type: Comment
type: QuestionComment
has text: @EugeneK Thank you so much! When doing this manually it worked. How would I go about converting the format?
comment on: http://stackoverflow.com/q/49099392
score: 0

http://stackoverflow.com/comment/85141373
has text: Did you run the script to completion before checking the file contents? The file will appear to be empty until the buffers are flushed, usually when the file is closed.
type: Comment
comment on: http://stackoverflow.com/a/49065216
type: AnswerComment
score: 0

http://stackoverflow.com/q/49073615
tagged with: python
has answer: http://stackoverflow.com/a/49073669
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85153165
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/85155611
linked to: http://stackoverflow.com/q/110923
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49073669
has comment: http://stackoverflow.com/comment/85153307
answer count: 2
has title: Unable to make a button (created using tkinter) quit automatically
possible better answer: http://stackoverflow.com/a/49073719
has comment: http://stackoverflow.com/comment/85162149
has body: I've written a script using tkinker in python. When I run the script, it receives an input and print that to the console. It is working great. What I wish to do is add any functionality to my existing script in such a way so that after filling in the inputbox when I press the get button, it will print the value in the console and quits automatically. Once again, my existing script is capable of printing values. I need to make that button quit as soon as the printing is done. Any help on this will be highly appreciated. Here is what I've tried so far: from tkinter import * master = Tk() e = Entry(master) e.pack() e.focus_set() callback = lambda : get_val(e.get()) get_val = lambda item: print(item) #this extra function is for further usage Button(master, text="get", width=10, command=callback).pack() master.mainloop() This is how the inputbox looks like:
has answer: http://stackoverflow.com/a/49073719
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/6920302

http://stackoverflow.com/q/49053567
type: Question
has title: How to solve ValueError: need more than 1 value to unpack?
has comment: http://stackoverflow.com/comment/85112082
tagged with: count
tagged with: python
has body: i use python 2.7 and i try to find how each of the POS in my file occur i write this code : from collections import Counter f = open("POS.txt","r") text = f.read() print(text) counts = Counter(tag for word,tag in text) print(counts) and the output was as here : File "C:/Python27/Lib/countPOS.py", line 10, in &lt;genexpr&gt; counts = Counter(tag for word,tag in text) ValueError: need more than 1 value to unpack How to solve this error ? and this is the input in my file: [(u'\u0627', 'JJ'), (u'\u0644', 'NNP'), (u'\u062d', 'NNP'), (u'\u064e', 'NNP'), (u'\u0631', 'NNP'), (u'\u0652', 'NNP'), (u'\u0628', 'NNP'), (u'\u064f', 'NN')]
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85111921
downvote count: 1
has comment: http://stackoverflow.com/comment/85112148
has answer: http://stackoverflow.com/a/49053619
has comment: http://stackoverflow.com/comment/85112225
accepted answer: http://stackoverflow.com/a/49053619
has comment: http://stackoverflow.com/comment/85112213
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85111895
favorite count: 0
has comment: http://stackoverflow.com/comment/85112751

http://stackoverflow.com/comment/85240625
type: QuestionComment
has text: How are your objects actually defined? Are they in some kind of container or do you just have 20k separate variables?
comment on: http://stackoverflow.com/q/49117648
type: Comment
score: 1

http://stackoverflow.com/a/49100882
has comment: http://stackoverflow.com/comment/85207107
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49100734
answers question: http://stackoverflow.com/q/49100734
type: Answer
has body: According to Access GPIO pins without root. No access to /dev/mem. Try running as root! your python script will write to /dev/gpiomem. This doesn't work, because the user that runs your python script (www-data) is not allowed to write to this device: To write there you need to be root or in the gpio group. The user www-data is neither root nor in the gpio group. In order to access gpio ports, you need to put the www-data user in the correct group: sudo usermod -aG gpio www-data Don't forget to restart your http server (and php-fpm if applicable). You won't notice a difference otherwise.
score: 0

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/49050108

http://stackoverflow.com/comment/84965988
comment on: http://stackoverflow.com/q/48980425
has text: Mind posting the list you got?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49049431
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85103005
has answer: http://stackoverflow.com/a/49049665
has body: Whats the best way to refactor this code to clean it up: 1) Selects from the db adding a column for the percentage difference between two columns 2) Loops through the values of the columns 3) If the date is in the past 4) If the price is greater than 500 and the percentage difference is less than 1st argument set flag to 1 5) Else if the price is less than 500 and the percentage difference is less than 2nd argument set flag to 1 6) Otherwise keep the flag as 0 def calculateEmployeeSpend(read_cursor, flag_higher_amount, flag_lower_budget): read_cursor.execute("SELECT distinct b.employee_id, b.amount, " "s.spend, b.date, b.amount - s.spend as spend_left, " "100.0*(b.amount - s.spend) / b.amount As PercentDiff FROM employee_budget_upload " "As b JOIN employee_budget_spent As s ON b.employee_id = s.employee_id where b.amount != 0") for employee_id, amount, spend, date, spend_left, percent_diff in read_cursor: flag=0 date_of_amount = dt.strptime(date, "%d/%m/%Y") if date_of_amount &lt;= dt.now(): if amount &gt; 500 and percent_diff &lt; int(flag_higher_amount): flag=1 if amount &lt; 500 and percent_diff &lt; int(flag_lower_amount): flag=1 Edit: I have changed the ifs to one if: if amount &gt; 500 and percent_diff &lt; int(flag_higher_amount) or amount &lt; 500 and percent_diff &lt; int(flag_lower_amount): flag=1
score: 0
has answer: http://stackoverflow.com/a/49050035
answer count: 3
has comment: http://stackoverflow.com/comment/85103066
has answer: http://stackoverflow.com/a/49049517
accepted answer: http://stackoverflow.com/a/49049517
tagged with: python
has title: Refactoring if statements and other code in python
possible better answer: http://stackoverflow.com/a/49049665

http://stackoverflow.com/comment/84938011
score: 1
has text: Just for clarity, can you give some examples of your input data.
comment on: http://stackoverflow.com/q/48966175
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49108836
tagged with: kivy
favorite count: 0
tagged with: python-3.x
tagged with: kivy-language
has body: I have two file test.py and test.kv . i run test.py then shows show button. When i click on show button then def abc call.Can someone tell me how to show array in dynamic label and value(Item1=5000.Item2=1000). Item1 5000 Item2 1000 I am using array arr = ({'Item1': 5000},{'Item2': 1000}) test.py from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty Window.clearcolor = (0.5, 0.5, 0.5, 1) Window.size = (600, 600) class Invoice(Screen): def __init__(self, **kwargs): super(Invoice, self).__init__(**kwargs) def abc(self): #fetching from database arr = ({'Item1': 5000},{'Item2': 1000}) print(arr) class Test(App): def build(self): self.root = Builder.load_file('test.kv') return self.root if __name__ == '__main__': Test().run() test.kv &lt;Button@Button&gt;: font_size: 15 font_name: 'Verdana' size_hint_y:None height: 30 &lt;Label@Label&gt;: font_size: 15 font_name: 'Verdana' size_hint_y:None height: 30 Invoice: BoxLayout: orientation: "vertical" padding : 15, 15 BoxLayout: orientation: "vertical" padding : 5, 5 size_hint: .6, None pos_hint: {'x': .18,} BoxLayout: orientation: "horizontal" padding : 5, 5 spacing: 10, 10 size: 800, 40 size_hint: 1, None Button: text: "Show" size_hint_x: .05 spacing_x: 30 on_press:root.abc() BoxLayout: orientation: "horizontal" size_hint: 1, 1 BoxLayout: orientation: "vertical" size_hint: .5, 1 padding : 0, 15 spacing: 10, 10 size: 500, 30 Button: text: "Invoice" text_size: self.size halign: 'center' valign: 'middle' GridLayout: cols: 2 #orientation: "horizontal" padding : 5, 0 spacing: 10, 0 #size: 500, 30 size_hint: 1, 1 pos: self.pos size: self.size Label: size_hint_x: .35 text: "Item1" text_size: self.size halign: 'left' valign: 'middle' canvas.before: Color: rgb: .6, .6, .6 Rectangle: pos: self.pos size: self.size Label: size_hint_x: .15 text: "5000" text…
has answer: http://stackoverflow.com/a/49116497
tagged with: python
type: AnsweredQuestion
type: Question
upvote count: 4
has title: Python/Kivy : How to put dynamic label widget and value
accepted answer: http://stackoverflow.com/a/49116497
score: 4
has answer: http://stackoverflow.com/a/49115012
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/49115012
downvote count: 0

http://stackoverflow.com/a/48997476
has comment: http://stackoverflow.com/comment/85144954
has comment: http://stackoverflow.com/comment/85022968
has comment: http://stackoverflow.com/comment/85030110
has comment: http://stackoverflow.com/comment/85121448
has comment: http://stackoverflow.com/comment/85027284
has comment: http://stackoverflow.com/comment/85031236
score: 1
has body: Starting with direct recursion and state variables with default values, def flatten (l, i = 0, path = (), acc = []): if not l: return acc else: first, *rest = l if isinstance (first, list): return flatten (first, 0, path + (i,), acc) + flatten (rest, i + 1, path, []) else: return flatten (rest, i + 1, path, acc + [ (first, path + (i,)) ]) print (flatten (L)) # [ (1, (0, 0, 0)) # , (2, (0, 0, 1)) # , (3, (0, 0, 2)) # , (4, (0, 1, 0)) # , (5, (0, 1, 1)) # , (6, (1, 0)) # , (7, (2, 0)) # , (8, (2, 1, 0)) # , (9, (2, 1, 1)) # , (10, (3,)) # ] The program above shares the same weakness as yours; it is not safe for deep lists. We can use continuation-passing style to make it tail recursive – changes in bold def identity (x): return x # tail-recursive, but still not stack-safe, yet def flatten (l, i = 0, path = (), acc = [], cont = identity): if not l: return cont (acc) else: first, *rest = l if isinstance (first, list): return flatten (first, 0, path + (i,), acc, lambda left: flatten (rest, i + 1, path, [], lambda right: cont (left + right))) else: return flatten (rest, i + 1, path, acc + [ (first, path + (i,)) ], cont) print (flatten (L)) # [ (1, (0, 0, 0)) # , (2, (0, 0, 1)) # , (3, (0, 0, 2)) # , (4, (0, 1, 0)) # , (5, (0, 1, 1)) # , (6, (1, 0)) # , (7, (2, 0)) # , (8, (2, 1, 0)) # , (9, (2, 1, 1)) # , (10, (3,)) # ] Finally, we replace the recursive calls with our own call mechanism. This effectively sequences the recursive calls and now it works for data of any size and any level of nesting. This technique is called a trampoline – changes in bold def identity (x): return x def flatten (l): def loop (l, i = 0, path = (), acc = [], cont = identity): if not l: return cont (acc) else: first, *rest = l if isinstance (first, list): return call (loop, first, 0, path + (i,), acc, lambda left: call (loop, rest, i + 1, path, [], lambda right: cont (left + right))) else: return call (loop, rest, i + 1, path, acc + [ (first, path + (i,)) ], cont) return loop (l) .run () class ca…
has comment: http://stackoverflow.com/comment/85023707
has comment: http://stackoverflow.com/comment/85120154
has comment: http://stackoverflow.com/comment/85025843
has comment: http://stackoverflow.com/comment/85121815
has comment: http://stackoverflow.com/comment/85001388
has comment: http://stackoverflow.com/comment/85189936
has comment: http://stackoverflow.com/comment/85124094
upvote count: 1
has comment: http://stackoverflow.com/comment/85002592
has comment: http://stackoverflow.com/comment/85022971
has comment: http://stackoverflow.com/comment/85124412
has comment: http://stackoverflow.com/comment/85008678
has comment: http://stackoverflow.com/comment/85081110
has comment: http://stackoverflow.com/comment/85189857
type: Answer
has comment: http://stackoverflow.com/comment/85022980
answers question: http://stackoverflow.com/q/48996063
downvote count: 0
has comment: http://stackoverflow.com/comment/85081849
has comment: http://stackoverflow.com/comment/85002401
has comment: http://stackoverflow.com/comment/85120711

http://stackoverflow.com/comment/128110741
has text: @Plesbien Can you share the solution? I need.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49039670
type: Comment

http://stackoverflow.com/comment/85724928
type: AnswerComment
comment on: http://stackoverflow.com/a/49355161
has text: Only drawback: It does not seem to work with python 2.
score: 0
type: Comment

http://stackoverflow.com/a/49106127
has body: Firstly, you have to introduce all orders inside of the loop, otherwise, only will work with the last iteration. Second, You could try closing the requests session at the end of each iteration: import requests for i in range(5): # Number of pages plus one url = "https://www.example.com/S1-3-{}.html".format(i) r = requests.get(url) from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'product-item item-template-0 alternative'}) r.close()
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49105772
upvote count: 1
type: Answer

http://stackoverflow.com/q/48990191
has answer: http://stackoverflow.com/a/48990270
answer count: 1
has comment: http://stackoverflow.com/comment/84986055
has comment: http://stackoverflow.com/comment/84984958
favorite count: 0
has comment: http://stackoverflow.com/comment/84984968
has comment: http://stackoverflow.com/comment/84985041
accepted answer: http://stackoverflow.com/a/48990270
tagged with: python
has comment: http://stackoverflow.com/comment/84985111
type: AnsweredQuestion
downvote count: 2
tagged with: file
has title: Accessing a function variable from another file in python
linked to: http://stackoverflow.com/q/34255592
has comment: http://stackoverflow.com/comment/85008272
linked to: http://stackoverflow.com/q/42972184
type: Question
has comment: http://stackoverflow.com/comment/85008147
has body: I have two files File1 and File2. In File1 I have a function detect() defined as: def detect(): s = // some operations I need to access this variable s in File2. I have tried declaring the variable as global but it has not worked. How can I access the variable without creating a class as in this post or by using __main__ as in this post ??
tagged with: function
upvote count: 0
score: -2
tagged with: variables

boolean
tags question: http://stackoverflow.com/q/49066162
tags question: http://stackoverflow.com/q/49068539
tags question: http://stackoverflow.com/q/49009870
tags question: http://stackoverflow.com/q/48998583
tag name: boolean
tags question: http://stackoverflow.com/q/48988038
tags question: http://stackoverflow.com/q/49021823
tags question: http://stackoverflow.com/q/49055336
tags question: http://stackoverflow.com/q/49074117
tags question: http://stackoverflow.com/q/49033899
tags question: http://stackoverflow.com/q/49020628
type: Tag

http://stackoverflow.com/q/49052676
has answer: http://stackoverflow.com/a/79525538
upvote count: 7
has answer: http://stackoverflow.com/a/49053053
answer count: 4
tagged with: bash
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/79522456
score: 7
favorite count: 0
has body: How can I set up a cron job to monitor multiple PIs (via SSH) that are running the same daemon script (service)? I was thinking of using a cron job to monitor the service status and write to a file on my server if the status of the service is active or inactive, and then I can later use the contents of that file to display the results of the Cron job onto a web page (but that is for me to figure out later). I'm open to other options if someone can figure out an easier way using a different tool, E.g. bash script, python script, PHP etc,
tagged with: daemon
has answer: http://stackoverflow.com/a/53899483
type: Question
tagged with: cron
accepted answer: http://stackoverflow.com/a/49053053
tagged with: python
has title: How to check if a daemon service is running via Cron job or script?
tagged with: php
possible better answer: http://stackoverflow.com/a/53899483

http://stackoverflow.com/comment/85942979
has text: or even `[0.2,0.2,0.2]`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49084206

list-comprehension
tags question: http://stackoverflow.com/q/49076437
tags question: http://stackoverflow.com/q/49074095
tags question: http://stackoverflow.com/q/48994859
tags question: http://stackoverflow.com/q/49074059
tags question: http://stackoverflow.com/q/49066799
tag name: list-comprehension
tags question: http://stackoverflow.com/q/49067980
tags question: http://stackoverflow.com/q/49063055
type: Tag
tags question: http://stackoverflow.com/q/49090643
tags question: http://stackoverflow.com/q/49002409
tags question: http://stackoverflow.com/q/48991879
tags question: http://stackoverflow.com/q/49034946
tags question: http://stackoverflow.com/q/49000790
tags question: http://stackoverflow.com/q/49020269
tags question: http://stackoverflow.com/q/49114267
tags question: http://stackoverflow.com/q/49107491

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/49058275
tags question: http://stackoverflow.com/q/49094311
tag name: lemmatization

http://stackoverflow.com/a/48986961
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84979284
has body: As Arpit mentioned in the comments you can use a for loop and iloc to achieve what you need: df = pd.read_csv(pd.compat.StringIO('''A B C D E 1 2 3 4 5 5 6 7 8 9'''),sep='\s+') df.loc[2,'A'] = 5 for i in range(1,len(df.columns)): df.iloc[2,i] = df.iloc[0,i-1] + df.iloc[1,i] - df.iloc[2,i-1] Output: In [43]: df Out[43]: A B C D E 0 1.0 2.0 3.0 4.0 5.0 1 5.0 6.0 7.0 8.0 9.0 2 5.0 2.0 7.0 4.0 9.0
accepted answer of: http://stackoverflow.com/q/48985466
answers question: http://stackoverflow.com/q/48985466
upvote count: 1
has comment: http://stackoverflow.com/comment/84980938
type: AcceptedAnswer

http://stackoverflow.com/q/49117576
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85244687
has body: We have a db_connection.py module which looks like below. from os import getenv from collections import OrderedDict import asyncpg from tornado import gen from util.utils import custom_exception import time db_name = getenv("DB_NAME", "XXX") db_user = getenv("DB_USER", "YYY") db_password = getenv("DB_PASSWORD", "ZZZ") db_host = getenv("DB_HOST", "localhost") db_port = getenv("DB_PORT", "5432") db_args = dict(user=db_user, password=db_password, database=db_name, host=db_host, port=db_port) class db_connection(object): def __init__(self, **db_args): self.db_pool = [] self.init(**db_args) # create a pool ref coroutine where we can get connections from # needs user, password, database, host, port @gen.coroutine def init(self,**db_args): self.db_pool = yield asyncpg.create_pool(**db_args) @gen.coroutine def exit(self): yield self.db_pool.close() # run a queer async def run(self,q): if not self.db_pool: self.init() #try again if not self.db_pool: raise custom_exception(reason='Database connection error', status_code=500) async with self.db_pool.acquire() as connection: ret = await connection.fetch(q) # format to match the old data types return [OrderedDict(e) for e in ret] def __exit__(self, exc_type, exc_val, exc_tb): self.exit() self.db_pool = [] In the app, we initialize the db_connection object as follows: from util.db_connection import db_args, db_connection (...) if __name__ == "__main__": AsyncIOMainLoop().install() dbc = db_connection(**db_args) # What we have here is a rather basic tornado app app = make_app() app.listen(port=8080) asyncio.get_event_loop().run_forever() The problem we saw is that, and this is something I can not explain, it seems that the connection string (db_args) is not always set and sometimes appears to be an empty dictionary; asyncpg then falls back and tries to get a connection string from the linux user associated to the container via os. Mar 5 16:59:50 ABC: ERROR: tornado.application:Future &lt;tornado.concurrent.Future object at 0x7eff6…
tagged with: tornado
type: Question
has comment: http://stackoverflow.com/comment/85245448
has comment: http://stackoverflow.com/comment/85244938
tagged with: postgresql
score: 0
has title: Sometimes empty connection string from `getenv` in module
tagged with: connection-pooling
has comment: http://stackoverflow.com/comment/85245369
has comment: http://stackoverflow.com/comment/85245167
type: UnansweredQuestion

http://stackoverflow.com/comment/85026399
comment on: http://stackoverflow.com/q/49010883
score: 1
has text: sry i meant using os.path.join('/Users/myname/Desktop','traindog.8011.jpg')
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85102200
comment on: http://stackoverflow.com/q/49043744
has text: No. No error is coming. It's just not redirecting to that page.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84972442
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48983860
has text: 1. I do not see the problem with my question, I would like to know how to extract those keys from a particular dictionary which is 0 when the same key and value is more than 0 in another dictionary? 2. I know it does not look like a dict but I thought it would be easier to write and read as csv rather than 'the correct' syntax.
score: 0

http://stackoverflow.com/comment/85130530
type: Comment
comment on: http://stackoverflow.com/a/49062251
type: AnswerComment
has text: I tried running your code on the [larger dataset](https://uploadfiles.io/) but it yelled an error. You don't need to take a look into this, but your solution would be more robust if you did.
score: 0

http://stackoverflow.com/a/49012593
score: 0
has body: You might want to modify your code a bit. I suggest you use a recursive function for this, as you would want it to dynamically read all "txt" files in sub-directories as well. Something like this: from pprint import pprint def getFileContent(path_dir, dict_In): for path, dirs, files in os.walk(path_dir): folders = path.split(os.sep) for dir in dirs: inner_path = path + '/' + dir getFileContent(inner_path, dict_In) for file in files: if file.endswith(".txt"): f=open(os.path.join(path, file),'r') content = f.read() dict_In[f.name] = content path = os.path.join("C:/Users/John/Desktop/Ppractice") result_dict = {} getFileContent(path_dir = path, dict_In = result_dict) pprint(result_dict)
has comment: http://stackoverflow.com/comment/85479948
type: Answer
answers question: http://stackoverflow.com/q/48994256
has comment: http://stackoverflow.com/comment/85479772

http://stackoverflow.com/comment/87277872
comment on: http://stackoverflow.com/a/49786336
score: 0
type: AnswerComment
type: Comment
has text: I tried for ages. But, still, I find nobody able to do that, you will be the first :) As soon as I change your code to `dynamic_rnn` it stops to work

http://stackoverflow.com/comment/85044608
type: QuestionComment
type: Comment
has text: As a more cogent example: try writing code that asks for the user's name, then printing "Hello, <name>!" Then try writing a function that capitalizes the name before giving it back to be printed.
comment on: http://stackoverflow.com/q/49019554
score: 0

http://stackoverflow.com/comment/85220204
type: QuestionComment
has text: Possible duplicate of [how to save/load a trained model in H2o?](https://stackoverflow.com/questions/31522341/how-to-save-load-a-trained-model-in-h2o)
comment on: http://stackoverflow.com/q/49107634
score: 0
type: Comment

http://stackoverflow.com/a/49084557
accepted answer of: http://stackoverflow.com/q/49084471
answers question: http://stackoverflow.com/q/49084471
type: Answer
has body: Match using \\frac\{(.*?)\}\{2} and substitute using \\frac{1}{2} \1 Updated code: import re regex = r"\\frac\{(.*?)\}\{2}" test_str = "I_{2}\\,\\mathrm{phi2dd}-\\frac{l_{2}\\,\\mathrm{lm}_{4}\\,\\cos\\left(\\varphi _{2}\\right)}{2}+\\frac{l_{2}\\,\\mathrm{lm}_{3}\\,\\sin\\left(\\varphi _{2}\\right)}{2}=0" subst = "\\\\frac{1}{2} \\1" # 4th argument decides how many occurences to replace result = re.sub(regex, subst, test_str, 0) if result: print (result)
has comment: http://stackoverflow.com/comment/85174965
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85175810
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49040518
type: Question
tagged with: class
answer count: 3
has answer: http://stackoverflow.com/a/49040616
has comment: http://stackoverflow.com/comment/85086483
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/49040591
tagged with: python
has answer: http://stackoverflow.com/a/49040591
has comment: http://stackoverflow.com/comment/85086504
has title: Python's initialization a list in a class
has body: I don't understand python's behavior, I've got many the same errors: File "./start.py", line 20, in print2 item.print2() RuntimeError: maximum recursion depth exceeded My code is the following: #!/usr/bin/python class Component: def print2(self): pass class Composite(Component): items = [] name = 'composite' def __init__(self, name): self.name = name def add(self, item): self.items.append(item) def print2(self): if self.items: for item in self.items: item.print2() else: print self.name class Leaf(Component): name = 'leaf' def __init__(self, name): self.name = name def print2(self): print self.name category = Composite('category1') leaf = Composite('leaf1') category.add(leaf) leaf = Leaf('leaf2') category.add(leaf) category.print2() When I add self.items = [] in the constructor ( __init__ ), it works fine. Could you explain the behavior?
has answer: http://stackoverflow.com/a/49040587
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/49040587

http://stackoverflow.com/comment/84966618
comment on: http://stackoverflow.com/q/48979023
score: 0
type: QuestionComment
type: Comment
has text: you may need to check the tensorflow lite, it using different model, that should be the only way to load in java. https://www.tensorflow.org/images/tflite-architecture.jpg?hl=zh-cn

http://stackoverflow.com/comment/85232719
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49113193
has text: Unfortunately I've tried every browser and it still isn't working. The issue stems from having to run a python script as well. Could it be my local storage not allowing chrome to access them? if it is how would i check that?
score: 0

http://stackoverflow.com/a/49073882
score: 0
type: Answer
has body: i found the solution , i maked the content of the txt file in a list with split method , def check_offline(text): list_pro = open('full-list-bad.txt','r') content = list_pro.read() list_content = content.split('\n') for word in list_content : if word in text : remplacement = "*" * len(word) text = text.replace(word ,remplacement) print word print remplacement return text print check_offline("this is a adult world " ) adult this is a ***** world
accepted answer of: http://stackoverflow.com/q/49072656
answers question: http://stackoverflow.com/q/49072656
type: AcceptedAnswer

http://stackoverflow.com/a/49120676
type: Answer
has body: Use sum and a generator expression that gives 1 if the element is in the sublist. import itertools collection = [['a','b','b','c','d','e','f'],['b','b','d','f']] all_letters = set(itertools.chain.from_iterable(collection)) # or write them out by hand # all_letters = {'a', 'b', 'c', 'd', 'e', 'f'} result = [(ch, sum(1 for sublst in collection if ch in sublst)) for ch in all_letters] # [('e', 1), ('d', 2), ('f', 2), ('b', 2), ('a', 1), ('c', 1)] # or some other order, since sets are orderless.
answers question: http://stackoverflow.com/q/49120597
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/84962742
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48977933
has text: @Gus I edited my answer to concatenate all the adjacent words that fullfill the `if` condition. It should work for your case, however, let me know if something's not working properly.
score: 0

http://stackoverflow.com/q/49023446
tagged with: ffmpeg
has answer: http://stackoverflow.com/a/49023774
tagged with: python
has comment: http://stackoverflow.com/comment/85068303
type: AnsweredQuestion
tagged with: command-prompt
has body: I know ">" and ">>" redirecting symbols would help to copy whole thing from command prompt , but how to copy a specific line with the required string ?
type: Question
accepted answer: http://stackoverflow.com/a/49023774
has title: how to copy specific output from command promt to a file?
has comment: http://stackoverflow.com/comment/85067731
score: 0
answer count: 1

http://stackoverflow.com/comment/84940343
has text: [How to share conda environments across platforms](https://stackoverflow.com/questions/39280638/how-to-share-conda-environments-across-platforms)
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48967229

http://stackoverflow.com/q/48994944
has answer: http://stackoverflow.com/a/48995080
has comment: http://stackoverflow.com/comment/84995285
type: Question
answer count: 2
favorite count: 0
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/84995441
downvote count: 3
tagged with: python
has title: ValueError: invalid literal for int() with base 10: '26.02.2018'
has body: So I was bored and decided to do a little bit of coding using Python (I'm a noob), when i got this error: Blockquote ValueError: invalid literal for int() with base 10: '26.02.2018' Here is the full script: print("This is case sensitive!") #Ask for the users name name_1 = input("What is your name?") #Ask for the users gender gender = input("Are you a male, a female or other(If other, then what?)?") #Ask for the users birthday birthday = input("When were you born?(DD.MM.YYYY)") #Ask for the users location location = input("In what country do you live?") import datetime now = datetime.datetime.now() today = now.strftime("%d.%m.%Y") today = int(today) birthday = int(birthday) age = today - birthday if gender == "male": print("Mr.", name_1) print(age) print (birthday ) print("Male") if birthday == today: print("Happy Birthday,Mr.", name_1) else: "" elif gender == "female": print ("female") else: print (gender) print ("Part of the LGBT+ Community.") This script is not complete.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48994976
has comment: http://stackoverflow.com/comment/84995280

http://stackoverflow.com/a/58995596
answers question: http://stackoverflow.com/q/49030629
type: Answer
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49030629
has body: I use py-spy with speedscope now. It is a very cool combination. py-spy works on Windows/Linux/macOS, can output flame graphs by its own and is actively deployed, eg. subprocess profiling support was added in October 2019.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48973318
linked to: http://stackoverflow.com/q/44109
score: -3
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84952018
downvote count: 3
type: Question
linked to: http://stackoverflow.com/q/15341285
has answer: http://stackoverflow.com/a/48973998
upvote count: 0
answer count: 1
has body: I know there is a Django shop you can implement but it doesn't seem to fit my need. I have a python code which returns a 2d list, which I then use jinja to display in HTML. Each list in the 2d list contains information about products and I was wondering if its possible to add an add to basket feature which stores that list to the user, I was thinking in a form of a dictionary, so the user can later see their basket.
favorite count: 0
has title: How to add a dictionary(or some other data type) to an account in Django
accepted answer: http://stackoverflow.com/a/48973998

http://stackoverflow.com/q/48975017
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84954886
has title: how is below code working? aren't tuples supposed to be immutable? please clarify
accepted answer: http://stackoverflow.com/a/48975060
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84954815
favorite count: 0
has comment: http://stackoverflow.com/comment/84954818
has body: &gt;&gt;&gt; tuple1 = (1,2,3,4) &gt;&gt;&gt; tuple2 = (3,4,5,6) &gt;&gt;&gt; tuple1 = tuple1+tuple2 &gt;&gt;&gt; print tuple1 (1, 2, 3, 4, 3, 4, 5, 6) &gt;&gt;&gt; Sorry if this is a noob question, and posting this as I could not find anything related to this.
tagged with: python
has comment: http://stackoverflow.com/comment/84954881
score: -1
has answer: http://stackoverflow.com/a/48975060
type: AnsweredQuestion

http://stackoverflow.com/a/49008985
answers question: http://stackoverflow.com/q/49002086
score: 0
has body: The APIs you are invoking have varying response formats. Hence the describe-security-groups command is not returning the details in a nice tabular format. The information you are looking for can not be obtained in a tabular format. You can get it in text format though: aws ec2 describe-security-groups --filters Name=ip-permission.cidr,Values='0.0.0.0/0' --query "SecurityGroups[*].[[GroupName,GroupId,IpPermissions[].FromPort][]]" --output text
type: Answer
has comment: http://stackoverflow.com/comment/85066055
has comment: http://stackoverflow.com/comment/85047255

http://stackoverflow.com/a/49117646
answers question: http://stackoverflow.com/q/49117441
type: Answer
has body: You could use any to check the presence of an element from one list to another: import pandas df = pd.DataFrame({'column': ['vivek is sleeping','karti is eating','ramu is walking']}) keyword = ['sleeping', 'eating', 'walking'] ## check if the keyword is present df['is_available'] = df['column'].map(lambda x: any([y for y in x.split() if y in keyword])) print(df) column is_available 0 vivek is sleeping True 1 karti is eating True 2 ramu is walking True
score: 0

http://stackoverflow.com/comment/84949715
type: AnswerComment
comment on: http://stackoverflow.com/a/48964604
type: Comment
has text: And how can i do this? I don’t understand it, but at least, The noise module is now working for me
score: 0

http://stackoverflow.com/comment/85079540
type: Comment
has text: *"Follow-up question then, is the scipy randint a class? of which you instantiate an object?"* No, `scipy.stats.randint` is an instance of the class `scipy.stats.randint_gen`. `scipy.stats.randint` is ready to use--you can call its methods without instantiating any additional objects.
score: 2
comment on: http://stackoverflow.com/a/49036934
type: AnswerComment

http://stackoverflow.com/a/48966177
accepted answer of: http://stackoverflow.com/q/48965985
type: Answer
has body: Can't you just create the graph and remove the node (or nodes if necessary), eg: import networkx as nx simple_graph = { 'A': ['B'], 'B': ['A', 'C', 'D'], 'C': ['A'], 'D': ['E', 'A', ''], 'E': ['B', ''] } g = nx.DiGraph(simple_graph) g.remove_node('') Then g.edges() will give you: OutEdgeView([('A', 'B'), ('E', 'B'), ('D', 'A'), ('D', 'E'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A')])
downvote count: 0
score: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48965985
upvote count: 5

http://stackoverflow.com/a/49091153
has body: You can use json.loads: import json info = ['{"contributors": null, "truncated": true, "text": "hey there"}', '{"contributors": null, "truncated": false, "text": "how are you"}', '{"contributors": 10, "truncated": false, "text": "howdy"}'] info = [json.loads(x) for x in info] print(info) Output: [{'contributors': None, 'truncated': True, 'text': 'hey there'}, {'contributors': None, 'truncated': False, 'text': 'how are you'}, {'contributors': 10, 'truncated': False, 'text': 'howdy'}]
score: 5
type: AcceptedAnswer
upvote count: 6
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49091132
answers question: http://stackoverflow.com/q/49091132

http://stackoverflow.com/comment/84974769
comment on: http://stackoverflow.com/q/48985027
type: Comment
type: QuestionComment
has text: You want to delete unmatched column or row?
score: 1

http://stackoverflow.com/comment/85152674
has text: Sure. Well, this isn't actually the same as my old code. But I'll write an example right now and put it into my description.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49073355
score: 0

http://stackoverflow.com/q/49115765
type: AnsweredQuestion
has title: Verify if 2 LineString (shapely) are parallel
upvote count: 3
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49116322
score: 3
possible better answer: http://stackoverflow.com/a/67313757
has answer: http://stackoverflow.com/a/67313757
accepted answer: http://stackoverflow.com/a/49116322
answer count: 2
tagged with: shapely
downvote count: 0
has body: I have 2 shapely.LineString, and I would like to verify if they are parallel. a = LineString(((0, 0), (0 , 1))) b = LineString(((1, 0), (0.9, 1))) #Not intersecting, but also not parallel) When I use intersects, the intersects, it returns False because the 2 lines are not intersecting, but they are also not parallel. Is there a method in Shapely to verify parallelism? I could use the angle (via np.arctan).
has comment: http://stackoverflow.com/comment/85237544
favorite count: 0
tagged with: python

http://stackoverflow.com/a/49051527
has comment: http://stackoverflow.com/comment/85107909
accepted answer of: http://stackoverflow.com/q/49051407
score: 3
has comment: http://stackoverflow.com/comment/85160054
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49051407
has body: I presume it stands for "iterable slice", since it takes the same arguments as the slice built-in but generates a sequence of results rather than returning a list. You may be suffering from some slight misunderstanding of "infinitive," which is a part of speech (in English, "to fall" is the infinitive of the verb "fall"). You perhaps mean "infinite," which is never-ending or uncountable. If so, you have correctly observed that one advantage of the functions in itertools is that they can be applied to infinite sequences. This is because they return iterators that yield results on demand, rather than functions that return lists.
has comment: http://stackoverflow.com/comment/85107700
type: Answer
upvote count: 3

http://stackoverflow.com/q/49016530
type: Question
has comment: http://stackoverflow.com/comment/85038610
tagged with: keras
has comment: http://stackoverflow.com/comment/85170934
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/85180612
has comment: http://stackoverflow.com/comment/85038291
has comment: http://stackoverflow.com/comment/85055066
has body: Im trying to implement Grad-CAM as explained in this amazing book. However in the model from the book they are not using a dropout layer but I am so the example code provided does not run. I am using the following model: Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 30, 30, 32) 896 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 15, 15, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 13, 13, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 6, 6, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 4, 4, 128) 73856 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 2, 2, 128) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 512) 0 _________________________________________________________________ dropout_1 (Dropout) (None, 512) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 262656 _________________________________________________________________ dense_2 (Dense) (None, 256) 131328 _________________________________________________________________ dense_3 (Dense) (None, 128) 32896 _________________________________________________________________ dense_4 (Dense) (None, 43) 5547 And would like to get the following code working: from tensorflow.python.keras.backend import mean, function, gradients roadwork_output = model.output[:, 25] # 25 is the label for roadwork last_conv_layer = model.get_layer('conv2d_3') grads = gradients(roadwork_output, last_conv_layer.output)[0] pooled_grads = mean(grads, axis=(0, 1, 2)) iterate = function([model.input], [pooled_grads, last_conv_layer.output[0]]) pooled_grads_value, conv_layer_output_value = iterate([resi…
has comment: http://stackoverflow.com/comment/85054160
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85039300
has comment: http://stackoverflow.com/comment/85055034
has title: Adding function parameters to Keras backend function for Grad-CAM to work with dropout
has comment: http://stackoverflow.com/comment/85167808
tagged with: python
has comment: http://stackoverflow.com/comment/85039802
tagged with: tensorflow

http://stackoverflow.com/comment/85111722
comment on: http://stackoverflow.com/q/49053435
score: 0
type: QuestionComment
has text: Yes. This is just dummy data. But in reality sometimes they will be the same, other times they will be different.
type: Comment

http://stackoverflow.com/a/49088345
score: 1
has comment: http://stackoverflow.com/comment/85182264
has comment: http://stackoverflow.com/comment/85182213
upvote count: 1
has body: You could use a keyword argument to pass on the recursion depth. def f1(t, _max_depth=10): if _max_depth &gt; 0: if t &lt; 0: return 0 result = 0 result = 1.5 * f2(t-1, _max_depth=_max_depth - 1) + 3.5 * f1(t-1, _max_depth=_max_depth - 1) return result else: # return some default value here You can do the same for f2.
answers question: http://stackoverflow.com/q/49086677
has comment: http://stackoverflow.com/comment/85182347
type: Answer
has comment: http://stackoverflow.com/comment/124401873
has comment: http://stackoverflow.com/comment/85201548
downvote count: 0

http://stackoverflow.com/comment/85169221
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49081813
type: Comment
has text: My images are mostly up-close pictures of the face. I don't split the sets in the code, I have a large amount of images on my drive. There, I sort them into the train and validation folders that I have defined. Correct me if I'm wrong, but the validation set is irrelevant in this case is it not? I am feeding it images on my own after it trains, and they are quite similar to the images I am using to train.

http://stackoverflow.com/comment/84992615
type: AnswerComment
has text: Yes, right, I fixed sigmoid, but, unfortunatelly, it makes no difference because I used 1./sigmoid before so the result formula did not change.
type: Comment
comment on: http://stackoverflow.com/a/48993564
score: 0

http://stackoverflow.com/comment/85147239
type: QuestionComment
has text: Are your inputs scaled between 0 and 1 or -1 and 1? Also, looking at your hidden layers, 4 might be overkill. In most cases, 1-2 hidden layers are good enough. And I would keep the number of neurons between 1 to the number of columns.
score: 0
comment on: http://stackoverflow.com/q/49070253
type: Comment

http://stackoverflow.com/comment/85015797
has text: Just replace strip(" ") by rstrip(" ") and it works. Point is that the elt you want to parse are starting at the same ID. We don't care at which they end, and remove only the space at the end.
comment on: http://stackoverflow.com/a/49005227
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84946040
has text: No. You can transfer data over a network. But it's unlikely to get you the performance you need, simply because of network latency and lag in packing the data for sending and unpacking it on receipt.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48970272

http://stackoverflow.com/comment/85108106
type: QuestionComment
comment on: http://stackoverflow.com/q/49051488
score: 1
has text: Well, while I'm not sure what is unclear about that (`nrows` are the number of subplot rows of your plot, `ncols` are the number of columns; here you want one row and three columns), *that* would actually be a question you can ask here - although make sure it hasn't also been asked before.
type: Comment

jupyter-notebook
tags question: http://stackoverflow.com/q/49039750
tags question: http://stackoverflow.com/q/48986025
tags question: http://stackoverflow.com/q/49087317
tags question: http://stackoverflow.com/q/49100236
tags question: http://stackoverflow.com/q/49037430
tags question: http://stackoverflow.com/q/48972735
tags question: http://stackoverflow.com/q/49072664
tags question: http://stackoverflow.com/q/49002274
tags question: http://stackoverflow.com/q/48993288
tags question: http://stackoverflow.com/q/48977441
tags question: http://stackoverflow.com/q/49099147
tags question: http://stackoverflow.com/q/49064113
tags question: http://stackoverflow.com/q/49012323
tags question: http://stackoverflow.com/q/49056028
tags question: http://stackoverflow.com/q/49021802
type: Tag
tags question: http://stackoverflow.com/q/49105469
tags question: http://stackoverflow.com/q/49020056
tags question: http://stackoverflow.com/q/49100959
tags question: http://stackoverflow.com/q/49060525
tags question: http://stackoverflow.com/q/48964883
tags question: http://stackoverflow.com/q/49021464
tags question: http://stackoverflow.com/q/49046757
tags question: http://stackoverflow.com/q/49065265
tags question: http://stackoverflow.com/q/49045213
tags question: http://stackoverflow.com/q/49107183
tags question: http://stackoverflow.com/q/49089127
tags question: http://stackoverflow.com/q/48976352
tags question: http://stackoverflow.com/q/49118477
tags question: http://stackoverflow.com/q/49026551
tags question: http://stackoverflow.com/q/49083326
tags question: http://stackoverflow.com/q/48976611
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/49112580
tags question: http://stackoverflow.com/q/49060661
tags question: http://stackoverflow.com/q/49074290
tags question: http://stackoverflow.com/q/49097639
tags question: http://stackoverflow.com/q/49032555
tags question: http://stackoverflow.com/q/49059521

twitter
tags question: http://stackoverflow.com/q/49068214
type: Tag
tags question: http://stackoverflow.com/q/49083005
tags question: http://stackoverflow.com/q/48966176
tags question: http://stackoverflow.com/q/49036563
tags question: http://stackoverflow.com/q/49027297
tag name: twitter
tags question: http://stackoverflow.com/q/49098726
tags question: http://stackoverflow.com/q/49000392
tags question: http://stackoverflow.com/q/49024296

http://stackoverflow.com/comment/85042438
type: Comment
comment on: http://stackoverflow.com/q/49018087
type: QuestionComment
score: 0
has text: Paste a few lines.

http://stackoverflow.com/comment/85217826
has text: Just to clarify, you want the communities that appear on your plot? If this is the case I can update my answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/49081304
score: 0
type: Comment

http://stackoverflow.com/comment/85251172
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49119628
has text: Thank you everyone for the fast replies! I'm extremely new at this so not sure how to access some of the info (like if Python is using the binary command line and how it's being launched) but it sounds like my best bet is using Python 3 (which doesn't seem to have the bug) and a better text editor.

http://stackoverflow.com/a/49140736
type: Answer
has comment: http://stackoverflow.com/comment/85300594
accepted answer of: http://stackoverflow.com/q/49084154
has body: Instead of hacking globals() it would be better to define __getattr__ for your module as follows: module_name.py foo = 'foo' def bar(): return 'bar' my_module.py import sys import module_name class MyModule(object): def foobar(self): return 'foobar' def __getattr__(self, item): return getattr(module_name, item) sys.modules[__name__] = MyModule() and then: &gt;&gt;&gt; import my_module &gt;&gt;&gt; my_module.foo 'foo' &gt;&gt;&gt; my_module.bar() 'bar' &gt;&gt;&gt; my_module.foobar() 'foobar'
score: 9
upvote count: 9
downvote count: 0
has comment: http://stackoverflow.com/comment/85299802
has comment: http://stackoverflow.com/comment/85296464
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49084154

http://stackoverflow.com/q/49013801
has comment: http://stackoverflow.com/comment/85032552
linked to: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/85032460
score: -2
has comment: http://stackoverflow.com/comment/85032452
has comment: http://stackoverflow.com/comment/85032535
answer count: 3
has body: In this code, I tried if the number input is 000 get out of the loop with a nested if statement but it doesn't work. get this error: IndentationError: expected an indented block var=1; while var==1: num=int(input("Enter a number:")) if (isinstance(num, int)): print("your input number:",num) if(num==000): break else: print('incorrect!!!')
has comment: http://stackoverflow.com/comment/85032453
has answer: http://stackoverflow.com/a/49013957
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49013885
has answer: http://stackoverflow.com/a/49013873
has title: Use nested if statement in a while loop
has comment: http://stackoverflow.com/comment/85032379
downvote count: 3
duplicate of: http://stackoverflow.com/q/45621722
type: Question

http://stackoverflow.com/q/49077694
favorite count: 0
accepted answer: http://stackoverflow.com/a/49078673
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49078673
downvote count: 0
score: 1
has body: I'm trying to make an excel file I upload to Firebase storage (google cloud storage) publicly available as a link. When I use the method blob.make_public() I get a Forbidden 403 error: Insufficient permission. I'm using the Firebase Admin SDK for python. As far as I can tell in the IAM part of the cloud console the admin SDK has Editor and Storage Object Admin roles. Any way to make the uploaded object public through python? Haven't found anything else that works in the docs: Python GCS API Thanks. Code example # Access google cloud storage bucket bucket = firebase_admin.storage.bucket(app=app) # Blob - Google's wrapper for objects stored in buckets destination_blob_name = 'excelReports/' + filename + '_' + datetime.now().strftime("%b_%d_%Y_%H_%M_%S") blob = bucket.blob(destination_blob_name) # Upload file blob.upload_from_filename(filename) # Make the file available for public download by those who have the link. blob.make_public()
type: Question
tagged with: firebase
tagged with: firebase-admin
tagged with: google-cloud-storage
upvote count: 1
has title: google cloud storage make object public through python Firebase admin SDK
answer count: 1

http://stackoverflow.com/q/49071707
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/85148921
answer count: 0
has comment: http://stackoverflow.com/comment/85149008
has body: I have define some function. I tried to use lambdas insted of using for loop. But can't able to figure out why it is not working. my function is like: def dis_find(df,X,Y): base = (df.x[X],df.y[X]) inter = (df.x[Y],df.y[Y]) dis = (vincenty(base, inter).km) return np.round(dis) where df is my data-frame, and X and Y are Coordinates. Value of X is constant but Y will be from the list. instead of using for loop i tried: list(map(lambda Y : dis_find(df,tr_stn,Y),Y)) Here Y is the list of Coordinates. Error massage is df is not define? How to do that?
type: Question
has title: running function in lambdas
has comment: http://stackoverflow.com/comment/85148839
has comment: http://stackoverflow.com/comment/85148833

http://stackoverflow.com/comment/85242130
type: AnswerComment
has text: @Tai Why not, it's a pretty decent option _in this case_.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49103547

http://stackoverflow.com/q/49047914
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49047957
accepted answer: http://stackoverflow.com/a/49047957
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
answer count: 1
tagged with: foreign-keys
upvote count: 1
linked to: http://stackoverflow.com/q/49150613
favorite count: 0
has body: I'm trying to make my dashboard show a list of users in your area. This so far works but I can not get the user's fist image to show. The current error message I am getting is "'QuerySet' object has no attribute 'id'" models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) views.py class DashboardView(TemplateView): template_name = 've/cp/dashboard.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DashboardView, self).dispatch(*args, **kwargs) def get(self, request, pk=None): users = User.objects.exclude(id=request.user.id) user = User.objects.filter(pk=pk) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { 'users': users, 'favorites':favorites, 'images': Images.objects.filter(user_id=user.id) } return render(request, self.template_name, args) dashboard.html People near you {% for user in users %} {{ user.username }} {{ user.images }} {% if images %} {% for img in images %} {% endfor %} {% else %} No images {% endif %} {% if not user in favorites %} Add Favorite {% endif %} {% endfor %}
has title: Django Foreign Key in View - get first image to show for each user in list

http://stackoverflow.com/a/60561841
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49098469
upvote count: 1
has body: You can use psutil package: Install pip install psutil Usage: In order to get process id using process name refer the following snippet: import psutil process_name = "fud" def get_pid(process_name): for proc in psutil.process_iter(): if proc.name() == process_name: return proc.pid

http://stackoverflow.com/comment/85179475
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49083479
has text: That's the `type`. I want to see `csv_matrix.dtype`. The error suggests it's a mix of objects. Even if it is `float`, `unique` won't work well. Floats are close to each other, and rarely exactly equal.

http://stackoverflow.com/q/49010813
has answer: http://stackoverflow.com/a/49011141
tagged with: subprocess
type: UnansweredQuestion
tagged with: web-scraping
upvote count: 1
tagged with: python
tagged with: python-requests
has body: FindAll doesn't find the class I need. However I was able to find the class above that one, but the data structure is not that well organized. Do you know what can we do to get the data or organize the output from the class above which has all the data together ? Please see the HTML below and the images. import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.vivino.com/explore?e=eJzLLbI11jNVy83MszU0UMtNrLA1MVBLrrQtLVYrsDVUK7ZNTlQrS7YtKSpNVSsviY4FioEpIwhlDKFMIJQ5VM4EAJCfGxQ=' #Opening a connection uClient = uReq(my_url) page_html = uClient.read() uClient.close() #html parse page_soup = soup(page_html, "html.parser") container = page_soup.findAll("div", {"class":"wine-explorer__results__item"}) len(container)
has comment: http://stackoverflow.com/comment/85026328
has comment: http://stackoverflow.com/comment/85026236
score: 1
type: Question
has comment: http://stackoverflow.com/comment/85026170
downvote count: 0
has answer: http://stackoverflow.com/a/49014832
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85026742
answer count: 3
has title: How to find a particular class in BeautifulSoup using findAll
has comment: http://stackoverflow.com/comment/85026659
favorite count: 0
has answer: http://stackoverflow.com/a/49011574

http://stackoverflow.com/comment/84953218
has text: While true, this is a separate issue and not an answer to the question.
score: 2
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48974194

http://stackoverflow.com/q/49049378
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/49049978
has comment: http://stackoverflow.com/comment/85103162
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49049755
has body: I have multiple text files. Each file is a list of animals and their counts for a house. Like this: houseA.txt cats 3 dogs 1 birds 4 houseB.txt cats 5 dogs 3 birds 1 I have about 20 houses and each house has about 16000 species (so each file has about 16000 lines. All houses have the same species, just different counts for each specie. My current script loops through each file, line by line, and captures the house, specie name and its count. I want to create a dictionary of houses, where each house is a dictionary of animals and their counts. So from the example above, the result would look like this: dictOfDicts{houseA:{'cats': 3, 'dogs': 1, 'birds': 4}, houseB:{'cats': 5, 'dogs': 3, 'birds': 1}} In case you're wondering, this will later be turned into a table: house: A B animal cats 3 5 dogs 1 3 birds 4 1 Here's my script: #!/usr/bin/python3 import sys houseL = [] dictList = [] with open(sys.argv[1], 'r') as files: for f in files: f = f.rstrip() with open(f, 'r') as aniCounts: house = str(aniCounts).split(sep='/')[2] # this and the next line captures the house name from the file name. house = house.split('.')[0] houseL.append(house) for line in aniCounts: ani = line.split()[0] count = line.split()[1] #print(ani, ' ', count) EDIT: Changed question to dict of dicts, thanks to a helpful commenter.
has title: Create multiple dynamic dictionaries in a dictionary
possible better answer: http://stackoverflow.com/a/49049755
has comment: http://stackoverflow.com/comment/85137932
type: Question
has answer: http://stackoverflow.com/a/49049565
has comment: http://stackoverflow.com/comment/85102834
answer count: 3
score: 2
accepted answer: http://stackoverflow.com/a/49049565
downvote count: 0
has comment: http://stackoverflow.com/comment/85103649
favorite count: 0

http://stackoverflow.com/comment/85136078
type: Comment
comment on: http://stackoverflow.com/q/49065265
score: 0
type: QuestionComment
has text: if you have current version of Jupyter try with class name and shift+tab probably will show definition of class..

http://stackoverflow.com/q/49062983
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85131123
downvote count: 2
tagged with: scp
type: Question
has answer: http://stackoverflow.com/a/49063283
has comment: http://stackoverflow.com/comment/85131265
has body: I am getting the following error FileNotFoundError: [WinError 3] The system cannot find the path specified The paths are actually valid, definitely. I do see the files in the folder specified. Update: I swapped the local and remote path but still the same error: I checked on the remote server again, the file does exist on the server:
has comment: http://stackoverflow.com/comment/85131340
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85131295
has comment: http://stackoverflow.com/comment/85131310
accepted answer: http://stackoverflow.com/a/49063283
has title: How to copy file from remote server over SSH using Paramiko Python? FileNotFoundError: [WinError 3] The system cannot find the path specified
favorite count: 0
has comment: http://stackoverflow.com/comment/85131434
tagged with: ssh
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/85131182

fractions
type: Tag
tags question: http://stackoverflow.com/q/49039473
tag name: fractions

google-bigquery
tags question: http://stackoverflow.com/q/48980886
type: Tag
tag name: google-bigquery

http://stackoverflow.com/a/49089234
has comment: http://stackoverflow.com/comment/85184072
type: Answer
score: -1
downvote count: 1
has body: You can just collect all websites in set and in the end subtract remo set from it: filtered_websites = websites - set(["listings", "nationwide"])
has comment: http://stackoverflow.com/comment/85184024
answers question: http://stackoverflow.com/q/49089165
upvote count: 0

http://stackoverflow.com/comment/85247176
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49119522
has text: There are other operations in java that allow you to specify multiple inputs to insert into a list. Overall, I think it is just doing around the same thing if you are working with arrays. Try this, open.addAll(Arrays.asList(new int[] { 1, 2, 3, 4}));

http://stackoverflow.com/comment/85153414
has text: Why do you think `defaultdict` preferable to the pandas solution or a dict comprehension in this case?
comment on: http://stackoverflow.com/a/49061572
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48978773
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48978824
accepted answer: http://stackoverflow.com/a/48978824
type: Question
has title: isPrime test using list of factors
possible better answer: http://stackoverflow.com/a/48978878
score: 0
answer count: 3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48978878
has answer: http://stackoverflow.com/a/48978914
favorite count: 0
tagged with: python-3.x
has body: I'm trying to create a python program to check if a given number "n" is prime or not. I've first created a program that lists the divisors of n: import math def factors(n): i = 2 factlist = [] while i &lt;= n: if n% i == 0: factlist.append(i) i = i + 1 return factlist factors(100) Next, I'm trying to use the "for i in" function to say that if p1 (the list of factors of n) only includes n itself, then print TRUE, and if else, print FALSE. This seems really easy, but I cannot get it to work. This is what I've done so far: def isPrime(n): p1 = factors(n) for i in p1: if factors(n) == int(i): return True return False Any help is appreciated! This is a hw assignment, so it's required to use the list of factors in our prime test. Thanks in advance!
tagged with: python

http://stackoverflow.com/a/48970484
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48970416
has body: There's various routes that you can take. Assuming you want to print the first 3 elements of your array, here's two: array=[1,2,3,4,5] 1) Slice the array # start at index 0 and go until index 2 for record in array[0:3]: print(record) 2) Use a variable to iterate over the array # range(3) = [0, 1, 2] for i in range(3): print(array[i])
score: 4
upvote count: 4

http://stackoverflow.com/q/49000692
tagged with: python
tagged with: dictionary
upvote count: 0
has answer: http://stackoverflow.com/a/49000738
type: UnansweredQuestion
tagged with: django
has body: So I have the following code: views.py: def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) return render(request, 'learning_logs/topic.html', context) I understand that I am querying the database and sorting the data by date then storing that data in the topics variable. My first question is, is the topics variable storing the data as a list? (assuming multiple entries). If so when I have the following code in my html file topics.html: {% for topic in topics %} {{ topic }} {% empty %} No topics have been added yet. {% endfor %} why do I need pass the data stored in topics into a context dictionary for topics.html to loop through and display the data? why not loop through the topics variable itself? I'm just confused on the use of "contexts" Thanks for the help in advance.
score: -1
type: Question
answer count: 1
downvote count: 1
tagged with: url
has title: context and dictionaries python Django
favorite count: 0
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/48972470
tagged with: python
upvote count: 13
tagged with: timeit
linked to: http://stackoverflow.com/q/10471897
has comment: http://stackoverflow.com/comment/108652937
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71817138
has comment: http://stackoverflow.com/comment/84950006
linked to: http://stackoverflow.com/q/48769703
score: 13
has comment: http://stackoverflow.com/comment/108652955
has comment: http://stackoverflow.com/comment/84950339
type: Question
linked to: http://stackoverflow.com/q/32565829
linked to: http://stackoverflow.com/q/56763416
tagged with: ipython
has title: %%timeit not returning defined variable
answer count: 1
downvote count: 0
has body: I'm trying to use IPython magic command %%timeit and I run into some problems. The chunk that I'm trying to time is not returning a variable I define in it. Specifically, let's say I want to measure how long does it take to set variable var to 30. %%timeit var = 5 * 6 Running this chunk, I get something like 16.8 ns ± 0.303 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each). When I later try to call var, I get NameError: name 'var' is not defined. I found this question, however, I'm not sure what to take from it. Also, it is from 2014 so I think there could have been some changes. Is there a way how to 'keep' variable defined in a chunk with %%timeit so that it can be later called? I'm using Python 3.6, Anaconda 4.4.10.
favorite count: 0
has comment: http://stackoverflow.com/comment/84957425

http://stackoverflow.com/a/48977207
score: 1
answers question: http://stackoverflow.com/q/48977025
upvote count: 1
downvote count: 0
has body: Try this (it only prints for john, maria and stacy): data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45), ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)] permitted_names = ['john', 'maria', 'stacy'] output = {} for name, gender, age in data: if name not in permitted_names: pass elif name not in output: output[name] = '{0}({1})'.format(gender, age) else: output[name] += ' {0}({1})'.format(gender, age) for name, value in output.items(): print("{0}: {1}".format(name, value)) Output: john: m(23) m(45) maria: f(17) stacy: f(19) f(21)
type: Answer

http://stackoverflow.com/a/49024227
score: 1
type: Answer
upvote count: 2
downvote count: 1
has body: Let me know if you're aware of a more traditional way to solve this that will also work for classes that use __slots__. But for my use case, the below will work: class X: var = [1,2] def __init_subclass__(cls): attr_name = 'var' if not attr_name in cls.__dict__: raise NotImplementedError( "Attribute '{}' has not been overriden in class '{}'" \ .format(attr_name, cls.__name__) ) class Y(X): # var = X.var + [3,4] # this will work pass # this won't work y = Y() edit: There is another downside to using this approach, which is that this will wrongly error for grandchildren who do not override: class Y(X): var = X.var + [3,4] y = Y() # this works class Z(Y): pass z = Z() # this errors I will leave this answer as unmarked for someone to suggest a better alternative.
answers question: http://stackoverflow.com/q/49022656

http://stackoverflow.com/comment/84977800
type: Comment
comment on: http://stackoverflow.com/a/48983648
score: 0
type: AnswerComment
has text: what you mean by side by side?

http://stackoverflow.com/comment/85026128
type: QuestionComment
has text: code is added !
comment on: http://stackoverflow.com/q/49010738
score: 0
type: Comment

http://stackoverflow.com/q/49096755
has comment: http://stackoverflow.com/comment/85202556
has body: Hi so I have this program which basically goes into the inbox and then looks at the latest email. Scans it and if it has a link it gives you a notification, or if it has an attachment it gives a notification. Everything is working fine although I tried to combine the two notifications into one. So it's a bit nicer, instead of having one notification show, then another right after it. If an email has both a link and attachment. I'd of prefer it just to be one notification if the email has both and then separate notifications if they only contain either a link or attachment. I've tried to split it up into a if and elif loop. I can get a notification to appear for both if I do an 'and' within the loop in the if statement - e.g if any(word in html_text for word in word) and file_name == None: fboth() fboth() (this is the function that would tell you there is both a link and attachment, just like flink() and fattach()) although when I put my other options as elif: statements, one for a link by itself and one for an attachment by itself. Those still play out even though it found the first statement to be True and it alerts that the email has both a link and attachment. Is there away to stop this? I'm starting to think it's another if statement? But I had a few failed attempts and maybe not fully understanding it. Is my theory correct with how I am tackling it by still using the for loop? Here is the code: import imaplib import email import Tkinter as tk import time word = ["href=", "href", "&lt;a href="] #list of strings to search for in email body #connection to the email server mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('xxxx', 'xxxx') mail.list() latest_email_uid = '' #Finding a link popup def flink(): flink = tk.Tk() flink.title("Found Link") tk.Label(flink, text="Email has link in body\n" + "From: " + msg['From'] + "\n" + "Subject: " + msg['Subject'] + "\n" + "Date: " + msg['Date'], fg='yellow', bg='black').pack() flink.after(5000, lambda: flink.destroy())…
has answer: http://stackoverflow.com/a/49097674
type: Question
tagged with: for-loop
upvote count: 0
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/49097674
has title: Python, combining if and for loops
tagged with: email
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85199548
has comment: http://stackoverflow.com/comment/85198701
downvote count: 2
tagged with: imaplib
type: AnsweredQuestion

http://stackoverflow.com/q/48973972
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48975181
tagged with: tensorflow
has body: I had trained network N first and saved it with the saver into checkpoint Checkpoint_N. There were some variable scopes defined within N. Now, I want to build a siamese network using this trained network N as below: with tf.variable_scope('siameseN',reuse=False) as scope: networkN = N() embedding_1 = networkN.buildN() # this defines the network graph and all the variables. tf.train.Saver().restore(session_variable,Checkpoint_N) scope.reuse_variables() embedding_2 = networkN.buildN() # define 2nd branch of the Siamese, by reusing previously restored variables. When I do the above, the restore statement throws a Key Error that siameseN/conv1 was not found in the checkpoint file for every variable in N's graph. Is there a way to do this, without changing the code of N? I just basically added a parent scope to every variable and operation in N. Can I restore the weights to the right variables by telling tensorflow to ignore the parent scope or something?
type: Question
answer count: 2
downvote count: 0
score: 7
favorite count: 0
linked to: http://stackoverflow.com/q/45606298
has answer: http://stackoverflow.com/a/48976024
has answer: http://stackoverflow.com/a/48975181
has title: Tensorflow restore while ignoring scope name or into new scope name
possible better answer: http://stackoverflow.com/a/48976024
tagged with: python
upvote count: 7

http://stackoverflow.com/a/49513617
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49110344
type: Answer
has comment: http://stackoverflow.com/comment/100493728
answers question: http://stackoverflow.com/q/49110344
downvote count: 0
score: 1
has body: I have a workaround for this issue. Instead of using the library python-docx to extract the text from the docx file, I used the library docx2txt (extract all the text) and then I just needed to find the specific word in the string. text = docx2txt.process(file) q = "Example1" result = text[text.find(q)+len(q):].split()[0] and this gives me the "Yes" or "No" from Column2, for each value on Column1 (In the example above, it gives Yes).

http://stackoverflow.com/q/49011579
has body: I have two piped programs: a debug log which updates very quickly which sends the information to a python program which processes the information: ./debugClient | python processor.py The problem is, the debugClient program produces output real-time and the processor program needs to be able to process at real-time as well. It is entirely okay and expected that some information is missed as long as the program occurs real-time. However when the two are piped together I seem to only get old debug information going to processor.py. I understand why this might be the case as the two programs are supposed to run concurrently and the program involves more than just a STDIN loop. But I am confused on the buffer involved and why the new information isn't being sent instead of the old info.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85029331
tagged with: pipe
type: Question
accepted answer: http://stackoverflow.com/a/49052319
answer count: 1
has comment: http://stackoverflow.com/comment/85027740
tagged with: bash
tagged with: python
has title: Stop piped programs from exchanging outdated information
score: 0
has answer: http://stackoverflow.com/a/49052319

http://stackoverflow.com/comment/85249779
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49108274
has text: [This answer](https://stackoverflow.com/a/2259387/7675174) shows how to check for file existence, `os.path.isfile(path)`. Try that before loading the image to verify that you're trying to open a valid file.

http://stackoverflow.com/q/49087480
type: Question
has comment: http://stackoverflow.com/comment/85182471
has comment: http://stackoverflow.com/comment/85181734
has comment: http://stackoverflow.com/comment/85184230
upvote count: 2
has title: Make parallel concurrent calls to external apis from django
tagged with: apache
has comment: http://stackoverflow.com/comment/85183264
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85181063
has body: I have a django app (django+python+apache mod_wsgi) which act as a middleware between two systems, app gets requests from one system and it makes multiple requests to other apis to fetch and prepare the desired response, and then it passes the response to the requesting system. So it's basically acting as a one-to-many middleware, problem is making calls sequentially is taking too much time, I tried to use threading for IO concurrency. However this is not working (I've read django works on single thread; correct me if I'm wrong), I've not worked with making requests in parallel on a webserver and have no idea how to do it. Following is the current implementation : with futures.ThreadPoolExecutor(max_workers=MAX_BATCH_SIZE) as executor: future_to_url = {} for pnode in plist_node: config = {'url':rurl} futur = executor.submit(self.get_result_from_url, config) Can someone please suggest the right way to do this ?
score: 2
answer count: 0
downvote count: 0
tagged with: mod-wsgi
tagged with: django

http://stackoverflow.com/comment/85234019
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49108518
has text: Can you please tell me, what is happening here?
score: 0

http://stackoverflow.com/q/49036537
has answer: http://stackoverflow.com/a/49037331
score: 2
type: AnsweredQuestion
has body: I have transformed the following toy chemical reactions into a DataFrame for further bipartite network representation: R1: A + B -&gt; C R2: C + D -&gt; E SourceTarget R1 C A R1 B R1 R2 E C R2 D R2 Now, I want to create a new DataFrame from this one, representing only the relationships between the reactions based on their compounds, for example: In the DataFrame above C is a Target from R1 and C is also Source for R2, then, the relationship should be: R1-&gt;R2 (the only reaction-reaction relationship I can obtain for the Daframe above) The code I have created for this task is the following: newData=[] for i in range(0,len(data["Target"].index.values)): for j in range(0,len(data["Source"].index.values)): if data.iloc[i,1] == data.iloc[j,0] and not re.match("R.", data.iloc[i,1], flags=0): newData.append(data.iloc[i,0] +"\t" + data.iloc[j,1]) The code works, however, for big tables (thousands of rows) it gets very slow... I'm still a beginner, so I would be really glad if you could help me to improve it. Thanks =D
type: Question
has comment: http://stackoverflow.com/comment/85078174
answer count: 2
has answer: http://stackoverflow.com/a/49036643
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/49037331
has title: How to find the elements from one column which also appear in another column of a DataFrame in Python
upvote count: 2
possible better answer: http://stackoverflow.com/a/49036643

http://stackoverflow.com/a/49066172
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/49064817
upvote count: 4
answers question: http://stackoverflow.com/q/49064817
downvote count: 0
has body: Do you want to separate several numbers? 1 2 3 -> [1, 2, 3] n = str(input()) n = n.split() numbers = [int(i) for i in n] print(numbers) Or split a number in numeral? 123 -> [1, 2, 3] n = str(input()) numbers = [int(i) for i in n] print(numbers) Use Nikhil answer, if you want to split a number with delimiters 1%3 -> [1, 3]
type: AcceptedAnswer

http://stackoverflow.com/comment/85199594
comment on: http://stackoverflow.com/a/49091540
has text: @piRSquared, thank you, will edit the sorting caveat into my answer. I saw that the example data was sorted chronologically, but this approach indeed fails on unsorted input.
type: AnswerComment
score: 0
type: Comment

peewee
tag name: peewee
tags question: http://stackoverflow.com/q/48986433
type: Tag
tags question: http://stackoverflow.com/q/49115997
tags question: http://stackoverflow.com/q/48990017
tags question: http://stackoverflow.com/q/49119128

http://stackoverflow.com/q/49000091
type: UnansweredQuestion
tagged with: python
score: 8
linked to: http://stackoverflow.com/q/7577923
downvote count: 0
tagged with: celery
upvote count: 8
type: Question
has title: Celery/Redis task expiration
answer count: 1
has answer: http://stackoverflow.com/a/49462840
tagged with: celeryd
favorite count: 0
has body: I am using Celery with supervisor running the workers and Redis as the broker, and I'm having an issue with a Celery worker apparently freezing up, making it unable to process any more tasks and causing its task queue in Redis to fill up to the point of causing some memory issues. I tried setting the expires option when I called the task, thinking that this would take advantage of Redis' support for key expiry: some_task.apply_async(args=('foo',), expires=60) but this didn't work, and when I inspected the corresponding list in the Redis CLI, it just kept expanding – perhaps unsurprisingly, because it sounds like list expiry is not built-in functionality in Redis. The Celery docs say that the expiration time corresponds to time after "publishing" the task, but I couldn't find any mention of what "publishing" actually means. I had assumed it referred to adding the task to the Redis list, so either that presumption is wrong or something else is going on that I don't understand (or both). Am I wrong about task expiry time? And if so, is there any way to cause the messages to expire within Redis?
tagged with: redis

http://stackoverflow.com/comment/84966848
comment on: http://stackoverflow.com/a/48978709
score: 0
type: AnswerComment
type: Comment
has text: This was of the form I was interested in; interestingly though, this method passes *fewer* test cases than the iterator sol'n I gave.

http://stackoverflow.com/q/49040347
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python-requests
tagged with: python-responses
score: 2
has body: first time post, long time reader. I am very new to coding and just trying to teach myself using the net. I have some code in python im having trouble with and would love some help. I have 2 python scripts that basically read data from my AC unit and the second sends data to it. Here is the code to get data...(the results are just a long line of text hence the formatted data to extract particular info) #!/usr/bin/python import requests import json link = "https://actron.ninja.is/rest/v0/device/ACONNECT001EC015ABFE_0_2_4?&lt;user_access_token&gt;" f = requests.get(link) raw_data = f.text formatted_data = json.loads(raw_data) amOn = formatted_data['data']['last_data']['DA']['amOn'] tempTarget = formatted_data['data']['last_data']['DA']['tempTarget'] print (tempTarget) and the code to send data... #!/usr/bin/python import requests headers = { 'Origin': 'https://actronair.com.au', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/json', 'Accept': 'application/json', 'Referer': 'https://actronair.com.au/aconnect/', 'Connection': 'keep-alive', } params = ( ('user_access_token', '&lt;user access token&gt;'), ) data = '{"DA":{"tempTarget":24}}' response = requests.put('https://actron.ninja.is/rest/v0/device/ACONNECT001EC015ABFE_0_2_4', headers=headers, params=params, data=data) My question and what my goal is, i'd like to merge this into one python file and basically have the program read the current 'tempTarget' and then increase it by an increment of 1 in which this script will be eventually attached to a button. I am struggling with this as the data sent is a string so i'm imaging i need to convert it to say a dict and +1 the received tempTarget and then back to a string, i just cant seem to get the converting and sequencing right. Or maybe this isnt the way to do it. Your help is much appreciated.
has answer: http://stackoverflow.com/a/49040490
type: Question
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
has title: Python request get and put data in increments

http://stackoverflow.com/comment/85070734
type: Comment
comment on: http://stackoverflow.com/a/49033041
score: 1
has text: I think this is the third time now you've posted an answer seconds before I finish mine! Good work as ever. The only thing I'll add for the question asker is that there is a distinction between _global variables_ and _local variables_; just because you've said that a function takes parameters called `alpha`, `beta`, and `delta`, doesn't mean that it's going to use the global variables with the same name!
type: AnswerComment

http://stackoverflow.com/a/48973866
has body: def print_table(arr): for col in zip(*arr): print(' '.join(col))
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48973678
upvote count: 1

http://stackoverflow.com/comment/85157987
has text: "when I see these words, I know my computer will be boom"
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49076072

http://stackoverflow.com/comment/85004800
type: AnswerComment
score: 0
type: Comment
has text: Port forwarding alone isn't always enough - connecting to the public IP from within the LAN won't use the port forward, unless the router is capable of NAT loopback (and it is enabled for that forwarding rule)
comment on: http://stackoverflow.com/a/48999711

http://stackoverflow.com/q/49088038
upvote count: 1
type: Question
tagged with: mingw-w64
tagged with: anaconda
tagged with: python-3.6
has body: I am using anaconda py3.6, with conda's mingw32. I set mingw32 as the compiler, also modified cygwinccompiler.py as suggested in Building minimal cython file with python 3.3 (Anaconda) under windows 7 . Now I still can't build any binary pyd module, they all failed at the linking step with similar error. C:\ProgramData\Anaconda3\Scripts\gcc.bat -shared -s build\temp.win32-3.6\Release\cymysql\packet.o build\temp.win32-3.6\Release\cymysql\packet.cp36-win32.def -LC:\ProgramData\Anaconda3\libs -LC:\ProgramData\Anaconda3\PCbuild\win32 -lpython36 -lmsvcr140 -o build\lib.win32-3.6\cymysql\packet.cp36-win32.pyd c:/programdata/anaconda3/mingw/bin/../lib/gcc/i686-w64-mingw32/4.7.0/../../../../i686-w64-mingw32/bin/ld.exe: build\temp.win32-3.6\Release\cymysql\packet.cp36-win32.def:1: syntax error c:/programdata/anaconda3/mingw/bin/../lib/gcc/i686-w64-mingw32/4.7.0/../../../../i686-w64-mingw32/bin/ld.exe:build\temp.win32-3.6\Release\cymysql\packet.cp36-win32.def: file format not recognized; treating as linker script c:/programdata/anaconda3/mingw/bin/../lib/gcc/i686-w64-mingw32/4.7.0/../../../../i686-w64-mingw32/bin/ld.exe:build\temp.win32-3.6\Release\cymysql\packet.cp36-win32.def:1: syntax error collect2.exe: error: ld returned 1 exit status error: command 'C:\\ProgramData\\Anaconda3\\Scripts\\gcc.bat' failed with exit status 1 another example: (base) D:\pymssql-build\pymssql&gt;gcc -shared -s build\temp.win32-3.6\Release\_mssql.o build\temp.win32-3.6\Release\_mssql.cp36-win32.def -LC:\ProgramData\Anaconda3\Library\mingw-w64\lib -LC:\ProgramData\Anaconda3\Library\lib -LD:\pymssql-build\pymssql\freetds\ming_32\lib-nossl -LC:\ProgramData\Anaconda3\libs -LC:\ProgramData\Anaconda3\PCbuild\win32 -llibiconv -liconv -lsybdb -lws2_32 -lwsock32 -lkernel32 -lpython36 -lmsvcr140 -o build\lib.win32-3.6\_mssql.cp36-win32.pyd c:/programdata/anaconda3/mingw/bin/../lib/gcc/i686-w64-mingw32/4.7.0/../../../../i686-w64-mingw32/bin/ld.exe: build\temp.win32-3.6\Release\_mssql.cp36-win32.def:1: synt…
downvote count: 0
linked to: http://stackoverflow.com/q/24291506
has title: pyd modules build failed with ld.exe complaining [def_file].def:1: syntax error
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: build
answer count: 0
score: 1

http://stackoverflow.com/comment/85200548
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49097658
has text: replace the O item with the X or O i guess!
score: 0

http://stackoverflow.com/comment/84938299
type: Comment
comment on: http://stackoverflow.com/q/48966135
type: QuestionComment
has text: Which version of Python? Which bitness? Which version of ibm_db, and ibm_db_dbi ? Also what is the encoding of your target Db2 database?
score: 0

http://stackoverflow.com/comment/85232365
comment on: http://stackoverflow.com/q/49113289
score: 0
type: QuestionComment
type: Comment
has text: @Olivier Ah, nice, I appreciate it.

ash
tags question: http://stackoverflow.com/q/49090469
type: Tag
tag name: ash

http://stackoverflow.com/q/49047909
accepted answer: http://stackoverflow.com/a/49048310
has body: So I want to calculate the distance from the two furthest points in a cuboid. The mathematical equation for this is z^2 = a^2 + b^2 + c^2 but when I do that it doesn't return correctly. from math import * dimension = input("What dimension: ") if dimension == ("3D") or dimension == ("3d") or dimension == ("3"): a = int(input("a = ")) b = int(input("b = ")) c = (sqrt((a**2) + (b**2))) z = (sqrt((a**2) + (b**2) + (c))) rounded_z = round(z, 4) print(rounded_z,'cm') else: a = int(input("a = ")) b = int(input("b = ")) c = (sqrt((a**2) + (b**2))) rounded_c = round(c, 2) print(rounded_c,'cm') For example: if a = 6 and b = 2 It should be 7 cm Source. But it returns 6.8062!! Why? please help.
tagged with: math
has comment: http://stackoverflow.com/comment/85112523
answer count: 2
favorite count: 0
has title: 3D Pythagoras program not returning correct results
tagged with: algebra
has answer: http://stackoverflow.com/a/49048310
possible better answer: http://stackoverflow.com/a/49048648
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/49048648
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85100774
downvote count: 3
tagged with: pythagorean
upvote count: 1
has comment: http://stackoverflow.com/comment/85100308
type: Question

http://stackoverflow.com/comment/84966111
type: Comment
has text: Thank you so much for helping me. In the end there was quite a simple solution. I simply uninstalled pygame and indtalled it again... And now it works.
type: AnswerComment
comment on: http://stackoverflow.com/a/48980219
score: 0

http://stackoverflow.com/comment/85124060
type: QuestionComment
score: 0
has text: As the error message says, `product` is `None`. `soup.find_all()` returns `None` when it doesn't find any matching elements, so that is probably the problem. A simple `print(product)` will suffice to test this hypothesis.
type: Comment
comment on: http://stackoverflow.com/q/49059489

http://stackoverflow.com/a/49120841
downvote count: 0
has comment: http://stackoverflow.com/comment/85247136
accepted answer of: http://stackoverflow.com/q/49120813
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/85247324
answers question: http://stackoverflow.com/q/49120813
score: 2
has body: pet.name is your method pet.name() is a call to your method So here, you need to add parenthesis to call your name method: &gt;&gt;&gt; pet = Dog("Boby", 45) &gt;&gt;&gt; print(pet.name()) # Parentheses after pet.name Boby
has comment: http://stackoverflow.com/comment/85247288
has comment: http://stackoverflow.com/comment/85247159
type: AcceptedAnswer

http://stackoverflow.com/comment/96110491
comment on: http://stackoverflow.com/a/54658502
type: AnswerComment
score: 0
has text: x264 is an encoder. H.264 is the format. Using `-vcodec mpeg4` creates an outdated format: MPEG-4 Part 2 video.
type: Comment

http://stackoverflow.com/comment/85226157
type: Comment
has text: Interesting. I'll probably use this for my current algorithm version where the range is constant. But in a future version, the range (i.e. the cercle radius, will be in % of f1 and f2). For instance `a in range(-10% of f1, +10% of f1)` and `b in range(-5% of f2, +5% of f2)`. We agree that your solution can't be adapted for this scenario since it's no longer possible to compute the radius (offsets) beforehand? (Or you got an other idea ? ^^)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49110088

http://stackoverflow.com/comment/85160227
score: 0
comment on: http://stackoverflow.com/q/49074194
type: Comment
type: QuestionComment
has text: The code work except for adding @jit(nopython=True) for the two functions mentioned

http://stackoverflow.com/a/49060808
score: 2
downvote count: 0
upvote count: 2
has body: This is one way with Pandas if you can get it working: df = pd.DataFrame(data).sort_values(0).drop_duplicates([1, 2, 4]).values Result [[0 1 1 'b' 1] [0 3 1 'c' 4]] Explanation Your problem can be reduced to: Sort by column 0, ascending=True is the default. Remove duplicate rows by columns [1, 2, 4]. pd.DataFrame.values extracts the underlying numpy array.
answers question: http://stackoverflow.com/q/49060645
type: Answer
has comment: http://stackoverflow.com/comment/85126820

http://stackoverflow.com/a/49107092
type: Answer
has body: I think what you need is yield_per() function, so you do not have to process all the results at one time, but separate them in chunks. In this way you can save more memory. You can read more about this function at this link. However, take note that yield_per() may ignore some of your query rows, and the answer in this question provides a detailed explanation. If you think you do not want to use yield_per() after reading, you may refer to all the answers posted on this stackoverflow question as well. Another tips for you in processing large size of list is to use yield, so you do not have to load all the entries in memory at once, but process them one by one. Hope it helps.
has comment: http://stackoverflow.com/comment/85262214
accepted answer of: http://stackoverflow.com/q/49106472
answers question: http://stackoverflow.com/q/49106472
has comment: http://stackoverflow.com/comment/85256227
has comment: http://stackoverflow.com/comment/85257881
score: 0
has comment: http://stackoverflow.com/comment/85255846
has comment: http://stackoverflow.com/comment/85256553
type: AcceptedAnswer

http://stackoverflow.com/q/49066983
tagged with: python
has title: python flask_restless with sqlalchemy doesn't generate api endpoints and gives "has no attribute extensions" error using blueprints
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: flask-restless
has answer: http://stackoverflow.com/a/51179231
accepted answer: http://stackoverflow.com/a/51179231
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/85148208
type: Question
tagged with: flask
upvote count: 3
has body: for my webapp I want to automatically generate a REST API. I read the of flask_restless docs, tried several tutorials and did everything as described: my routes are to be located in module app.main.api.pv_tool.py from . import api from app.__init__ import db, app from app.models import University import flask_restless manager = flask_restless.APIManager(app, session=db.scoped_session) manager.create_api(University, methods=['GET']) @api.route('/') def index(): return 'asdf' where University is defined in models.py from sqlalchemy import String, Integer from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() ... class University(Base): __tablename__ = 'unis' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(64), nullable=False, unique=True) def __repr__(self): return '&lt;Uni %r&gt;' % self.name ... and the connection to the existing and filled database is established in database.py: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from app.models import Base class Database: path = 'sqlite:///pv_tool.sqlite' engine = None session = None scoped_session = None def __init__(self, path=path): self.engine = create_engine(path, convert_unicode=True) Base.metadata.bind = self.engine db_session = sessionmaker(bind=self.engine, autocommit=False) db_session.bind = self.engine self.session = db_session() self.scoped_session = scoped_session(self.session) Base.metadata.create_all() Now in my browser or using requests library module I get 'asdf' response on http://localhost:5000. However, I cannot reach my University data trying everything like: localhost:5000/unis, localhost:5000/api/unis and so on. I always get a 404 response. Without any errors this issue is hard to pursue. Does anybody have an idea how I could debug this in general and what my error in the code might be? In PyCharm Debugger the manager object seems to have some API to create: But I have no idea what I could loo…
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85125173
type: Comment
has text: Thank you but this does not work unfortunately. Nothing is replaced in the arrays.
comment on: http://stackoverflow.com/a/49059974
score: 0
type: AnswerComment

http://stackoverflow.com/a/49077985
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49077911
has body: You can try this: df = pd.DataFrame({'col1':['place0-place01','place1-place01-place11']}) df['col2'] = df.col1.str.split('-').str.get(0) # output col1 col2 0 place0-place01 place0 1 place1-place01-place11 place1

http://stackoverflow.com/comment/87593048
type: Comment
has text: how to do this?
comment on: http://stackoverflow.com/a/48969238
score: 0
type: AnswerComment

http://stackoverflow.com/a/49083506
type: Answer
answers question: http://stackoverflow.com/q/49083385
has body: I am not running Windows but under Linux when you downloaded the tar.gz file you would have to extract it and then run python setup.py install in the extracted directory not pip (assuming there is a setup.py file there of course)
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49083385

http://stackoverflow.com/a/48975540
has comment: http://stackoverflow.com/comment/84956227
answers question: http://stackoverflow.com/q/48975419
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48975419
has comment: http://stackoverflow.com/comment/84956181
type: Answer
has body: The easiest way would probably be to have a generator with a configurable step. from datetime import date, timedelta def days(start, end, step=timedelta(days=1)): curr = start while curr &lt;= end: yield curr curr += step print(list(days(date(2017, 1, 1), date(2017, 1, 3)))) # [datetime.date(2017, 1, 1), datetime.date(2017, 1, 2), datetime.date(2017, 1, 3)]

http://stackoverflow.com/q/49073547
has comment: http://stackoverflow.com/comment/85154490
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/49073607
downvote count: 3
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: dataframe
has body: I have 3 columns of data. I have data stored in three columns (k, v, t) in csv. For instance, Data: k v t a 1 2 b 2 3 c 3 4 a 2 3 b 3 2 b 3 4 c 3 5 b 2 3 I want to get as the following data. Basically, sum all the values of t that has the same k and v. a 1 5 b 2 6 b 3 6 c 3 9 this is the code I have so far: aList = [] aList2 = [] aList3 = [] for i in range(len(data)): if data['k'][i] == 'a': if data['v'][i] == 1: aList.append(data['t'][i]) elif data['v'][i] == 2: aList2.append(data['t'][i]) else: aList3.append(data['t'][i]) and it keeps going until the end. I use "for loop" and "if" but it is too long. Can I use numpy in a short and clean way? or any other better way?
accepted answer: http://stackoverflow.com/a/49073607
has comment: http://stackoverflow.com/comment/85153082
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has title: Sum values in third column while putting together corespondinng values in first and second columns
has comment: http://stackoverflow.com/comment/85154446
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/49079911
has comment: http://stackoverflow.com/comment/85165665
upvote count: 1
has body: Store them in a dictionary: grades = {'algebra': 57, 'geometry': 82, 'physics': 68} for subject in grades: if grades[subject] &lt; 70: print('Your {} could be better'.format(subject)) which can be condensed into a list comprehension using dict.items() in a single line! [print("Your {} could be better".format(subject)) for subject, grade in grades.items() if grade &lt; 70] or for multiple subjects in the same sentence: grades = {'algebra': 57, 'geometry': 82, 'physics': 68} subjects = ' and '.join([subject for subject, grade in grades.items() if grade &lt; 70])) print('Your {} could be better'.format(subjects))
accepted answer of: http://stackoverflow.com/q/49079877
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85165763
answers question: http://stackoverflow.com/q/49079877
has comment: http://stackoverflow.com/comment/85166027
type: Answer
score: 1

http://stackoverflow.com/a/48987929
answers question: http://stackoverflow.com/q/48987882
type: Answer
accepted answer of: http://stackoverflow.com/q/48987882
has body: 'some2' has list as value. You can either iterate over it or use index to access the value. EX: parsedjson = {"some":"data","some2":[{"some3":"data3","some4":{"some5":"data5","some6":{ "some7":"data7","some8":{"some9":"data9","somedata":[0,100,200,300,400]}}}}]} print parsedjson['some2'][0]['some4']['some6']['some8']['somedata'] #Using index 0 Output: [0, 100, 200, 300, 400]
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84980839

http://stackoverflow.com/comment/85069201
score: 0
type: Comment
has text: thank you so much it really boosted me now i going to study this json_normalize and how to use it. its very helpful :) :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49026547

http://stackoverflow.com/comment/85018232
type: QuestionComment
score: 0
has text: @jdehesa I read it from https://python-forum.io/Thread-Basic-Never-use-for-i-in-range-len-sequence
comment on: http://stackoverflow.com/q/49006614
type: Comment

http://stackoverflow.com/comment/85222802
comment on: http://stackoverflow.com/a/49108867
type: Comment
has text: No, thats not gonna work. I want it fully automated. Thanks
score: 0
type: AnswerComment

http://stackoverflow.com/comment/112053615
has text: Please don't post code only answers without a textual explanation.
type: Comment
score: 4
comment on: http://stackoverflow.com/a/63356780
type: AnswerComment

http://stackoverflow.com/q/49021333
has answer: http://stackoverflow.com/a/49021480
upvote count: 1
type: Question
has body: Am generating a text file using python script like below (1,2,3)(4,5,6) If I need to split this to 2 lines with delimiter, how can i do that. I need the text file to be like (1,2,3) (4,5,6) Thanks
score: -1
has title: Writing to new text file after splitting delimiters in python
answer count: 2
has answer: http://stackoverflow.com/a/49021472
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85048094
downvote count: 2

http://stackoverflow.com/q/48976184
favorite count: 0
has comment: http://stackoverflow.com/comment/84957488
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84957457
score: 1
has body: I am trying to remove and correct the file with reindent module in python 2.7 on windows machine. from windows command line when I try to use the following solution it gives me and error. Installing reindent python Erros is; "reindent is not recognized as an internal or external command,operable program or batch file." when i checked to install with pip install reindent, it says; Requirement already satisfied: reindent in c:\python27\lib\site-packages. indentation has been the a big issue for a newbie like me in my journey to learning python.
type: Question
has comment: http://stackoverflow.com/comment/84957331
has comment: http://stackoverflow.com/comment/84957487
tagged with: indentation
upvote count: 1
has title: reindent.py usage for newbie
linked to: http://stackoverflow.com/q/12132481
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84958486
has comment: http://stackoverflow.com/comment/84958664
tagged with: python

libvirt
tag name: libvirt
tags question: http://stackoverflow.com/q/49012747
type: Tag
tags question: http://stackoverflow.com/q/48988584

http://stackoverflow.com/comment/85223211
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49108742
has text: Something I noticed just now: if I execute the code in the IDE without the app part, like @Laszlowaty said, it works from the shell. If I leave the app beginning in, then it works from the IDE but not the shell....
type: QuestionComment

http://stackoverflow.com/a/49024849
has comment: http://stackoverflow.com/comment/85054612
has body: Make your print statement like this: print(user,';',num_followers) So that it prints ';' as separator for values. Then pipe the output to a file: python yourscript.py &gt; yourcsv.csv
answers question: http://stackoverflow.com/q/49024296
has comment: http://stackoverflow.com/comment/85054496
score: 0
has comment: http://stackoverflow.com/comment/85059908
has comment: http://stackoverflow.com/comment/85054730
type: Answer

http://stackoverflow.com/a/49034777
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49034670
score: 1
answers question: http://stackoverflow.com/q/49034670
has body: Use a lookbehind and lookahead; these just look without being modified by the replacement text: text7 = re.sub(r'(?&lt;=\w)"(?=\w)', "'", text6)

http://stackoverflow.com/q/49106310
answer count: 1
linked to: http://stackoverflow.com/q/3687682
has comment: http://stackoverflow.com/comment/85217641
has body: I trying to create functions by gitting functions names from giving dictionary, actually, I'm not sure if this is possible, her is what I'm trying to do: def functions_factory(my_dict): for the name in my_dict: create_function(name) def create_function(function_name): x=0 # **code implentation:** here should write a code that can create function with name = &lt;function_name&gt;
has comment: http://stackoverflow.com/comment/85217837
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85256758
type: UnansweredQuestion
downvote count: 2
has title: Python : Create functions by gitting names from dictionary
has comment: http://stackoverflow.com/comment/85217685
type: Question
has answer: http://stackoverflow.com/a/49107923
upvote count: 0
score: -2

http://stackoverflow.com/comment/85110746
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48978463
has text: Yes i've got:) sorry for misleading, take a look on update 3 it`s much simpler than it was.

http://stackoverflow.com/a/48994359
accepted answer of: http://stackoverflow.com/q/48992929
type: AcceptedAnswer
type: Answer
has body: You can do all the work in a one-liner, but it takes a bit of setup. This takes advantage of the fact that you basically want all the binary numbers within a range of 0 to 2**n, except if their leftmost bits represent a particular binary number. Note that in general you will be keeping most of the numbers in the range (all but 1/2**len(word)), so it's reasonably efficient just to generate all the numbers and then filter out the ones you don't want. word = '00' word_int = int(word, base=2) m = len(word) n = 3 results = ['{0:b}'.format(num).zfill(n) for num in range(2**n) if num &gt;&gt; (n-m) != word_int] print('\n'.join(results)) # 010 # 011 # 100 # 101 # 110 # 111 You can eliminate some of the setup, but the one-liner gets harder to read: word = '00' n = 3 [ num for num in ('{0:b}'.format(p).zfill(n) for p in range(2**n)) if not num.startswith(word) ] Or you can use itertools.product word = '00' n = 3 [ num for num in (''.join(p) for p in itertools.product('01', repeat=n)) if not num.startswith(word) ]
answers question: http://stackoverflow.com/q/48992929
score: 0

http://stackoverflow.com/comment/84958868
comment on: http://stackoverflow.com/q/48975975
score: 0
type: Comment
type: QuestionComment
has text: Downvotes? Why? Is it too simple or what?

http://stackoverflow.com/q/49021810
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Find intersection of two sets of columns in python pandas dataframe for each row without looping
has answer: http://stackoverflow.com/a/49022060
tagged with: python
has body: I have a following pandas.DataFrame: df = pd.DataFrame({'A1':['a','a','d'], 'A2':['b','c','c'], 'B1':['d','a','c'], 'B2': ['e','d','e']}) A1 A2 B1 B2 0 a b d e 1 a c a d 2 d c c e I would like to choose the rows in which values in A1 and A2 are different from B1 and B2, or intersection of values in ['A1', 'A2'] and ['B1', 'B2'] is empty, so in the above example only the row 0 should be chosen. So far the best I could do is to loop over every row of my data frame with the following code for i in df.index.values: if df.loc[i,['A1','A2']].isin(df.loc[i,['B1','B2']]).sum()&gt;0: df = df.drop(i,0) Is there a way to do this without looping?
score: 2
type: UnansweredQuestion
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/49022689
upvote count: 2
has answer: http://stackoverflow.com/a/49021928

http://stackoverflow.com/comment/85061728
type: AnswerComment
comment on: http://stackoverflow.com/a/49028483
score: 0
has text: @Ninjasoup - be free get my sample DataFrame, add new column and create expected output.
type: Comment

http://stackoverflow.com/comment/84971333
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48982700
score: 0
has text: Sorry @jezrael, I was editing the question. An example output is shown. As stated in the question I'm struggling to describe it. I'm hoping to find the "incremental mean" if that makes sense. So `3` index would be in the middle of `2` and `4`. `5`,`6`,`7` would be split evenly between `4` and `8`. So in increments of 0.51913125. If there were 6 `nan's` between `4` and `8` that average increment would be smaller.

http://stackoverflow.com/a/54916562
accepted answer of: http://stackoverflow.com/q/49058396
upvote count: 2
answers question: http://stackoverflow.com/q/49058396
type: AcceptedAnswer
type: Answer
has body: You could perhaps make your program accept a variable number of positional arguments (between 0 and 2) which would be added to a positional parameters list (with action="append"), and also call add_argument("-i",...) and add_argument("-o",...) to handle the flag equivalents. Typically, argparse options fall either in the positional or optional category (but not both). So, you'll need to pass settings to argparse that allow some redundancy, and deal with conflicts after parsing. For instance, you can configure argparse to accept an input file both via -i INPUT and as positional INPUT, but then you add a custom check after parsing to make sure only one of the two forms was used. Pseudocode: parser.add_argument('infile', metavar="INFILE", nargs='?', type=argparse.FileType('r'), action='append', dest="positional_args") parser.add_argument('outfile', metavar="OUTFILE", nargs='?', type=argparse.FileType('w'), action='append', dest="positional_args") parser.add_argument('-i', metavar="INFILE", dest="infile", default=None) parser.add_argument('-o', metavar="OUTFILE", dest="outfile", default=None) args = parser.parse_args([....]) # here insert check for conflicts between len(args.positional_args) and -i and -o # example: if sum([len(args.positional_args), args.infile is not None, args.outfile is not None]) != 2: parser.print_help() sys.exit(1) ... infile = args.infile or args.positional_args.pop(0) outfile = args.outfile or args.positional_args.pop(0)
score: 2
downvote count: 0

http://stackoverflow.com/comment/84985479
type: Comment
type: QuestionComment
has text: going through the documentation of appJar, could be the `ChangeFunction` event (http://appjar.info/pythonEvents/#types-of-event) key to directly printing the value?
comment on: http://stackoverflow.com/q/48986533
score: 0

http://stackoverflow.com/a/48994957
type: Answer
score: 1
upvote count: 1
has body: Slice out both and take the last item. seq[0:2][-1]
answers question: http://stackoverflow.com/q/48994941
downvote count: 0

http://stackoverflow.com/comment/85227982
type: QuestionComment
type: Comment
has text: The point (0.5, 0) has 4 neighbors, but some of them are "within" the red area. But this point should bot be removed..
score: 0
comment on: http://stackoverflow.com/q/49111258

http://stackoverflow.com/q/49099956
has title: Reading color indexed .tiff file with Python OpenCV
answer count: 1
favorite count: 0
upvote count: 3
tagged with: python
downvote count: 0
type: UnansweredQuestion
type: Question
tagged with: tiff
tagged with: opencv
score: 3
has answer: http://stackoverflow.com/a/49781267
has body: I have .tiff files containing color-indexed images, i.e. the image itself (1024x1024) contains an index per pixel (in my case 0, 1) and within the tiff file is a colormap (256x3) that maps these codes to colors code R G B _________________ 0 = 0 0 0 1 = 140 215 115 2 = 255 255 255 ... (other codes are irrelevant for me) I want to read the indexed image with Python. I'm using OpenCV and following the docs I tried this (not using the -1 flag gives an RGB image): img = cv2.imread(file, cv2.IMREAD_UNCHANGED) # cv2.IMREAD_UNCHANGED = -1 I would expect the unchanged indexed-color image, i.e. an image 1024x1024 containing values 0 or 1. However I'm getting an 1024x1024 image with values 0 or 181. I'm puzzled where the 181 is coming from (not an average of the corresponding color value; (140 + 215 + 115) / 3 = 157), also I don't want to manually change these values. Is there a way to read color indexed tiff-files with Python OpenCV (or if need be other libs) to [a] get the index-image and (optional) [b] even get the color map? An example file is here. Reading this data with MATLAB works as expected: img = imread(file); % returns img: (1024, 1024) with values [0, 1] [img, cmap] = imread(file); % returns img: (1024, 1024) with values [0, 1], cmap (256x3)

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

http://stackoverflow.com/comment/85008187
type: Comment
comment on: http://stackoverflow.com/a/49001222
has text: No it's not working either :( Same as earlier response send and response contains Exception details as earlier.
type: AnswerComment
score: 0

http://stackoverflow.com/a/49002273
answers question: http://stackoverflow.com/q/49002224
upvote count: 5
type: Answer
has body: &gt;&gt;&gt; from itertools import product ... ... list1 = ['EXCHANGE_US_M', '1021,2360', '1256,14536,5429', 'AED589L', 'DOL895'] ... ... for i, p in enumerate(product(*[elem.split(',') for elem in list1])): ... print(('{}/{}'.format(p[0], i), *p[1:])) ... ('EXCHANGE_US_M/0', '1021', '1256', 'AED589L', 'DOL895') ('EXCHANGE_US_M/1', '1021', '14536', 'AED589L', 'DOL895') ('EXCHANGE_US_M/2', '1021', '5429', 'AED589L', 'DOL895') ('EXCHANGE_US_M/3', '2360', '1256', 'AED589L', 'DOL895') ('EXCHANGE_US_M/4', '2360', '14536', 'AED589L', 'DOL895') ('EXCHANGE_US_M/5', '2360', '5429', 'AED589L', 'DOL895')
downvote count: 0
score: 5

http://stackoverflow.com/comment/85009153
type: QuestionComment
has text: What have you tried so far? Have you seen https://docs.python.org/3/library/itertools.html#itertools.permutations ?
score: 0
comment on: http://stackoverflow.com/q/49002224
type: Comment

http://stackoverflow.com/q/49047674
has answer: http://stackoverflow.com/a/49070937
tagged with: apache
accepted answer: http://stackoverflow.com/a/49070937
tagged with: apache2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85118636
downvote count: 0
score: 1
has title: Android HTTP: get out of infinite while loop with sending requests to Apache server
favorite count: 0
type: Question
tagged with: android
upvote count: 1
tagged with: python
has body: this is a schema of my project: 1) Android app -> 2) Apache server on RPi -> 3) Python scripts that control -> 4) my device 1) Android app - 2 simple switches, each one sends different request to Apache on RPi: public class MainActivity extends Activity{ private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Switch switch_auto = findViewById(R.id.switch_auto); Switch switch_manual = findViewById(R.id.switch_manual); switch_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { new Background_get().execute("led1=1"); } else { new Background_get().execute("led1=0"); } } }); switch_manual.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { Log.d(TAG, "onCheckedChanged: SET TO TRUE"); new Background_get().execute("led2=1"); Log.d(TAG, "onCheckedChanged: EXIT"); } else { Log.d(TAG, "onCheckedChanged: SET TO FALSE"); new Background_get().execute("led2=0"); Log.d(TAG, "onCheckedChanged: EXIT"); } } }); } private class Background_get extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { try { URL url = new URL("http://192.168.0.248/?" + params[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder result = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) result.append(inputLine).append("\n"); in.close(); connection.disconnect(); return result.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } } } 2) Apache server on RPi - very simple PHP code: if it was "led1=1", launch Pyt…
answer count: 1

http://stackoverflow.com/comment/85076797
has text: This won't cause any problems with Python. Python is a memory-managed language, here, reference-counting will take care of reclaiming the objects.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49035783
type: Comment

http://stackoverflow.com/q/49025162
accepted answer: http://stackoverflow.com/a/49025597
downvote count: 0
has title: Is pandas showing the wrong percentile?
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49025608
has body: I'm working with this WNBA dataset here. I'm analyzing the Height variable, and below is a table showing frequency, cumulative percentage, and cumulative frequency for each height value recorded: From the table I can easily conclude that the first quartile (the 25th percentile) cannot be larger than 175. However, when I use Series.describe(), I'm told that the 25th percentile is 176.5. Why is that so? wnba.Height.describe() count 143.000000 mean 184.566434 std 8.685068 min 165.000000 25% 176.500000 50% 185.000000 75% 191.000000 max 206.000000 Name: Height, dtype: float64
has comment: http://stackoverflow.com/comment/85056797
has answer: http://stackoverflow.com/a/49025608
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49025713
has answer: http://stackoverflow.com/a/49025597
type: Question
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/39567712
tagged with: statistics
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/85158584
type: Comment
has text: Excellent. Helps a lot. Thank you.
score: 0
comment on: http://stackoverflow.com/a/49076263
type: AnswerComment

http://stackoverflow.com/comment/84935648
type: Comment
comment on: http://stackoverflow.com/a/48964498
has text: I think it is another way, not sure if worse readable or not ;)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85105128
type: QuestionComment
comment on: http://stackoverflow.com/q/49050397
score: 5
has text: what do you think that error means?
type: Comment

http://stackoverflow.com/q/49118890
favorite count: 0
has title: Solve a system of odes with scipy - how to reference different indexes?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85246141
tagged with: python
tagged with: differential-equations
answer count: 1
tagged with: scipy
has body: I have a system of ODEs that depend on a matrix of data. Each ODE should reference a different column of data in its evaluation. import numpy as np n_eqns = 20 coeffs = np.random.normal(0, 1, (n_eqns, 20)) def dfdt(_, f, idx): return (f ** 2) * coeffs[idx, :].sum() - 2 * f * coeffs.sum() from scipy.integrate import ode f0 = np.random.uniform(-1, 1, n_eqns) t0 = 0 tf = 1 dt = 0.001 r = ode(dfdt) r.set_initial_value(f0, t0).set_f_params(range(n_eqns)) while r.successful() and r.t &lt; tf: print(r.t+dt, r.integrate(r.t+dt)) How can I specify that each ODE should use the idx value associated with its index in the system of ODEs? The first equation should be passed idx=0, the second idx=1, and so on.
has comment: http://stackoverflow.com/comment/85246530
has answer: http://stackoverflow.com/a/49121084
accepted answer: http://stackoverflow.com/a/49121084
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/q/48981501
tagged with: python
tagged with: python-decorators
downvote count: 0
score: 21
tagged with: vectorization
has comment: http://stackoverflow.com/comment/84968892
type: Question
has answer: http://stackoverflow.com/a/48981622
has title: Is it possible to numpy.vectorize an instance method?
has answer: http://stackoverflow.com/a/48982079
has answer: http://stackoverflow.com/a/55353392
has comment: http://stackoverflow.com/comment/84970596
has answer: http://stackoverflow.com/a/50306525
has comment: http://stackoverflow.com/comment/84968368
tagged with: numpy
upvote count: 21
has answer: http://stackoverflow.com/a/50556493
has body: I've found that the numpy.vectorize allows one to convert 'ordinary' functions which expect a single number as input to a function which can also convert a list of inputs into a list in which the function has been mapped to each input. For example, the following tests pass: import numpy as np import pytest @np.vectorize def f(x): if x == 0: return 1 else: return 2 def test_1(): assert list(f([0, 1, 2])) == [1, 2, 2] def test_2(): assert f(0) == 1 if __name__ == "__main__": pytest.main([__file__]) However, I've not been able to get this to work for an instance method which makes use of an instance attribute. For example: class Dummy(object): def __init__(self, val=1): self.val = val @np.vectorize def f(self, x): if x == 0: return self.val else: return 2 def test_3(): assert list(Dummy().f([0, 1, 2])) == [1, 2, 2] This test fails: =================================== FAILURES =================================== ____________________________________ test_3 ____________________________________ def test_3(): &gt; assert list(Dummy().f([0, 1, 2])) == [1, 2, 2] test_numpy_vectorize.py:31: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/lib/function_base.py:2739: in __call__ return self._vectorize_call(func=func, args=vargs) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/lib/function_base.py:2809: in _vectorize_call ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = &lt;numpy.lib.function_base.vectorize object at 0x106546470&gt; func = &lt;function Dummy.f at 0x10653a2f0&gt;, args = [array([0, 1, 2])] def _get_ufunc_and_otypes(self, func, args): """Return (ufunc, otypes).""" # frompyfunc will fail if args is empty if not args: raise ValueError('args can not be empty') if self.otypes is not None: otypes = self.otypes nout = len…
favorite count: 0
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/q/48992001
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48992121
tagged with: python
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48992121
type: AnsweredQuestion
has title: Calculation using value from rows with matching identifier value in pandas dataframe
type: Question
tagged with: time-series
has body: I have a very large dataframe with loads of users and associated events and times. I'd like to add a new column with the time delta for each user from a specific type of event of interest that occurs once for each user. Example start data: UserID | Event | DateTime 1 | Interest | 12:00 2 | Other | 12:01 1 | Other | 12:02 2 | Interest | 12:03 2 | Other | 12:04 Basic example of what I'm looking for: UserID | Event | DateTime | TimeDelta 1 | Interest | 12:00 | 0:00 2 | Other | 12:01 | -0:02 1 | Other | 12:02 | 0:02 2 | Interest | 12:03 | 0:00 2 | Other | 12:04 | 0:01 I have an iterative solution below, but I'm aware that iteration tends not to be the optimal way to work with dataframes and my solution doesn't scale to the larger datasets I'm working with. Is there a more "pandas" way to do this: for uid in list_of_uids: event_of_interest_time = df['DateTime'][(df['UserId']==uid) &amp; (df['Event']=='Interest')] df.loc[df['UserId'] == uid, 'TimeDelta'] = df.loc[df['UserId'] == uid, 'DateTime'] - event_of_interest_time.values[0]

http://stackoverflow.com/a/49045510
has comment: http://stackoverflow.com/comment/85096780
has body: If your distribution is symmetrical (which is the case of the normal distribution), then the theoretical median, has the same value as the average. Otherwise, the median probability, is the one corresponding with 0.5 in CDF distribution.
answers question: http://stackoverflow.com/q/49045372
has comment: http://stackoverflow.com/comment/85125146
score: 0
type: Answer

http://stackoverflow.com/comment/130231298
comment on: http://stackoverflow.com/a/49736941
score: 0
type: AnswerComment
type: Comment
has text: @TonyMontana: are you getting a pickle-related error with `ppft` (`ParallelPool`) or `multiprocess` (`ProcessPool`)? It should not happen from the former. There are many reasons that an object can be unpicklable, you should open a ticket on GitHub and address this (as opposed to in the comments here).

http://stackoverflow.com/a/49103330
has body: I think it might be because of the file mode being rb instead of r but it's really a guess until you post the actual ascii_art.txt: with open('ascii_art.txt', 'r') as f: for line in f: print(line.rstrip())
has comment: http://stackoverflow.com/comment/85334074
accepted answer of: http://stackoverflow.com/q/49103277
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49103277
type: Answer

http://stackoverflow.com/a/49035363
type: Answer
has comment: http://stackoverflow.com/comment/85090165
score: 1
upvote count: 1
has body: One option is to use lambda or functools.partial and pass the instance of the boton as argument. Instead of setting the callback when the button is instantiated (the reference does not yet exist) you can use the config method. On the other hand you can use an instance attribute to store the references of the selectable buttons (self._step_buttons in the code below, a list) and another attribute that stores the reference of the selected button (self._step_selected in the code below). The code could look like this: import tkinter as tk from functools import partial class Popup2(tk.Toplevel): def __init__(self, master=None): super().__init__(master) self.master = master self.geometry("300x300") self.title("Secondary") self.entry_input = tk.StringVar() tk.Label(self, text="Your input").pack() tk.Entry(self, textvariable=self.entry_input).pack() tk.Button(self, text="Submit", command=self.evaluation, bg="pink").pack() def evaluation(self): input_value = self.entry_input.get() self.master.add_step(input_value) self.destroy() class Ldo(tk.Frame): def __init__(self, master=None): super().__init__(master) self._step_buttons = [] self._step_selected = None self.grid() self.app_outline() def app_outline(self): self.masterframe1 = tk.Frame(self.master, width=300, height=300) self.masterframe1.grid(sticky=tk.N, padx=20) self.masterframe2 = tk.Frame(self.master, width=300, height=100) self.masterframe2.grid(sticky=tk.S, padx=20) self.addtabbutton = tk.Button(self.masterframe2, text="Add Step", width=10, command=self.open_popup, bg="sienna1") self.addtabbutton.grid(row=0, column=0, sticky=tk.EW) self.runallbutton = tk.Button(self.masterframe2, text="Run All", width=10, command=self.process_all, bg="sienna1", state=tk.DISABLED) self.runallbutton.grid(row=0, column=1, sticky=tk.EW) self.runselbutton = tk.Button(self.masterframe2, text="Run Selected", width=10, command=self.process_selected, bg="sienna1", state=tk.DISABLED) self.runselbutton.grid(row=0, column=2, sticky=tk.EW) def op…
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49032298
accepted answer of: http://stackoverflow.com/q/49032298

http://stackoverflow.com/q/49034083
has answer: http://stackoverflow.com/a/49034180
favorite count: 0
type: UnansweredQuestion
has title: Find a specific pattern in a string using regex
tagged with: python
tagged with: regex
tagged with: http://stackoverflow.com/tag/json
has body: RT @Complex: 'Atlanta' Season 2 director: "If the first season is College Dropout, this one is Late Registration." @pastorjnelson Pastor JN, I have spoken to you before. But, lol, you didnt know who I was. Or maybe, I didnt know2026 Suppose I have two strings shown above. I want to fetch a specific string pattern from a given line @____ using Python regex. How can I do that? The expected output should be @Complex for the first string and @pastorjnelson for the second string.
downvote count: 1
type: Question
answer count: 2
upvote count: 0
linked to: http://stackoverflow.com/q/2304632
has comment: http://stackoverflow.com/comment/85072907
score: -1
duplicate of: http://stackoverflow.com/q/2304632
has answer: http://stackoverflow.com/a/49034153

http://stackoverflow.com/comment/85247025
type: AnswerComment
score: 0
type: Comment
has text: would you write me a new answer and imagine this line : " <bound method NDFrame.head of ID VegType Elevation C N C/N Soil13C Soil15N pH \ " would be on the top of the list?
comment on: http://stackoverflow.com/a/49119949

http://stackoverflow.com/a/77809728
answers question: http://stackoverflow.com/q/49121154
has body: The algorithm in the question refers to an old version of Hoare partition scheme, which changed over time. By changing the inner loops to break on elements equal to pivot (left scan loops on &lt; instead of &lt;=, right scan loops on &gt; instead of &gt;=), the need for sentinel elements or bounds checking was eliminated. Look at the history and Hoare partition scheme sections in the Wikipedia article: https://en.wikipedia.org/wiki/Quicksort
score: 0
type: Answer

http://stackoverflow.com/comment/85050730
type: AnswerComment
score: 0
type: Comment
has text: @want That's probably because the normal ASCII characters can only be represented one way. Those Chinese characters, however, can be represented as one symbol or as a sum of different modifiers.
comment on: http://stackoverflow.com/a/49010083

http://stackoverflow.com/comment/85141319
type: Comment
comment on: http://stackoverflow.com/q/49068153
score: 0
type: QuestionComment
has text: Can you post the contents of `name_box`?

http://stackoverflow.com/q/49017088
type: Question
has body: I have two .csv files in which I am attempting to find exact matches between the two. First sheet is testnasdaq.csv and it contains: Symbol GOGO WFTX SYQD B Second sheet is mytickers.csv and it contains: Symbol GOGO WFT QD S I am using this code currently, but it is not giving the correct results and I can not seem to figure out why that is. import csv import requests nasdaqDatabase = r'C:\Users\Sterling\Desktop\StockProject\testnasdaq.csv' with open(nasdaqDatabase, "r") as f: nasdaq_reader = csv.DictReader(f) nasdaq_symbols = set([row['Symbol'] for row in nasdaq_reader]) with open(r'C:\Users\Sterling\Desktop\StockProject\mytickers.csv', 'r' ) as theFile: reader = csv.DictReader(theFile) for row in reader: if row['Symbol'] in nasdaq_symbols: print(row['Symbol'], 'FOUND') newAddress = 'blank.com/' + row['Symbol'] + '.htm' print(newAddress) else: print(row['Symbol'], 'NOT FOUND') newAddress = 'blank.com/' + row['Symbol'] + '.htm' print(newAddress) The output that I am getting is: GOGO FOUND blank.com/GOGO.htm S NOT FOUND blank.com/S.htm Process finished with exit code 0 Any help is appreciated.
has comment: http://stackoverflow.com/comment/85039243
has title: Locating matches with .csv files in python issue
answer count: 1
accepted answer: http://stackoverflow.com/a/49017138
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49017138

http://stackoverflow.com/q/48998972
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85003567
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/15112125
type: UnansweredQuestion
tagged with: python
has title: Cant make it print if a word isnt found in my word search project
has comment: http://stackoverflow.com/comment/85003326
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/85009012
linked to: http://stackoverflow.com/q/15112125
type: Question
has body: This is the code for the main body. Which goes through a string of character formats them and then searches words in a inputed list. the string of characters is 'WAQHGTTWEECBMIVQQELSAZXWKWIIILLDWLFXPIPVPONDTMVAMNOEDSOYQGOBLGQCKGMMCTYCSLOACUZMXVDMGSXCYZUUIUNIXFNU' and the string of words is 'UNIX CALPOLY GCC SLO COMPILE VIM TEST' my code correctly finds the words in all directions how ever the issue is when it doesn't find the word. import funcs def main(): rawPuzzle = funcs.create_puzzle() words = funcs.get_words() funcs.print_puzzle(rawPuzzle) puzzle = funcs.format_puzzle(rawPuzzle) vertPuzzleRaw = funcs.make_vert_puzzle(puzzle) vertPuzzle = funcs.format_vert_puzzle(vertPuzzleRaw) for x in range(len(words)): word = words[x] for l in range(len(puzzle)): forward = funcs.check_forward(puzzle, word, l) if forward != -1: print(word, ': (FORWARD)', 'row: ', l, 'column: ', forward) backward = funcs.check_backward(puzzle, word, l) if backward != -1: print(word, ': (BACKWARD)', 'row: ', l, 'column: ', (9 - backward)) down = funcs.check_down(vertPuzzle, word, l) if down != -1: print(word, ': (DOWN)', 'row: ', down, 'column: ', l) up = funcs.check_up(vertPuzzle, word, l) if up != -1: print(word, ': (UP)', 'row: ', (9 - up), 'column: ', l) if forward and backward and down and up == -1: print(word, ': word not found') if __name__ == '__main__': main() and the output looks like this: Puzzle: WAQHGTTWEE CBMIVQQELS AZXWKWIIIL LDWLFXPIPV PONDTMVAMN OEDSOYQGOB LGQCKGMMCT YCSLOACUZM XVDMGSXCYZ UUIUNIXFNU UNIX : word not found UNIX : word not found UNIX : word not found UNIX : word not found UNIX : word not found UNIX : word not found UNIX : word not found UNIX : word not found UNIX : word not found UNIX : (FORWARD) row: 9 column: 3 UNIX : word not found CALPOLY : (DOWN) row: 1 column: 0 CALPOLY : word not found CALPOLY : word not found CALPOLY : word not found CALPOLY : word not found CALPOLY : word not found CALPOLY : word not found CALPOLY : word not found CALPOLY : word not found …
upvote count: 2

http://stackoverflow.com/a/49008394
answers question: http://stackoverflow.com/q/49007982
type: AcceptedAnswer
has body: This xpath should do the trick //a[./preceding-sibling::h2[.='TAG1']][./following-sibling::h2[.='TAG2']] The xpath reads as select all a tags which has h2 with text TAG 1 preceding it and h2 with text TAG2 following it.
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49007982
score: 4

http://stackoverflow.com/comment/85189071
type: AnswerComment
comment on: http://stackoverflow.com/a/49083767
type: Comment
score: 1
has text: Using `brew link python2` gives `Warning: python@2 is keg-only and must be linked with --force Note that doing so can interfere with building software.`

http://stackoverflow.com/q/48967780
favorite count: 0
type: UnansweredQuestion
has title: applying function to dataframe; timestamp.dt
tagged with: python
has answer: http://stackoverflow.com/a/48967889
type: Question
has answer: http://stackoverflow.com/a/48967897
upvote count: 5
answer count: 2
score: 5
tagged with: pandas
downvote count: 0
has body: Ultimately I want to calculate the number of days to the last day of the month from every date in df['start'] and populate the 'count' column with the result. As a first step towards that goal the calendar.monthrange method takes (year, month) arguments and returns a (first weekday, number of days) tuple. There seems to be a general mistake regarding applying functions to dataframes or series objects. I would like to understand, why this isn't working. import numpy as np import pandas as pd import calendar def last_day(row): return calendar.monthrange(row['start'].dt.year, row['start'].dt.month) This line raises an AttributeError: "Timestamp object has no attribute 'dt'": df['count'] = df.apply(last_day, axis=1) this is what my dataframe looks like: start count 0 2016-02-15 NaN 1 2016-02-20 NaN 2 2016-04-23 NaN df.dtypes start datetime64[ns] count float64 dtype: object

http://stackoverflow.com/a/65663334
downvote count: 0
upvote count: 3
has body: It is solved by cleaning .pycharm_helpers folder on remote interpreter. rm -rf ~/.pycharm_helpers
answers question: http://stackoverflow.com/q/49007292
type: Answer
score: 3

http://stackoverflow.com/comment/132379691
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48997550
has text: Why curl Windows does not supprt specific "--interface"?

http://stackoverflow.com/a/49020144
score: 2
has comment: http://stackoverflow.com/comment/85045514
upvote count: 2
answers question: http://stackoverflow.com/q/49020085
has body: You've specified the length as a size_t. The s# format does not take a size_t. It takes an int or Py_ssize_t, depending on whether the PY_SSIZE_T_CLEAN macro was #defined before including Python.h. Note: For all # variants of formats (s#, y#, etc.), the type of the length argument (int or Py_ssize_t) is controlled by defining the macro PY_SSIZE_T_CLEAN before including Python.h. If the macro was defined, length is a Py_ssize_t rather than an int. This behavior will change in a future Python version to only support Py_ssize_t and drop int support. It is best to always define PY_SSIZE_T_CLEAN.
downvote count: 0
has comment: http://stackoverflow.com/comment/85045648
type: Answer

apache
tag name: apache
tags question: http://stackoverflow.com/q/49040998
tags question: http://stackoverflow.com/q/49043325
tags question: http://stackoverflow.com/q/49069444
tags question: http://stackoverflow.com/q/49087480
tags question: http://stackoverflow.com/q/49047674
tags question: http://stackoverflow.com/q/49112945
type: Tag
tags question: http://stackoverflow.com/q/49089415
tags question: http://stackoverflow.com/q/49035412

http://stackoverflow.com/comment/85165174
score: 1
comment on: http://stackoverflow.com/q/49079517
has text: As I understand, the image is stored in your file system, and you want to send it to Slack. You are attempting to use a flask server to host images at given urls?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85168038
comment on: http://stackoverflow.com/a/49061904
has text: The end result is what I actually I want and use the key values to call the corresponding arrays into a new file
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85186593
has text: Couldn't you just have a fixture where the setup is and then provide that fixture to those particular tests? Something like this (with the `yield`): https://docs.pytest.org/en/latest/fixture.html#fixture-finalization-executing-teardown-code
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49090260

http://stackoverflow.com/comment/85324379
type: AnswerComment
has text: Thanks so much for your help. Unfortunately this produces a column of NaN so the lookup is failing somehow. When I run type on a value for each, they are both <class 'str'> so im not sure why its failing...
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49059113

http://stackoverflow.com/q/48985352
favorite count: 0
has comment: http://stackoverflow.com/comment/84975481
has comment: http://stackoverflow.com/comment/84978876
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84979993
downvote count: 2
has comment: http://stackoverflow.com/comment/84975561
has title: How to find a vector from a list of vectors that is nearest to all other vectors using Python?
tagged with: python
has comment: http://stackoverflow.com/comment/85024186
answer count: 1
has comment: http://stackoverflow.com/comment/84975307
score: 0
tagged with: math
tagged with: scipy
tagged with: vector
tagged with: scikit-learn
type: UnansweredQuestion
has body: I have a list of vectors as a numpy array. [[ 1., 0., 0.], [ 0., 1., 2.] ...] They all have the same dimension. How do I find out that in the vector space which vector is the closest to all the other vectors in the array? Is there scipy or sklearn function that calculates this? Update: By "closest", I meant the cosine and the Euclidean distance. Update 2: Let's say I have 4 vectors (a,b,c,d), and the Cosine distance between the vectors are: a,b = 0.2 a,c = 0.9 a,d = 0.7 b,c = 0.5 b,d = 0.75 c,d = 0.8 So for each, vector a,b,c,d I get : { 'a': [1,0.2,0.9,0.7], 'b': [0.2,1,0.5,0.75], 'c' : [0.9,0.5,1,0.75], 'd' : [0.7,0.75,0.8,1] } Is there a way of saying let's say vector d is the one that is the most similar to a,b,c ?
has answer: http://stackoverflow.com/a/48986228
has comment: http://stackoverflow.com/comment/84975219
has comment: http://stackoverflow.com/comment/84975500

http://stackoverflow.com/comment/85032477
has text: @chepner I tried this before and it gave me TypeError: must be str, not bytes
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49013719

markov
tags question: http://stackoverflow.com/q/49038111
type: Tag
tag name: markov

http://stackoverflow.com/q/49081813
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85169338
answer count: 1
tagged with: neural-network
has title: Keras CNN predicts only a single class
tagged with: keras
favorite count: 0
has body: I've been trying to do some basic facial recognition using Keras, but I always get the same label for some reason. I am training it on 2 classes, Person A and Person B. After its own validation testing, I input images that were neither in the training nor the validation set but it always gives me the same label. I have reduced the number of validation samples in this case for the sake of time, but even with more validation samples it doesn't appear to work. I have tried it with binary and sigmoid, but that doesn't help me either. My accuracy often jumps up to 90% and even 100% at times, and my loss is around 0.05 to 0.1. Person A has 809 images while Person B has 777 images for training. The end goal I need is to output probabilities of the image belonging to a certain class, and I would greatly appreciate any help since I am new to this field. Thanks! from keras.preprocessing.image import ImageDataGenerator from keras import backend as K import keras from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense K.set_image_dim_ordering('th') import tensorflow as tf config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) sess = tf.Session(config=config) keras.backend.set_session(sess) K.tensorflow_backend._get_available_gpus() # Setting the image size img_width, img_height = 250, 250 train_data_dir = 'data/train2' validation_data_dir = 'data/validation2' datagen = ImageDataGenerator(rescale=1./255) # Train and Test Generators train_generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=32, class_mode = 'categorical') validation_generator = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=32, class_mode = 'categorical') #The actual CNN model = Sequential() model.add(Convolution2D(32, 3, 3, input_shape=(3, img_width, img_height))) model.add(Activation('relu')) model.add(MaxPo…
has comment: http://stackoverflow.com/comment/85169384
has comment: http://stackoverflow.com/comment/85169152
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49096794
has comment: http://stackoverflow.com/comment/85169221

http://stackoverflow.com/q/48963908
type: Question
has answer: http://stackoverflow.com/a/48964172
has title: How to insert space between alphabet characters and numeric character using regex?
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/48963956
favorite count: 0
has answer: http://stackoverflow.com/a/48963970
has body: I'm trying to insert space between numeric characters and alphabet character so I can convert numeric character to words like : Input : subject101 street45 Output : subject 101 street 45 I tried this one re.sub('[a-z][\d]|[\d][a-z]',' ','subject101') but the output was like this : subjec 01 How can I do it using python?
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/48963970
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84933818
upvote count: 2
has comment: http://stackoverflow.com/comment/84933598
downvote count: 2
has comment: http://stackoverflow.com/comment/84933823
has answer: http://stackoverflow.com/a/48963956

http://stackoverflow.com/comment/85204340
type: AnswerComment
score: 0
type: Comment
has text: ah yes much more concise, don't know why I thought the generator expression was necessary
comment on: http://stackoverflow.com/a/49099512

http://stackoverflow.com/comment/85206298
comment on: http://stackoverflow.com/q/49100167
score: 0
has text: Please take a look [at this file](https://github.com/iharob/apache-ws/blob/master/python/src/py-apache-ws.c), I wrote it. There you can see how to create a Python obejct in [tag:c], I think this will fit perfectly and let you achieve your goal. Sorry if it's not well commented, it's a hobby project and I promised to comment it later, but you know ...
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49028533
tagged with: path
tagged with: pip
tagged with: python
has title: Pip packages path - windows
type: AnsweredQuestion
downvote count: 1
accepted answer: http://stackoverflow.com/a/49028561
type: Question
score: 5
upvote count: 6
has answer: http://stackoverflow.com/a/49028561
has comment: http://stackoverflow.com/comment/85064838
tagged with: windows
answer count: 1
has comment: http://stackoverflow.com/comment/85064802
favorite count: 0
has body: I have pip install &lt;package name&gt; installing the packages to AppData/Python/Python36/Scripts folder. How do I know the exact path to this folder from Command line? I tried doing py -m site --userbase This is showing AppData/Roaming/Python/Python36 which does not exist. How will I get to know the path without actually doing manual search? PS : I am writing an automation script to install pip and awscli later. After I install pip, I face command not found error. So looking how to set path directly from a script without having to face the issue of manually setting it. Found out that pip.exe and aws.exe are under AppData/Python/Python36/Scripts. My question is how do I get this path from inside a script.

http://stackoverflow.com/q/49095346
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85198052
has comment: http://stackoverflow.com/comment/85198058
tagged with: scikit-learn
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85197677
has comment: http://stackoverflow.com/comment/85198007
tagged with: python
has answer: http://stackoverflow.com/a/50462077
type: UnansweredQuestion
tagged with: classification
has title: Python Scikit-Learn SVM - No Predicted Samples for a Class
upvote count: 1
has comment: http://stackoverflow.com/comment/85197952
downvote count: 1
has comment: http://stackoverflow.com/comment/85197782
has answer: http://stackoverflow.com/a/49096543
has comment: http://stackoverflow.com/comment/85197075
has body: I am doing a classification task in Python to classify audio files of different musical instrument into their respective class, in my case there are 4 class, which are Brass, String, Percussion, and Woodwind. I used SVM algorithm as the classifier. My code looks a bit like this (I do not change any parameter for the classifier): #X is feature matrix, y is class vector X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) #SVM Classifier svm = SVC() svm.fit(X_train,y_train) svm_pred = svm.predict(X_test) print(metrics.classification_report(y_test,svm_pred) When I try to run this code, I got problem with the classifier. The error code looks like this: precision recall f1-score support Brass 1.00 0.21 0.34 72 Percussion 0.38 1.00 0.55 279 String 1.00 0.15 0.26 276 Woodwind 0.00 0.00 0.00 156 avg / total 0.58 0.43 0.32 783 C:\Users\Anaconda3\lib\site-packages\sklearn\metrics\classification.py:1135: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. When I checked my predicted labels from SVM classifier(svm_pred), no Woodwind class are predicted by the classifier &gt;&gt;&gt; set(svm_pred) {'Brass','String','Percussion'} My number of samples for each class are like this: Brass = 200 samples, Woodwind = 500 samples, Percussion = 900 samples, and String = 800 samples so it is a bit imbalanced My question is, is it possible for a SVM classifier to not predict a class at all in the output of the classifier like my case above?
has comment: http://stackoverflow.com/comment/85197027
has comment: http://stackoverflow.com/comment/85197240
tagged with: svm
type: Question

http://stackoverflow.com/q/49117565
has answer: http://stackoverflow.com/a/49119437
has body: Primer: I'm extremely new to Python. I am working on taking some Google Sheets data, and creating .xlsx sheets with it. With the code below, I am able to get Python to read the data and put it into arrays. However, I can't seem to figure out how to get openpyxl to write it to a document successfully. I'm assuming it has something to do with trying to write an array rather than iterating over rows that appear. Any help/advice you all could provide would be greatly appreciated. I get the following error when trying to run it: Traceback (most recent call last): File "quickstart.py", line 94, in &lt;module&gt; main() File "quickstart.py", line 90, in main ws.append([values]) File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\worksheet.py", line 763, in append cell = Cell(self, row=row_idx, col_idx=col_idx, value=content) File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 115, in __init__ self.value = value File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 299, in value self._bind_value(value) File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 206, in _bind_value raise ValueError("Cannot convert {0!r} to Excel".format(value)) ValueError: Cannot convert [['Student Name', 'Gender', 'Class Level', 'Home State', 'Major', 'Extracurricular Activity'], ['Alexandra', 'Female', '4. Senior', 'CA', 'English', 'Drama Club'], ['Andrew', 'Male', '1. Freshman', 'SD', 'Math', 'Lacrosse'], ['Anna', 'Female', '1. Freshman', 'NC', 'English', 'Basketball'], ['Becky', 'Female', '2. Sophomore', 'SD', 'Art', 'Baseball'], ['Benjamin', 'Male', '4. Senior', 'WI', 'English', 'Basketball'], ['Carl', 'Male', '3. Junior', 'MD', 'Art', 'Debate'], ['Carrie', 'Female', '3. Junior', 'NE', 'English', 'Track &amp; Field'], ['Dorothy', 'Female', '4. Senior', 'MD', 'Math', 'Lacrosse'], ['Dylan', 'Male', '1. Freshman', 'MA', 'Math', 'Baseball'], ['Edward', 'Male', '3. Junior', 'FL', 'English', 'Drama Club'], ['E…
answer count: 3
has comment: http://stackoverflow.com/comment/85241064
has title: How Do I Write Google Sheets Data to Microsoft Excel?
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/73995021
has comment: http://stackoverflow.com/comment/85240959
has comment: http://stackoverflow.com/comment/85243379
tagged with: excel
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49118996
has comment: http://stackoverflow.com/comment/85242940
type: Question
has comment: http://stackoverflow.com/comment/85243095
accepted answer: http://stackoverflow.com/a/49118996
score: 2
tagged with: google-sheets
possible better answer: http://stackoverflow.com/a/49119437
linked to: http://stackoverflow.com/q/5351093
downvote count: 0

http://stackoverflow.com/comment/85234197
type: AnswerComment
has text: @OhDear Great. Read here: [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)
comment on: http://stackoverflow.com/a/49114040
type: Comment
score: 0

http://stackoverflow.com/q/48965137
score: 1
favorite count: 0
tagged with: elasticsearch
tagged with: python
accepted answer: http://stackoverflow.com/a/48965779
has body: I tried to use the following code to create and load data into an index using python: from datetime import datetime from elasticsearch import Elasticsearch from elasticsearch import helpers es = Elasticsearch() actions = [ { "_index": "tickets-index", "_type": "tickets", "_id": j, "_source": { "any":"data" + str(j), "timestamp": datetime.now()} } for j in range(0, 10) ] helpers.bulk(es, actions) On executing the code, it shows: elasticsearch.exceptions.TransportError: TransportError(406, u'Content-Type header [] is not supported') I guess this code was previously written by someone on this forum as a solution, but it did not work for me. Please let me know on why do we get this issue and how can i get this solved. Thanks in advance.
type: AnsweredQuestion
upvote count: 1
has title: Unable to load elasticsearch index using bulk api
type: Question
has answer: http://stackoverflow.com/a/48965779
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85064792
comment on: http://stackoverflow.com/q/49028756
score: 0
type: QuestionComment
has text: What do you mean by "name of the frame"? Are you asking how to get the text of the notebook tab?
type: Comment

http://stackoverflow.com/a/49114680
type: Answer
has comment: http://stackoverflow.com/comment/85234770
has comment: http://stackoverflow.com/comment/85236058
has body: In the example you attached, CND is a function that is defined later in the article. You had to copy and run the whole code! The other functions (log and sqrt) are imported well, but your IDE seems to ignore it.
has comment: http://stackoverflow.com/comment/85235702
answers question: http://stackoverflow.com/q/49113979
score: 0

http://stackoverflow.com/q/49096242
answer count: 1
tagged with: python
tagged with: django-guardian
has title: Override get_queryset based on django-guardian permissions
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
score: 2
has answer: http://stackoverflow.com/a/49096508
type: Question
downvote count: 0
has body: I am trying to override get_queryset based on the object permissions, which the users have from django guardian, so that only the objects are visible, which the users have permissions for. def get_queryset(self, request): if request.user.is_superuser: qs = super(MyAdminInline, self).get_queryset(request) return qs for item in MyModel.objects.all(): for perm in get_perms(request.user, item): things_user_can_see = get_objects_for_user(request.user, perm) return things_user_can_see Sadly, this literally does nothing and all of the items, regardless of the permissions that the users have, are visible.

http://stackoverflow.com/comment/85058941
has text: Why did you tag your question with `docker` ?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49026524

http://stackoverflow.com/comment/84940334
comment on: http://stackoverflow.com/a/48967317
type: AnswerComment
has text: Surely it's far easier just to check the limits of the coords rather than just check if it's contained a in an object containing all possible permitted coords
score: 0
type: Comment

http://stackoverflow.com/a/49094163
has comment: http://stackoverflow.com/comment/85193492
answers question: http://stackoverflow.com/q/49094078
has body: If your names repeats use "_" to avoid such warnings.It's a common practice. def get_files_name(): root_dir = "/Volumes/NO NAME/" for root, _ds, fs in os.walk(root_dir): for f in fs: print(os.path.join(root_dir, f)) get_files_name() for root, _ds, fs in os.walk(other_dir): pass
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/85039338
has text: Disregard my last comment. Didn't read @glibdud answer properly :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49016951
type: AnswerComment

http://stackoverflow.com/comment/125104471
type: Comment
score: 1
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment
comment on: http://stackoverflow.com/a/70765950

http://stackoverflow.com/a/49038341
has body: "How to create entry inputs in a toplevel window" import tkinter as tk ... toplevel = tk.Toplevel(...) tk.Entry(toplevel) "How to create a child window on pressing a button..." import tkinter as tk ... def create_child_window(widget): tk.Toplevel(widget) ... root = tk.Tk() tk.Button(root, command=lambda w = root: create_child_window(w))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49035768

http://stackoverflow.com/a/53800458
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49010285
has comment: http://stackoverflow.com/comment/129413740
downvote count: 0
type: Answer
has body: Try this it is an example of working code from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = np.nan, strategy = 'mean', axis =0) imputer = imputer.fit(X[:,1:3]) X[:,1:3] = imputer.transform(X[:,1:3])

http://stackoverflow.com/comment/85036537
comment on: http://stackoverflow.com/q/49013901
type: Comment
score: 9
has text: managed to fix it by reinstalling the whole matplotlib module. `py -m pip uninstall matplotlib` and then `py -m pip install matplotlib`
type: QuestionComment

http://stackoverflow.com/comment/85182583
has text: what does the users value stand for? are these the complete figures or just a sample?
score: 0
comment on: http://stackoverflow.com/q/49087869
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85197054
type: Comment
comment on: http://stackoverflow.com/a/49095917
has text: Just tried this by redefining `class Simple(Base):`, but in `__init_subclass__`, without changing `Simple`, there is no `"__init__"` key in `cls.__dict__`, so the rest of your code doesn't run.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85064810
type: QuestionComment
comment on: http://stackoverflow.com/q/49029751
has text: add a link to your code, preferably a github link. I'll have a look.
score: 0
type: Comment

http://stackoverflow.com/comment/88158570
has text: I tried your code, but I think it still doesn't solve the problem. The problem is solved by imwrite rather than the plot
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48990614

http://stackoverflow.com/q/49065459
favorite count: 0
has comment: http://stackoverflow.com/comment/85143198
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/85136142
has title: numpy read txt error (loadtxt, genfromtxt)
tagged with: numpy
has answer: http://stackoverflow.com/a/49065586
accepted answer: http://stackoverflow.com/a/49065586
has body: I would like to read text file like below in python Example of text file {# "Column 4-5 Quantity": "Re/Im Pressure" # "Column 4-5 Units": "" # "Number Rows": 3584879 #} 4.0740740741e-002 -5.0370370370e-002 7.3333333333e-002 9.4443035889e+002 -6.0709484863e+002 4.1481481481e-002 -5.0370370370e-002 7.3333333333e-002 9.0292657471e+002 -6.2604998779e+002 4.2222222222e-002 -5.0370370370e-002 7.3333333333e-002 8.2029248047e+002 -6.4528021240e+002 4.2962962963e-002 -5.0370370370e-002 7.3333333333e-002 7.1829382324e+002 -6.5028546143e+002 4.3703703704e-002 -5.0370370370e-002 7.3333333333e-002 1.#QNAN00000e+000 0.0000000000e+000 4.4444444444e-002 -5.0370370370e-002 7.3333333333e-002 1.#QNAN00000e+000 0.0000000000e+000 4.5185185185e-002 -5.0370370370e-002 7.3333333333e-002 1.#QNAN00000e+000 0.0000000000e+000 4.5925925926e-002 -5.0370370370e-002 7.3333333333e-002 1.#QNAN00000e+000 0.0000000000e+000 -3.2592592593e-002 -4.9629629630e-002 7.3333333333e-002 4.9716027832e+002 -1.2688856201e+003 -3.1851851852e-002 -4.9629629630e-002 7.3333333333e-002 5.3677227783e+002 -1.4196939697e+003 -3.1111111111e-002 -4.9629629630e-002 7.3333333333e-002 6.1588317871e+002 -1.5679577637e+003 -3.0370370370e-002 -4.9629629630e-002 7.3333333333e-002 7.2673925781e+002 -1.7039268799e+003 -2.9629629630e-002 -4.9629629630e-002 7.3333333333e-002 8.5946520996e+002 -1.7935989990e+003 -2.8888888889e-002 -4.9629629630e-002 7.3333333333e-002 1.0030370483e+003 -1.7982950439e+003 Thus I used numpy's function loadtxt and genfromtxt First I tried loadtxt the code is impoty numpy as np readtxt = np.loadtxt("filename.txt") and I got error message like below Wrong number of columns at line 5 Second I tried genfromtxt the code is impoty numpy as np readtxt = np.genfromtxt("filename.txt") and I got error message like below Line #5 (got 5 columns instead of 4) So, How could I figure out this problem? I think the problem is "1.#QNAN00000e+000" And I would like to change this value as "0"
tagged with: genfromtxt
upvote count: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49040620
has answer: http://stackoverflow.com/a/49046937
has comment: http://stackoverflow.com/comment/85086621
type: Question
tagged with: python-multiprocessing
upvote count: 4
answer count: 2
has body: thanks for taking a look at this. I confess I have been dabbling with parallel processing in python for all of 1 week now so I apologize if there is an obvious solution I missed. I have a piece of code that I would like to run several different instances of of a mp.pool(). Those that were on the main .py file called worked fine but when I tried to add them to functions in modules I get no output from them all. The app just runs past it and continues. I am thinking it may have something to do with this post but it didn't give any ideas on alternative methods to accomplish what I need. The code that works in a simple example is this: import multiprocessing as mp def multiproc_log_result(retval): results.append(retval) if len(results) % (10 // 10) == 0: print('{0}% done'.format(100 * len(results) / 10)) def meat(): print 'beef' status = True return status results = [] pool = mp.Pool(thread_count) for x in range(10): pool.apply_async(meat, callback=multiproc_log_result) pool.close() pool.join() def veggie(): print 'carrot' status = True return status results = [] pool = mp.Pool(thread_count) for x in range(10): pool.apply_async(veggie, callback=multiproc_log_result) pool.close() pool.join() And the code that doesn't work is: import multiprocessing as mp def multiproc_log_result(retval): results.append(retval) if len(results) % (10 // 10) == 0: print('{0}% done'.format(100 * len(results) / 10)) def meat(): print 'beef' status = True return status results = [] pool = mp.Pool(thread_count) for x in range(10): pool.apply_async(meat, callback=multiproc_log_result) pool.close() pool.join() def nested_stupid_fn(): def multiproc_log_result(retval): results.append(retval) if len(results) % (10 // 10) == 0: print('{0}% done'.format(100 * len(results) / 10)) def veggie(): print 'carrot' status = True return status results = [] pool = mp.Pool(thread_count) for x in range(10): pool.apply_async(veggie, callback=multiproc_log_result) pool.close() pool.join() nested_stupid_fn() Ultimat…
downvote count: 0
score: 4
tagged with: process-pool
tagged with: python-2.7
has answer: http://stackoverflow.com/a/56810426
favorite count: 0
type: UnansweredQuestion
has title: Is there any way to use multiprocessing.pool within a nested function or module?
tagged with: python
linked to: http://stackoverflow.com/q/46266803

function
tags question: http://stackoverflow.com/q/49085668
tags question: http://stackoverflow.com/q/48981282
tags question: http://stackoverflow.com/q/48977589
tag name: function
tags question: http://stackoverflow.com/q/49032953
tags question: http://stackoverflow.com/q/49055336
tags question: http://stackoverflow.com/q/49019554
tags question: http://stackoverflow.com/q/49093444
tags question: http://stackoverflow.com/q/49054993
tags question: http://stackoverflow.com/q/49102225
tags question: http://stackoverflow.com/q/49048537
tags question: http://stackoverflow.com/q/49025996
tags question: http://stackoverflow.com/q/49039491
tags question: http://stackoverflow.com/q/48991993
tags question: http://stackoverflow.com/q/48968881
tags question: http://stackoverflow.com/q/48977374
tags question: http://stackoverflow.com/q/49108378
tags question: http://stackoverflow.com/q/49040796
tags question: http://stackoverflow.com/q/48970346
tags question: http://stackoverflow.com/q/49061465
tags question: http://stackoverflow.com/q/49093856
tags question: http://stackoverflow.com/q/48966507
tags question: http://stackoverflow.com/q/49020361
tags question: http://stackoverflow.com/q/49013629
tags question: http://stackoverflow.com/q/49041841
tags question: http://stackoverflow.com/q/49099874
tags question: http://stackoverflow.com/q/49081369
tags question: http://stackoverflow.com/q/49028775
type: Tag
tags question: http://stackoverflow.com/q/49101036
tags question: http://stackoverflow.com/q/49080500
tags question: http://stackoverflow.com/q/48969799
tags question: http://stackoverflow.com/q/49010360
tags question: http://stackoverflow.com/q/48984319
tags question: http://stackoverflow.com/q/49016527
tags question: http://stackoverflow.com/q/49058775
tags question: http://stackoverflow.com/q/49097013
tags question: http://stackoverflow.com/q/49010207
tags question: http://stackoverflow.com/q/48991374
tags question: http://stackoverflow.com/q/49118267
tags question: http://stackoverflow.com/q/49099141
tags question: http://stackoverflow.com/q/49086551
tags question: http://stackoverflow.com/q/49081092
tags question: http://stackoverflow.com/q/49107512
tags question: http://stackoverflow.com/q/48990191
tags question: http://stackoverflow.com/q/49075560
tags question: http://stackoverflow.com/q/49078780
tags question: http://stackoverflow.com/q/49050030
tags question: http://stackoverflow.com/q/49103873
tags question: http://stackoverflow.com/q/49101815
tags question: http://stackoverflow.com/q/48997485
tags question: http://stackoverflow.com/q/49038977
tags question: http://stackoverflow.com/q/49113174
tags question: http://stackoverflow.com/q/48966912

mutable
tags question: http://stackoverflow.com/q/49117286
type: Tag
tag name: mutable

http://stackoverflow.com/comment/110381049
has text: This would be a better answer if you explained how the code you provided answers the question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/62407810
type: Comment

http://stackoverflow.com/q/49029400
has body: I am trying to create java jar with the files in AWS S3 by Lambda function using Python I have tried in both ways import os def lambda_handler(event, context): os.system('jar cf abc.jar, file1.txt, file2.txt') return "Success" and import subprocess def lambda_handler(event, context): subprocess.call('jar cf abc.jar, file1.txt, file2.txt') return "Success"
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has title: create java jar in lambda function using python
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49030128

http://stackoverflow.com/q/49021710
type: AnsweredQuestion
downvote count: 0
has title: How can I keep track of which text entry is clicked?
has comment: http://stackoverflow.com/comment/85049085
score: 1
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85049122
favorite count: 0
tagged with: tkinter
has body: If I have a Tkinter Text widget with the text bound to a mouse click, how can I keep track of which text the user clicks on? I want the function to return the number of the label clicked, but as it stands it only prints the last value of n which is 5. For example, if the user clicks "Name 1", I want it to print "1", if the user clicks on "Name 2", I want it to return "2". Here is the code: import tkinter as tk def prt(num): print(num) root = tk.Tk() t = tk.Text(root, height=20, width=50) t.pack() for n in range(1, 6): t.insert(tk.END, "%s %d\n" % ("Name", n), "label") t.tag_bind("label", "&lt;Button-1&gt;", lambda event, num = n: prt(num)) root.mainloop() Any help appreciated.
has answer: http://stackoverflow.com/a/49022058
tagged with: python
accepted answer: http://stackoverflow.com/a/49022058

http://stackoverflow.com/comment/85139577
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49067231
has text: @pyd - Glad can help!

http://stackoverflow.com/a/49041651
has comment: http://stackoverflow.com/comment/85089138
downvote count: 0
has comment: http://stackoverflow.com/comment/85088745
answers question: http://stackoverflow.com/q/49041602
has comment: http://stackoverflow.com/comment/85089025
upvote count: 2
type: Answer
score: 2
has body: add project folder to sys.path import sys sys.path.append('/project/folder') import Maths

http://stackoverflow.com/a/49110666
has body: Trying using LA instead of just L as follows: from PIL import Image, ImageFilter import matplotlib.pyplot as plt file_name = r'images\2.4.1.png' im0 = Image.open(file_name).convert('LA') plt.imshow(im0, cmap='gray') plt.show() The parameter specifies the conversion mode, in your case the PNG file probably has an alpha channel, so the A is needed. See also: Pillow modes
type: Answer
has comment: http://stackoverflow.com/comment/85227868
has comment: http://stackoverflow.com/comment/85228945
has comment: http://stackoverflow.com/comment/85230621
has comment: http://stackoverflow.com/comment/85228102
accepted answer of: http://stackoverflow.com/q/49110328
answers question: http://stackoverflow.com/q/49110328
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85230502
has comment: http://stackoverflow.com/comment/85229007

http://stackoverflow.com/comment/85208360
score: 0
comment on: http://stackoverflow.com/q/49101273
type: Comment
type: QuestionComment
has text: If you wish to use `enumerate`, you have to supply to write `for index, item in enumerate(encrypted_message):`. `Enumerate` gives you both index and value of element in list.

http://stackoverflow.com/q/49039201
has title: How do I generate a random process value given a set of moments or cumulants?
tagged with: python
tagged with: generator
tagged with: simulator
upvote count: 1
has comment: http://stackoverflow.com/comment/85117948
has comment: http://stackoverflow.com/comment/85083757
type: UnansweredQuestion
tagged with: statistics
tagged with: random
answer count: 0
downvote count: 0
score: 1
favorite count: 0
has body: How would a create a data set from a known set of data moments or cumulants. Its fairly easy to generate a random number with a known variance and mean. I would like to get something that lets me submit an array of cumulants (or moments) Example: (ci = cumulent, mi = momemts) c1 = m1 or ‘mean’ c2 = m2 − m1 = σ2 or ‘variance’ (σ = standard deviation) c3 = m3 − 3*m1*m2 + 2*m3 or ‘skewness’ c4 = m4 − 3*m2 − 4*m1*m3 + 12*m1*m2 − 6*m1 or ‘kurtosis' So I would like a function, f, that takes a bunch of ci values and produces a single data point whose array of historical values maintains the specified cumulants. y(i) = f(c1,c2,c3,..., and optionally [y(i-1), y(i-2), ...]) See Moments, Cumulants and Scaling
type: Question

http://stackoverflow.com/comment/84963429
score: 0
comment on: http://stackoverflow.com/q/48979104
has text: ill try and research it then, thank you for the advice
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49069714
type: AnsweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/85144516
has body: I can't use pip. I've tried reinstalling pip. iterm returned: already installed here: Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg So I added Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg to my path: MacBook-Pro:~ user$ export PATH=$PATH:Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg MacBook-Pro:~ user$ pip -bash: pip: command not found MacBook-Pro:~ user$ echo $PATH /usr/bin:/bin:/usr/sbin:/sbin:Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg MacBook-Pro:~ user$ which pip MacBook-Pro:~ user$ It doesn't seem to be working, even though i tried installing pip in /usr/bin
type: Question
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85145169
tagged with: macos
has title: bash: pip: command not found mac os high sierra
favorite count: 0
has answer: http://stackoverflow.com/a/49070075
accepted answer: http://stackoverflow.com/a/49070075
tagged with: python

http://stackoverflow.com/comment/84962017
has text: There is absolutely no guarantee that `eval(str(obj)) == obj` and usually it is not. And that is the least problematic part of the idea...
comment on: http://stackoverflow.com/q/48978121
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49072968
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49072183
score: 1
has comment: http://stackoverflow.com/comment/85152465
upvote count: 1
has body: After looping over ['rows'], you simply need to use the r variable. Use this: for r in json_data['Generic']['rows']: print(r['row1']) print(r['row2']) print(r['row3']) Output: This is row 1-1 This is row 2-1 This is row 3-1 This is row 1-2 This is row 2-2 This is row 3-2 The reason you were getting only the first dictionary is - you were using json_data[x]['rows'][0] inside the loop. This [0] will always give you the first item (dictionary) in the 'rows' list.
accepted answer of: http://stackoverflow.com/q/49072183

http://stackoverflow.com/a/49003771
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49002731
has body: Sometimes PyCharm is using the wrong python interpreter. You can check the one which is used in Preferences &gt; Project &gt; Project Interpreter Make sure it corresponds to the virtualenv of your project. If not, you can change the Python interpreter by browsing to the right one.
has comment: http://stackoverflow.com/comment/85012993

http://stackoverflow.com/a/49018438
type: Answer
accepted answer of: http://stackoverflow.com/q/49017861
answers question: http://stackoverflow.com/q/49017861
has body: This was actually quite embarrassing, but this is what's wrong: server.sendmail(sendMail,loginMail,email) it should be: server.sendmail(loginMail,mailTo,email) I would guess the reason it said that the mails where sent to the recipient was that it was defined as so in the: msg = MIMEMultipart() msg['To'] = mailTo
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/85117557
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49033295
has text: Thanks for the info. Looking at the raw data, it seems it is being returned as mebibytes. need to look at the source a bit more.
score: 0

http://stackoverflow.com/a/49053998
accepted answer of: http://stackoverflow.com/q/49053865
answers question: http://stackoverflow.com/q/49053865
has body: Python 3 has changed how this expression should be written. From the documentation, it is now except OSError as e. Note that in Python 2, both comma and as were permitted.
has comment: http://stackoverflow.com/comment/87598808
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/49114220
type: Answer
accepted answer of: http://stackoverflow.com/q/49113806
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49113806
has body: Because you promoted 'f_xy' up from the 'parab' component, your objective should now be named 'f_xy' instead of 'parab.f_xy', and because you promoted 'x' and 'y' up from the 'indeps' component, your design variables should be named 'x' and 'y' instead of 'indeps.x' and 'indeps.y'.

http://stackoverflow.com/q/49107912
tagged with: python
has comment: http://stackoverflow.com/comment/85220781
score: 1
has title: How to use for loop on pandas.core.groupby.DataFrameGroupBy in reverse order?
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49108071
has body: I have a pandas.core.groupby.DataFrameGroupBy object,iter_gb contains customer Itinerary. The sample data looks like. After Itinerary it contains 6 columns, those columns are not important. Customer_id YEAR Itinerary A1, B1, ... 38915672 2015 B12345 38915672 2012 B12345 38915672 2012 B25431 38915672 2012 B25431 38915672 2012 B25431 38915672 2012 B25431 38915672 2012 B25431 38915672 2012 B36789 38915672 2012 B36789 38915672 2012 B36789 38915672 2012 B36789 38915672 2012 B36789 38915672 2012 B86451 38915672 2012 B86451 38915672 2012 B86451 38915672 2012 B86451 38915672 2011 B86451 I would like to read this using for loop in reverse order. For example for loop will start from last row store all the rows of B86451 in a data frame &amp; then B36789 &amp; so on. how to do that in python 3.x?
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85012963
type: QuestionComment
comment on: http://stackoverflow.com/q/49004210
score: 3
has text: Depends on what you want to do there might be a vectorized approach. If it's not possible you can use `apply_along_axis` with a proper function that does so. Please update your question with a minimal and reliable example.
type: Comment

http://stackoverflow.com/a/49094247
has body: You can try: awk '/pattern1/,/pattern2/' In my experience mawk can be significantly faster than sed with this kind of operation and is usually the fastest. Alternatively gawk4 can be much faster than gawk3, so you could try that too. --edit-- FWIW, just did a small test on a file with 4 million lines On MacOS 10.13: sed : 1.62 real 1.61 user 0.00 sys gsed : 1.31 real 1.30 user 0.00 sys awk : 2.14 real 2.12 user 0.00 sys gawk3: 5.05 real 3.90 user 1.13 sys gawk4: 0.61 real 0.60 user 0.00 sys mawk : 0.42 real 0.40 user 0.00 sys On Centos 7.4: gsed : 1.56 real 1.54 user 0.01 sys gawk4: 1.31 real 1.29 user 0.01 sys mawk : 0.56 real 0.54 user 0.01 sys
type: Answer
has comment: http://stackoverflow.com/comment/85193920
has comment: http://stackoverflow.com/comment/85194222
has comment: http://stackoverflow.com/comment/85198290
has comment: http://stackoverflow.com/comment/85198193
has comment: http://stackoverflow.com/comment/85193828
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85195914
accepted answer of: http://stackoverflow.com/q/49094035
answers question: http://stackoverflow.com/q/49094035
score: 0

http://stackoverflow.com/a/49050101
score: 0
has body: Doc says: This function only picks up the 'p' tags.It doesn’t pick up the 'a' tags, because those tags define both “class” and “id”. It doesn’t pick up tags like 'html' and 'title', because those tags don’t define “class”. soup.find_all(has_class_but_no_id) # [ The Dormouse's story , # Once upon a time there were... , # ... ] It is unclear and it leads people to expect a result without any a tag.They should change the statement or example.
type: Answer
answers question: http://stackoverflow.com/q/49016527

http://stackoverflow.com/comment/85110891
type: Comment
comment on: http://stackoverflow.com/q/49053105
score: 0
has text: Sounds like a bug in SST. Given that it hasn't been updated in five years I'd ditch it.
type: QuestionComment

http://stackoverflow.com/comment/84963083
has text: thanks again for your edit! thats a good advice with import ... as ... :)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48978883
type: AnswerComment

http://stackoverflow.com/comment/84990465
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48990687
score: 1
has text: you can follow it up with concat function as such : `chunk_df = pd.read_csv(filename, iterator=True, chunksize=chunksize)` `df = pd.concat(chunk_df, ignore_index=True)`

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/48993429
tag name: azure-iot-hub

http://stackoverflow.com/q/49086447
has title: Turtle Graphics - how can background image in the center after setting the world cooridinates?
tagged with: http://stackoverflow.com/tag/gif
tagged with: image
score: 0
has answer: http://stackoverflow.com/a/49090192
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49090192
type: AnsweredQuestion
tagged with: turtle-graphics
has body: I have been typically setting the world coordinates to the bottom left hand corner when using turtle graphics. import turtle t=turtle.Pen() turtle.setup(500,500) turtle.setworldcoordinates(0, 0,500, 500) The challenges is that when I insert a background image turtle.bgpic("cat.gif") It is also being moved the original origin (0,0) which is now in the bottom left hand corner of the screen. I need to move the center of the image to the center of my window. Is there to do this?
tagged with: coordinates
type: Question

http://stackoverflow.com/comment/85132871
comment on: http://stackoverflow.com/q/49063732
type: QuestionComment
type: Comment
has text: Can you please post the error.?
score: 0

http://stackoverflow.com/a/49029643
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49029196
answers question: http://stackoverflow.com/q/49029196
has body: you cannot send all the post data like that, as you have list inside your input names, you have to access each names differently and set them in the session. request.session['question_data'] = request.POST.getlist('topics_all') same for other input names, then access with key in the second view
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48974122
has body: i want to implement a q-learning algorithm in a 2D Gridworld. e.g.: [[_,_,_,G], [_,O,_,P], [x,_,_,_]] where "_" = Free Space, "G" = Goal state, "P" = Pitfall, "O" = Obstacle, "x" = the agent that wants to get to the goal state my code works so far but i have problems visualizing the way "x" walks. At the moment i'm just printing the whole list again and again but i would rather have the old gridworld be replaced in the console by the new one so it looks like the agent is moving. I tried to use \r but it didn't worked for lists /numpy arrays. short version: I want to print a list / numpy array over and over again, but the old one should be replaced in the console. I hope someone can help me :D Thanks in advance!
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/84954288
has comment: http://stackoverflow.com/comment/84955194
type: UnansweredQuestion
tagged with: python
has title: Replacing List /Numpy array in the console output (Python)
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/84954710
has comment: http://stackoverflow.com/comment/84955612
type: Question
tagged with: numpy

http://stackoverflow.com/a/49065095
accepted answer of: http://stackoverflow.com/q/49064548
answers question: http://stackoverflow.com/q/49064548
has body: Here is a pretty general method: It works with nested lists, lists of lists of arrays - regardless of whether the shapes of these arrays are different or equal. It also works when the data come clumped together in one single array, which is in fact the trickiest case. (Other methods posted so far will not work in this case.) Let's start with the difficult case, one big array: # create example # pick outer shape and inner shape &gt;&gt;&gt; osh, ish = (2, 3), (2, 5) # total shape &gt;&gt;&gt; tsh = (*osh, *ish) # make data &gt;&gt;&gt; data = np.arange(np.prod(tsh)).reshape(tsh) &gt;&gt;&gt; # recalculate inner shape to cater for different inner shapes # this will return the consensus bit of all inner shapes &gt;&gt;&gt; ish = np.shape(data)[len(osh):] &gt;&gt;&gt; # block them &gt;&gt;&gt; data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh) &gt;&gt;&gt; # admire &gt;&gt;&gt; data_blocked array([[array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]), array([[10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]), array([[20, 21, 22, 23, 24], [25, 26, 27, 28, 29]])], [array([[30, 31, 32, 33, 34], [35, 36, 37, 38, 39]]), array([[40, 41, 42, 43, 44], [45, 46, 47, 48, 49]]), array([[50, 51, 52, 53, 54], [55, 56, 57, 58, 59]])]], dtype=object) Using OP's example which is a list of lists of arrays: &gt;&gt;&gt; x = np.array([[1, 2, 3], [4, 5, 6]]) &gt;&gt;&gt; y = np.array([[7, 8, 9], [0, 1, 2]]) &gt;&gt;&gt; u = np.array([[3, 4, 5], [6, 7, 8]]) &gt;&gt;&gt; v = np.array([[9, 0, 1], [2, 3, 4]]) &gt;&gt;&gt; data = [[x, y], [u, v]] &gt;&gt;&gt; &gt;&gt;&gt; osh = (2,2) &gt;&gt;&gt; ish = np.shape(data)[len(osh):] &gt;&gt;&gt; &gt;&gt;&gt; data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh) &gt;&gt;&gt; data_blocked array([[array([[1, 2, 3], [4, 5, 6]]), array([[7, 8, 9], [0, 1, 2]])], [array([[3, 4, 5], [6, 7, 8]]), array([[9, 0, 1], [2, 3, 4]])]], dtype=object) And an example wit…
downvote count: 0
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/85456056
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/85136849
has comment: http://stackoverflow.com/comment/85214016

http://stackoverflow.com/comment/85181734
type: QuestionComment
has text: @Borut how does asyncio helps in this ? Can you please explain ? I've to make X calls -> wait for there result -> join result -> respond. Will it help ?
comment on: http://stackoverflow.com/q/49087480
score: 0
type: Comment

http://stackoverflow.com/comment/85206754
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49100161
has text: When I last checked, weights of LSTM was after few iterations either very close to -1 or close to 1. By class weights you mean `tf.nn.weighted_cross_entropy_with_logits`?
score: 0

http://stackoverflow.com/comment/85240511
comment on: http://stackoverflow.com/q/49117586
has text: Its probably trying to read image 1053 - and `cap` is None. - Anyhow - you did not really formulate a question, more state the obvious, so whats up?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84942544
type: Comment
score: 1
has text: You can speed this up a bit: `df.T.apply(pd.Series.duplicated, keep='first').sum()`
type: AnswerComment
comment on: http://stackoverflow.com/a/48968485

http://stackoverflow.com/comment/85202076
type: Comment
comment on: http://stackoverflow.com/a/49097052
has text: Have you ever seen this actually used?, Only thing that won't strictly fall under other exceptions is maybe using non hashable keys for accessing or something
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85121314
has text: A subplot grid with 1 row and 3 columns has 3 subplots. Naturally there is no tenth subplot, if there are only 3 present.
score: 0
comment on: http://stackoverflow.com/q/49051488
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85008147
has text: @Aran-Fey I think I fell into the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Thanks for post. Brought a lot of clarity for asking question!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48990191
score: 0

http://stackoverflow.com/a/49039223
has comment: http://stackoverflow.com/comment/85099295
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49038899
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85086003
has body: Suppose your HDB was created as follows: q)(` sv db,`t`)set .Q.en[db:`:alpha/HDB]([]sym:`A`B`C;a:1 2 3) `:alpha/HDB/t/ q)\l alpha/HDB q)t sym a ----- A 1 B 2 C 3 Then, first of all you should load it using \l command, not the load function: &gt;&gt;&gt; q('\\l alpha/HDB') k('::') This will load all your tables and enumeration domains. Now you should be able to convert the sym column of your table to a numpy array of strings &gt;&gt;&gt; np.array(q.t.sym) array(['A', 'B', 'C'], dtype=object) or to a numpy array of integers: &gt;&gt;&gt; np.array(q.t.sym.data) array([0, 1, 2]) You can also convert the entire table to a numpy record array in one go, but you will have to "map" it into the memory first: &gt;&gt;&gt; np.array(q.t.select()) array([('A', 1), ('B', 2), ('C', 3)], dtype=[('sym', 'O'), ('a', '&lt;i8')])
answers question: http://stackoverflow.com/q/49038899
type: AcceptedAnswer

http://stackoverflow.com/comment/84947867
score: 0
comment on: http://stackoverflow.com/q/48971247
has text: only the problem is within the 2d array
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84958275
type: QuestionComment
comment on: http://stackoverflow.com/q/48976599
score: 1
has text: https://stackoverflow.com/questions/35300396/does-cpythons-garbage-collection-do-compaction
type: Comment

http://stackoverflow.com/q/49118209
has answer: http://stackoverflow.com/a/64756171
answer count: 3
favorite count: 0
tagged with: beautifulsoup
upvote count: 9
has answer: http://stackoverflow.com/a/49123550
has answer: http://stackoverflow.com/a/49118330
type: UnansweredQuestion
tagged with: python
has title: BeautifulSoup - How to find a specific class name alone
has body: How to find the li tags with a specific class name but not others? For example: ... no wanted not his one neither this one neither this one neither this one ... I WANT THIS ONLY ONE ... the code: bs4.find_all ('li', class_='z') returns several entries where there is a "z" and another class name. How to find the entry with the class name "z", alone ?
downvote count: 0
type: Question
score: 9

http://stackoverflow.com/comment/84996709
type: QuestionComment
comment on: http://stackoverflow.com/q/48995393
score: 1
has text: @ArtemSokolov I think this questions are different because here OP wants to use subprocess instead of rpy2 external python library.
type: Comment

http://stackoverflow.com/a/49040927
answers question: http://stackoverflow.com/q/49040814
score: 0
has body: I used regex to find the td that contains the word 'Ether' and just parsed that tag. Code: import bs4, requests, re res = requests.get('https://etherscan.io/address/0x93673eeed88fda9423b8037374164383df54aec1') res.raise_for_status() soup = bs4.BeautifulSoup(res.text, 'html.parser') ethBal = soup.find('td', text=re.compile('Ether')).text print('The ETH blance is '+ ethBal) Output: The ETH blance is 0 Ether
type: Answer

shapely
tags question: http://stackoverflow.com/q/49115765
tag name: shapely
type: Tag
tags question: http://stackoverflow.com/q/49039400
tags question: http://stackoverflow.com/q/49099049
tags question: http://stackoverflow.com/q/49061521

expect
tags question: http://stackoverflow.com/q/49040123
type: Tag
tag name: expect
tags question: http://stackoverflow.com/q/49069887

http://stackoverflow.com/a/49096417
has comment: http://stackoverflow.com/comment/85206733
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85419697
upvote count: 2
has body: I don't think you can speedup user's function - in the end it is the responsibility of the user to write an efficient code. What you can do, is to give a possibility to interact with your program in an efficient manner without the need to pay for overhead. You can use Cython, and if the user is also game for using cython, you both could achieve speedups of around 100 compared to pure python-solution. As baseline, I changed your example a little bit: the function rate does more work. class Simulation: def __init__(self, rates): self.rates=list(rates) self.amount = 1 def run(self, maxtime): for t in range(0, maxtime): for rate in self.rates: self.amount += rate(t) def rate(t): return t*t*t+2*t Yields: &gt;&gt;&gt; simulation=Simulation([rate]) &gt;&gt;&gt; %timeit simulation.run(10**5) 43.3 ms ± 1.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) We can use cython to speed things up, first your run function: %%cython cdef class Simulation: cdef int amount cdef list rates def __init__(self, rates): self.rates=list(rates) self.amount = 1 def run(self, int maxtime): cdef int t for t in range(maxtime): for rate in self.rates: self.amount *= rate(t) This gives us almost factor 2: &gt;&gt;&gt; %timeit simulation.run(10**5) 23.2 ms ± 158 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) The user could also use Cython to speed-up his calculation: %%cython def rate(int t): return t*t*t+2*t &gt;&gt;&gt; %timeit simulation.run(10**5) 7.08 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Using Cython gave us already speed-up 6, what is the bottle-neck now? We still are using python for polymorphism/dispatch and this is pretty costly because in order to use it, Python-objects (i.e. Python-integers here) must be created. Can we do better with Cython? Yes, if we define an interface for the function we pass to run at compile time: %%cython cdef class FunInterface: cpdef int calc(self, int t): pass cdef class Simulation: cdef int amount cdef list rates …
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49090810
answers question: http://stackoverflow.com/q/49090810
type: Answer

http://stackoverflow.com/a/49080231
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49080156
type: Answer
has body: From what I can gather by what you've provided, there are only a couple of errors that can occur in this code. In the case that there is no data &lt;= x, your code can fail when it tries return the variable outcome without it having been initialized. It looks like you may have bad indentation on the line where you said the error is shown. Your code can fail when x is not comparable to the type stored in your list.
downvote count: 0

http://stackoverflow.com/q/49000790
upvote count: 1
answer count: 1
favorite count: 0
has title: Increment or index value for list comprehensions?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49000830
tagged with: list
downvote count: 0
score: 1
type: Question
tagged with: enumerate
has answer: http://stackoverflow.com/a/49000830
has body: Is there a handy way to get an autoincrement or index into a list comprehension? I’m trying to build a list of objects, each of which needs a unique identifier. So instead of this: tags_list = ['art', 'science', 'lollipops'] class Tag: def __init__(self, id, name): self.id = id self.name = name tags = [] i = 1 for t in tags_list: tag = Tag(i, t) tags.append(tag) i += 1 …something like this: tags = [Tag(i, t) for t in tags_list] ^^^ how do I get i? I know about enumerate() but this gives me tuples right?
tagged with: list-comprehension

http://stackoverflow.com/a/49103950
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85213151
has body: Object has no attribute data because you didnt give it the attribute. atributes are defined by making writing: self.object = [] instead of: object = []
type: Answer
answers question: http://stackoverflow.com/q/49103877

http://stackoverflow.com/comment/85125964
has text: well `join` requires index as the merge key for the right frames (`on` only effects the left frame), so it looks like you're trying to use the wrong method if you want the '#CNAEpai' column to be the merge key for both frames
comment on: http://stackoverflow.com/q/49060383
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85135861
comment on: http://stackoverflow.com/q/49064831
score: 0
has text: Why don't you just put a comment in the file telling people not to add any code after the sayhi() call? In Python we rely on the principle that "we're all adults here."
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85228054
type: Comment
has text: Does it allow for tf.constant?
type: AnswerComment
comment on: http://stackoverflow.com/a/49098138
score: 0

http://stackoverflow.com/q/49012844
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/85030511
tagged with: django-models
type: Question
has comment: http://stackoverflow.com/comment/85030543
has title: Django: Set charfield default as variable composed of ForeignKeys
has comment: http://stackoverflow.com/comment/85030409
has body: I need to set a default value for a CharField in a Django model as a composite of two ForeignKeys contained within the model itself. Here is the model in questions and the methods I attempted: class SensorParameter(models.Model): sensor = models.ForeignKey(Sensor) parameter = models.ForeignKey(Parameter) parameter_name_userdef = models.CharField(max_length=100, blank=False, default=default_name) live_value = models.FloatField() @staticmethod def default_name(): return str(self.sensor.name) + " - " + str(parameter.parameter_name) def __str__(self): return str(self.sensor.name) + ' - ' + str(self.parameter) def __key(self): return self.sensor.id, self.parameter.id def __eq__(self, y): return isinstance(y, self.__class__) and self.__key() == y.__key() def __hash__(self): return hash(self.__key()) class Meta: unique_together=(('sensor','parameter_name_userdef'),) Explanation: This will be a table of all Parameters that belong to a Sensor. The name of the Parameter instance is generated in another table by the Sensor instance, and the combination of both of those is presented in this table. The user can then opt to change the name of the Parameter for that Sensor only, through this table. The idea is, by default, the parameter_name_userdef(ined) will be a string of Sensor Name + " - " Parameter Name. But through a form and AJAX the user can change it to whatever string they want. I tried the following (assume "max_length=100, blank=False" are set): parameter_name_userdef = models.CharField(default=str(sensor.name) + " - " str(parameter.parameter_name) AttributeError: 'ForeignKey' object has no attribute 'parameter_name' (It does!) parameter_name_userdef = models.CharField(default=str(sensor + parameter)) TypeError: unsupported operand type(s) for +; 'ForeignKey' and 'ForeignKey' parameter_name_userdef = models.CharField(default=str(sensor.name, parameter.parameter_name) AttributeError: 'ForeignKey' object has no attribute 'parameter_name' default_sensor = str(sensor.name…
has comment: http://stackoverflow.com/comment/85030594
score: 0

http://stackoverflow.com/q/49065313
favorite count: 0
has comment: http://stackoverflow.com/comment/85254414
has comment: http://stackoverflow.com/comment/85157939
has comment: http://stackoverflow.com/comment/85172798
has comment: http://stackoverflow.com/comment/85252662
tagged with: python
has body: I've got a bunch of dates i'm trying to OCR using tesseract. However, a lot of the digits in the dates merge with the lines in the date boxes as so: Also, here's a good image that i can tesseract well with: And here's my code: import os import cv2 from matplotlib import pyplot as plt import subprocess import numpy as np from PIL import Image def show(img): plt.figure(figsize=(20,20)) plt.imshow(img,cmap='gray') plt.show() def sort_contours(cnts, method="left-to-right"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method == "bottom-to-top": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == "top-to-bottom" or method == "bottom-to-top": i = 1 # construct the list of bounding boxes and sort them from top to # bottom boundingBoxes = [cv2.boundingRect(c) for c in cnts] cnts, boundingBoxes = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b:b[1][i], reverse=reverse)) # return the list of sorted contours and bounding boxes return cnts, boundingBoxes def tesseract_it(contours,main_img, label,delete_last_contour=False): min_limit, max_limit = (1300,1700) idx =0 roi_list = [] slist= set() for cnt in contours: idx += 1 x,y,w,h = cv2.boundingRect(cnt) if label=='boxes': roi=main_img[y+2:y+h-2,x+2:x+w-2] else: roi=main_img[y:y+h,x:x+w] if w*h &gt; min_limit and w*h &lt; max_limit and w&gt;10 and w&lt; 50 and h&gt;10 and h&lt;50: if (x,y,w,h) not in slist: # Stops from identifying repeted contours roi = cv2.resize(roi,dsize=(45,45),fx=0 ,fy=0, interpolation = cv2.INTER_AREA) roi_list.append(roi) slist.add((x,y,w,h)) if not delete_last_contour: vis = np.concatenate((roi_list),1) else: roi_list.pop(-1) vis = np.concatenate((roi_list),1) show(vis) # Tesseract the final image here # ... image = 'bad_digit/1.jpg' # image = 'bad_digit/good.jpg' specimen_orig = cv2.imread(image,0) specimen = cv2.fastNlMeansDenoisin…
has comment: http://stackoverflow.com/comment/85252618
has answer: http://stackoverflow.com/a/49130797
has comment: http://stackoverflow.com/comment/85138994
tagged with: c++
has title: OpenCV digits merging into surrounding boxes
has answer: http://stackoverflow.com/a/49066648
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/85171739
has comment: http://stackoverflow.com/comment/85254461
type: Question
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85255532
has comment: http://stackoverflow.com/comment/85197792
possible better answer: http://stackoverflow.com/a/49066648
has answer: http://stackoverflow.com/a/49147938
has comment: http://stackoverflow.com/comment/85254949
score: 12
tagged with: imagemagick
accepted answer: http://stackoverflow.com/a/49147938
answer count: 3
upvote count: 12
has comment: http://stackoverflow.com/comment/85199677
downvote count: 0

http://stackoverflow.com/comment/85002427
comment on: http://stackoverflow.com/q/48997698
has text: Hm, have you tried a straight-forward for-loop implementation with `numba` JIT?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49000093
type: AnsweredQuestion
has body: import numpy as np np.random.seed(100) np.random.shuffle([1,2,3,4]) Why do I get [1,2,3,4] as the o/p? Shouldn't it be shuffled?
type: Question
has comment: http://stackoverflow.com/comment/85005471
has answer: http://stackoverflow.com/a/49000140
accepted answer: http://stackoverflow.com/a/49000140
tagged with: numpy
has title: np.random.shuffle not working(Python)
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/85005483
downvote count: 4

system
tags question: http://stackoverflow.com/q/49095889
tag name: system
type: Tag
tags question: http://stackoverflow.com/q/49051245
tags question: http://stackoverflow.com/q/48981724

http://stackoverflow.com/a/48978474
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48978144
has comment: http://stackoverflow.com/comment/84962409
accepted answer of: http://stackoverflow.com/q/48978144
has body: You can also use np.diff along axis 0 and check whether the result is greater than 0. arr = np.array([[0], [1], [2], [7], [4], [5], [6]]) np.diff(arr, axis=0) &gt; 0 array([[ True], 1 &gt; 0 [ True], 2 &gt; 1 [ True], 7 &gt; 2 [False], 4 &gt; 7 [ True], 5 &gt; 4 [ True]]) 6 &gt; 5 There is no row follow [6] and thus the result is one row shorter.
has comment: http://stackoverflow.com/comment/84962502
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84962521
type: Answer
has comment: http://stackoverflow.com/comment/84962460

http://stackoverflow.com/q/48991494
possible better answer: http://stackoverflow.com/a/48991749
linked to: http://stackoverflow.com/q/25642532
type: Question
has title: Program to identify pixel color on mouse click using python Tkinter
has body: I've written a small script in python, so that I can click on the image and the program returns to me the pixel position and the pixel color in BGR of the point where I click on the image. I use the click position to access the image numpy array (via cv.imread). The problem is that the position returned is shifted from the original image. Somehow the actual size of the image gets modified and I get the wrong pixel color or get an index out of bounds. I tried using the same geometry of the original image, but it didn't work. Here's the code: # -*- coding: utf-8 -*- import cv2 as cv import numpy as np import Tkinter as tk from PIL import ImageTk, Image import sys imgCV = cv.imread(sys.argv[1]) print(imgCV.shape) root = tk.Tk() geometry = "%dx%d+0+0"%(imgCV.shape[0], imgCV.shape[1]) root.geometry() def leftclick(event): print("left") #print root.winfo_pointerxy() print (event.x, event.y) #print("BGR color") print (imgCV[event.x, event.y]) # convert color from BGR to HSV color scheme hsv = cv.cvtColor(imgCV, cv.COLOR_BGR2HSV) print("HSV color") print (hsv[event.x, event.y]) # import image img = ImageTk.PhotoImage(Image.open(sys.argv[1])) panel = tk.Label(root, image = img) panel.bind("&lt;Button-1&gt;", leftclick) #panel.pack(side = "bottom", fill = "both", expand = "no") panel.pack(fill = "both", expand = 1) root.mainloop() The test image I used is this: Thanks a lot in advance for any help!
has answer: http://stackoverflow.com/a/48993354
accepted answer: http://stackoverflow.com/a/48993354
answer count: 2
downvote count: 0
favorite count: 0
tagged with: tkinter
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48991749
tagged with: opencv
type: AnsweredQuestion
score: 1

size
type: Tag
tag name: size
tags question: http://stackoverflow.com/q/49098565

http://stackoverflow.com/q/49013956
has body: I have two models. The Course model has a many-to-many field related to the Student model. Problem is, when I iterate through the course.student and iterate trough the students to compare if values are same, there are too many iterations. Basically a list of students is normally displayed in my template, and when I submit the form, the Course.student field is updated by one. So when iteration starts again, there will be 2 students to compare, which will display more students per page each time. I need to find a way to display the checked students just one time, otherwise display the form. {% for crs_stud in course.student.all %} {% for student in students %} {% if crs_stud == student %} &lt;p&gt;{{ student.name.upper }} is already enrolled.&lt;/p&gt; {% else %} &lt;form action="." method="POST"&gt; {% csrf_token %} &lt;label for="id_{{ student.id }}"&gt;{{ student.name }}&lt;/label&gt; &lt;input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids"&gt; &lt;input type="submit"&gt; &lt;/form&gt; {% endif %} {% endfor %} {% endfor %}
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49014402
type: AnsweredQuestion
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/49014402
has title: Iterating over a ManytoMany field and comparing values with another iteration not working as expected
score: 0

http://stackoverflow.com/comment/85068935
score: 0
type: AnswerComment
has text: Before I go any further, I'd like to thank you so much for trying to help me out, even if I'm still experiencing difficulties.
comment on: http://stackoverflow.com/a/49029637
type: Comment

http://stackoverflow.com/comment/85105341
type: Comment
score: 1
has text: Nice, didn't know this was possible without a loop. Is the `os.getcwd() +` necessary though? Surely we just write to current working directory by default if we don't specify.
comment on: http://stackoverflow.com/a/49050472
type: AnswerComment

http://stackoverflow.com/q/48979020
has comment: http://stackoverflow.com/comment/84963769
answer count: 0
has title: TSN scheduling/routing PYTHON library
has comment: http://stackoverflow.com/comment/84964315
tagged with: libraries
type: Question
tagged with: algorithm
tagged with: routes
score: 0
tagged with: scheduling
has body: My question is regarding suggestions for PYTHON libraries about algorithm scheduling mainly, but more specifically about doing scheduling and routing in networks. (Examples of algorithms like: ALAP, ASAP etc. ). My area is TSN (Time-Sensitive Network) and my objective is to design algorithms for scheduling of tasks and finding the routes from point A to B for example. Here is an example for routing: Topology Routing example Here is an example for scheduling: Small scheduling example
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85001878
type: AnswerComment
type: Comment
has text: @OgnjenMišić in general, list-comprehensions are preferred over `map` + `lambda` and `filter` + `lambda`, note, list/generator/set/dict comprehensions are more efficient when you want to map *and* filter at the same time. But in Python, you should only go with these constructs when readable, and don't use side-effects inside of them (... like `print`...)
score: 1
comment on: http://stackoverflow.com/a/48998085

imagemagick
tags question: http://stackoverflow.com/q/49019073
type: Tag
tags question: http://stackoverflow.com/q/49037942
tags question: http://stackoverflow.com/q/49065313
tag name: imagemagick

http://stackoverflow.com/comment/84940623
type: Comment
has text: Correct. Thanks!
comment on: http://stackoverflow.com/a/48967433
score: 0
type: AnswerComment

http://stackoverflow.com/q/49026950
has comment: http://stackoverflow.com/comment/85063789
has answer: http://stackoverflow.com/a/78452919
score: 1
has answer: http://stackoverflow.com/a/65236355
upvote count: 1
type: Question
has body: I'm trying to use a Vte terminal widget to display text from my python script. I'm not setting the working directory or emulator, I just want a empty terminal that handles text and ansi escape sequences I have this piece of code, it works in python 2.7: import gi gi.require_version('Gtk', '3.0') gi.require_version('Vte', '2.91') from gi.repository import Gtk, Vte from gi.repository import GLib import os terminal = Vte.Terminal() terminal.spawn_sync( Vte.PtyFlags.DEFAULT, None, [], [], GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None, ) win = Gtk.Window() win.connect('delete-event', Gtk.main_quit) win.add(terminal) win.show_all() terminal.feed('hello') #string to display Gtk.main() but it doesn't work in python 3.5, all I get is a blank terminal.
has answer: http://stackoverflow.com/a/49059702
answer count: 3
downvote count: 0
tagged with: gtk3
favorite count: 0
has comment: http://stackoverflow.com/comment/85121221
tagged with: python-3.x
type: UnansweredQuestion
has title: Python - How to Write Text to a GTK+ Vte Terminal widget?
tagged with: python

http://stackoverflow.com/a/49031696
type: Answer
has comment: http://stackoverflow.com/comment/85070086
has body: This code will terminate as the function is calld with k-1, meaning that the condition k&gt;1 will eventually evaluate to False. Imagine recursion is like a continually growing tree and a squirrel is the interpreter. When the isort() function is called, the tree branches off and the squirrel runs to the end of that branch. However, the tree uses has a finite supply of nutrients (k) each time, and a bit is used (k-1) each time it grows a new branch. The tree will stop branching off when it runs out of nutrients (which is the k&gt;1 condition). When the tree stops growing, the squirrel will reach the end of the last branch and get the nut (return value/ next line(s) of code). The squirrel will now run back to the roots (the code (if any) after the call to the recursive function) by going back through the branches (leaving each recursion depth). When the squirrel arrives back at the roots, the program is finished. (Hope this analogy helps :) )
answers question: http://stackoverflow.com/q/49031548
has comment: http://stackoverflow.com/comment/85070522
score: 0
accepted answer of: http://stackoverflow.com/q/49031548
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85068254
has comment: http://stackoverflow.com/comment/85069160

http://stackoverflow.com/comment/85194377
type: Comment
type: QuestionComment
score: 0
has text: The point is, I did not use code in QGIS. I used the interface plugin to perform the viewshed analysis.
comment on: http://stackoverflow.com/q/49034457

http://stackoverflow.com/comment/84968670
has text: ah thx! The request is being made now but now I'm getting **error code 500 - internal server error**
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48981746

http://stackoverflow.com/comment/85047520
type: Comment
has text: I tried resultlabel.config(textvariable=Labelvar) and it still gives the same result, the label does not change, and now does not show text at all
score: 1
comment on: http://stackoverflow.com/a/49020771
type: AnswerComment

http://stackoverflow.com/q/49008397
type: Question
downvote count: 2
upvote count: 1
has body: I learned to use java functions before python functions, and generally I make a different classes for different "public static voids" so my main code regroup all of my functions. And when I wanted to do the same and I tried: global def function(): print("String") and def global function(): print("String") and some alternative ways (e.g Make my function in another class, com back in my main and put "global function") but I still can't make global functions... So if anyone has the answer, just tell me!
favorite count: 0
has title: How to import functions from a .py file to another .py file?
has answer: http://stackoverflow.com/a/49009047
has comment: http://stackoverflow.com/comment/85021278
has comment: http://stackoverflow.com/comment/85021752
possible better answer: http://stackoverflow.com/a/49008565
linked to: http://stackoverflow.com/q/27930038
answer count: 3
has comment: http://stackoverflow.com/comment/85021211
has answer: http://stackoverflow.com/a/49008565
has answer: http://stackoverflow.com/a/49008602
accepted answer: http://stackoverflow.com/a/49008602
has comment: http://stackoverflow.com/comment/85022904
tagged with: python
type: AnsweredQuestion
tagged with: java
score: -1

http://stackoverflow.com/a/48989022
type: Answer
score: 3
upvote count: 3
has body: You can use Variable class objects in sync with entry's text, the button is disabled as long as the entry is empty, and enabled when not in the example below: try: import tkinter as tk except ImportError: import Tkinter as tk def toggle_state(*_): if entry.var.get(): button['state'] = 'normal' else: button['state'] = 'disabled' if __name__ == '__main__': root = tk.Tk() entry = tk.Entry(root) entry.var = tk.StringVar() entry['textvariable'] = entry.var entry.var.trace_add('write', toggle_state) button = tk.Button(root, text="Button", state='disabled') entry.pack() button.pack() tk.mainloop()
accepted answer of: http://stackoverflow.com/q/48988799
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48988799

http://stackoverflow.com/comment/84957836
has text: Have you checked `np.where` as suggested here (https://stackoverflow.com/q/41588034/3512538)?
comment on: http://stackoverflow.com/q/48976415
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49042878
tagged with: pip
tagged with: python
has body: When I tried to install mysql in python using this command python -m pip install mysql can anyone help me with this? Collecting mysql Using cached mysql-0.0.1.tar.gz Collecting MySQL-python (from mysql) Using cached MySQL-python-1.2.5.zip Installing collected packages: MySQL-python, mysql Running setup.py install for MySQL-python ... error Complete output from command C:\Users\vishnuvardhan12137\AppData\Local\Programs\Python\Python36-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\VISHNU~1\AppData\Local\Temp\pip-build-lw04ypbu\MySQL-python\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\VISHNU~1\AppData\Local\Temp\pip-0awclynb-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib.win32-3.6 copying _mysql_exceptions.py -> build\lib.win32-3.6 creating build\lib.win32-3.6\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.6\MySQLdb creating build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.6\MySQLdb\constants running build_ext building '_mysql' extension error:…
downvote count: 1
type: AnsweredQuestion
has title: python mysql installation failed
upvote count: 0
possible better answer: http://stackoverflow.com/a/56869542
score: -1
tagged with: mysql
has comment: http://stackoverflow.com/comment/91995990
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49042901
has answer: http://stackoverflow.com/a/56869542
tagged with: database
has comment: http://stackoverflow.com/comment/85091927
has answer: http://stackoverflow.com/a/49042901
linked to: http://stackoverflow.com/q/9077890
favorite count: 0
linked to: http://stackoverflow.com/q/29846087
linked to: http://stackoverflow.com/q/38949519

http://stackoverflow.com/q/49089391
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/85184674
has answer: http://stackoverflow.com/a/49089481
has title: Python How do I search through a dictionary if the the value is a list and I have the first number in the list?
has body: So if I have a dictionary like mydict = {"a":[0,0], "b":[2,1], "c":[2,2], "d":[0,0], "e":[3,1]} How would I search for all keys that the first number in its value is 2 (so I get "b" and "c")?
has answer: http://stackoverflow.com/a/49089484
type: Question
has answer: http://stackoverflow.com/a/49089405
upvote count: 0
score: -2
favorite count: 0
answer count: 3
tagged with: python

http://stackoverflow.com/comment/85185120
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49089744
has text: Can you use `pytest`? If so, this should be easy to do with a [properly scoped fixture](https://docs.pytest.org/en/latest/fixture.html#scope-sharing-a-fixture-instance-across-tests-in-a-class-module-or-session).
type: Comment

http://stackoverflow.com/q/49017738
tagged with: python-3.x
has title: virtual environment not importing packages from virtual environment site-packages in Python 3.6.4
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/85040703
has comment: http://stackoverflow.com/comment/85094167
has comment: http://stackoverflow.com/comment/85040770
has comment: http://stackoverflow.com/comment/85040596
has comment: http://stackoverflow.com/comment/85041516
has comment: http://stackoverflow.com/comment/85120719
has comment: http://stackoverflow.com/comment/85041144
has body: I created a virtual environment (venv64) for python 3.6.4. and installed ujson. It is installed in virtual environment site-packages. But, when I am trying to import ujson in virtual env. It gives me an error: ModuleNotFoundError: No module named 'ujson' When I checked sys.path I got: ['', 'C:\\Python36\\python36.zip', 'C:\\Python36\\DLLs','C:\\Python36\\lib','C:\\Python36', 'C:\\Users\\Khushal Adlakha\\AppData\\Roaming\\Python\\Python36\\site-packages','C:\\Python36\\lib\\site-packages'] Instead it should be: C:\Python36\venv64\Lib\site-packages Why virtual environment is not using it's own site-packages? pip freeze in venv shows: certifi==2018.1.18 chardet==3.0.4 cymem==1.31.2 cytoolz==0.8.2 dill==0.2.7.1 falcon==1.4.1 ftfy==4.4.3 html5lib==1.0b8 hug==2.4.0 hug-middleware-cors==1.0.0 idna==2.6 mmh3==2.5.1 msgpack-numpy==0.4.1 msgpack-python==0.5.4 murmurhash==0.28.0 numpy==1.14.1 pathlib==1.0.1 peewee==2.10.2 plac==0.9.6 preshed==1.0.0 prodigy==1.3.0 pyreadline==2.1 python-mimeparse==1.6.0 regex==2017.4.5 requests==2.18.4 six==1.11.0 spacy==2.0.9 termcolor==1.1.0 thinc==6.10.2 toolz==0.9.0 tqdm==4.19.6 ujson==1.35 urllib3==1.22 waitress==1.1.0 wcwidth==0.1.7 wrapt==1.10.11 Windows 10 64-bit Python 3.6.4 (64-bit)
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48895867
score: 2
answer count: 0
downvote count: 0
tagged with: virtualenv
favorite count: 0

http://stackoverflow.com/q/49054768
score: -1
type: Question
answer count: 2
upvote count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/85114180
tagged with: python
has body: I'm going to optimize three variable x, alpha and R. X is a one dimensional vector, alpha is a two dimensional vector and R is a scalar value. How can I maximize this function? I write below code: #from scipy.optimize import least_squares from scipy.optimize import minimize import numpy as np sentences_lengths =[6, 3] length_constraint=5 sentences_idx=[0, 1] sentences_scores=[.1,.2] damping=1 pairwise_idx=[(0,0),(0,1),(1,0),(1,1)] overlap_matrix=[[0,.01],[.02,0]] def func(x, R, alpha, sign=1.0): """ Objective function """ return sign*(sum(x[i] * sentences_scores[i] for i in sentences_idx) - damping * R * sum(alpha[i][j] * overlap_matrix[i][j] for i,j in pairwise_idx)) x0=np.array([1,0]) R0=.1 alpha0=np.array([1,0,0,0]) def func_deriv(x, R, alpha, sign=1.0): """ Derivative of objective function """ #Partial derivative to x dfdX = sign*(sum(sentences_scores[i] for i in sentences_idx)) #Partial derivative to R dfdR= sign*(- damping * sum(alpha[i][j] * overlap_matrix[i][j] for i,j in pairwise_idx)) #Partial derivative to alpha dfdAlpha= sign*(- damping * R * sum(alpha[i][j] * overlap_matrix[i][j] for i,j in pairwise_idx)) return [ dfdX, dfdR, dfdAlpha] cons = ({'type': 'ineq', ## Constraints: one constraint for the size + consistency constraints #sum(x[i] * sentences_lengths[i] for i in sentences_idx) &lt;= length_constraint 'fun' : lambda x: length_constraint - sum(x[i] * sentences_lengths[i] for i in sentences_idx) , 'jac' : lambda x: [-sum(sentences_lengths[i] for i in sentences_idx), 0, 0]} ,{'type': 'ineq', #alpha[i][j] - x[i] &lt;= 0 'fun' : lambda x: [x[i]-alpha[i][j] for i,j in pairwise_idx], 'jac' : lambda x: [1.0, 0.0, -1.0]} ,{'type': 'ineq', #alpha[i][j] - x[j] &lt;= 0 'fun' : lambda x: [x[j]-alpha[i][j] for i,j in pairwise_idx], 'jac' : lambda x: [1.0, 0.0, -1.0]} ,{'type': 'ineq', #x[i] + x[j] - alpha[i][j] &lt;= 1 'fun' : lambda x: [1+alpha[i][j]-x[i]-x[j] for i,j in pairwise_idx], 'jac' : lambda x: [-1.0-1.0, 0.0, 1.0]}) res = minimize(func, (x0,R0,alpha…
favorite count: 0
has title: multi parameter optimization in python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49228738
downvote count: 1
has answer: http://stackoverflow.com/a/49278751
tagged with: constraints

http://stackoverflow.com/a/48981104
downvote count: 3
accepted answer of: http://stackoverflow.com/q/48980029
answers question: http://stackoverflow.com/q/48980029
upvote count: 0
type: AcceptedAnswer
has body: You can use a try/except block to catch a connection error: try: r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers) except requests.exceptions.ConnectionError: print "Proxy Connection Error" print(r.text) In the code above, if requests.post raises a ConnectionError, the except block will catch it and print out the Proxy Connection Error message.
has comment: http://stackoverflow.com/comment/117435350
score: -3
type: Answer

http://stackoverflow.com/comment/85004865
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48999769
type: Comment
has text: You can just `return x in self.rule.values()` instead of returning returning true in the condition of the statement.

http://stackoverflow.com/comment/85079111
comment on: http://stackoverflow.com/q/49036237
type: Comment
score: 1
has text: @ColinBlyth It's not quite reasonable to have different data types in the same column, and this usually makes further analysis and processing difficult. Is there a reason that you want to put them in the same column?
type: QuestionComment

web.py
tags question: http://stackoverflow.com/q/48988022
type: Tag
tag name: web.py

http://stackoverflow.com/comment/85175472
has text: Ahhh... (tips hat)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49084969
type: Comment

http://stackoverflow.com/q/49065265
has comment: http://stackoverflow.com/comment/85136078
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/13909536
tagged with: jupyter-notebook
has body: I am using Jupyter Console for python programming. Sometimes I do a lot of things in the same session. It happens that I define a class in the earlier part of the session and later want to see the class definition. Is there any way to do it?
tagged with: python
has title: How to see a class definition in python while using Jupyter Console?
accepted answer: http://stackoverflow.com/a/49065465
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49065465
type: Question

http://stackoverflow.com/comment/85100934
has text: This does the work but it is very inaccurate, sometimes the time delta is about 80-120ms. Something more accurate is needed.
comment on: http://stackoverflow.com/a/49047758
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49089262
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/85187100
has comment: http://stackoverflow.com/comment/85186957
answers question: http://stackoverflow.com/q/49088785
has comment: http://stackoverflow.com/comment/85184403
accepted answer of: http://stackoverflow.com/q/49088785
has comment: http://stackoverflow.com/comment/85187011
type: AcceptedAnswer
downvote count: 0
has body: You cannot change the color of the menubar on Windows or OSX. It might be possible on some window managers on linux, though I don't know for certain. The reason is that the menubar is drawn using native widgets that aren't managed by tkinter, so you're limited to what the platform allows.
type: Answer

http://stackoverflow.com/q/48981145
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48981309
accepted answer: http://stackoverflow.com/a/48981309
tagged with: django-rest-framework
score: 0
answer count: 1
has body: My view class looks like, views.py class UserHierarchyOfOrganizations(viewsets.GenericViewSet, mixins.ListModelMixin): serializer_class = UserListOrganizationHierarchySerializer def get_queryset(self): user_ids = map(int, self.request.query_params['users'].split(',')) return User.objects.filter(id__in=list(user_ids)).select_related('organization') serializers.py class UserOrganizationHierarchySerializer(serializers.ModelSerializer): # user_ids = serializers.ListField( # child=serializers.IntegerField(min_value=1, validators=[] # ), required=True # ) # user_id = serializers.IntegerField(min_value=1, read_only=True) # organizations = OrganizationReadOnlySerializer(read_only=True) class Meta: model = User fields = ('pk',) # read_only_fields = ('organizations','user_id') def to_representation(self, instance): out = super().to_representation(instance) print(out) out = OrganizationReadOnlySerializer(instance.organization).data print (out) return out class UserListOrganizationHierarchySerializer(serializers.ModelSerializer): # organization_hierarchy = serializers.ReadOnlyField() #organization_hierarchy = serializers.ListField(child=UserOrganizationHierarchySerializer(read_only=True)) organization_hierarchy = serializers.SerializerMethodField('_get_org_hierarchy') def _get_org_hierarchy(self, obj): print (type(obj)) serializer = UserOrganizationHierarchySerializer(obj, many=True) return serializer.data class Meta: model = User fields = ('organization_hierarchy',) read_only_fields = ('organization_hierarchy',) def to_representation(self, instance): out = super().to_representation(instance) return out But I'm getting single User instance in _get_org_hierarchy and to_representation methods instead of multiple User instances. Is there any way to get multiple instances of User class(see get_queryset method) in UserListOrganizationHierarchySerializer serializer? What I'm trying to achieve is, { "organization_hierarchy": [ {"id": 1, "organizations": "foo -&gt; bar"}, ] }
has title: Django drf serializer can't get multiple instances in to_representation
has comment: http://stackoverflow.com/comment/84967488
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84967578

http://stackoverflow.com/comment/85051880
comment on: http://stackoverflow.com/q/49023563
type: QuestionComment
score: 2
has text: Rather than making us scroll through loads of useless code, post a minimal, reproducible, example that demonstrates your issue as succinctly as possible. And while you're at it, please ask a specific question about the code.
type: Comment

http://stackoverflow.com/comment/85252058
type: AnswerComment
comment on: http://stackoverflow.com/a/49121348
score: 0
type: Comment
has text: The error you get looks like a [warning in metrics](https://stackoverflow.com/questions/47635510/strange-spark-error-on-aws-emr) that doesn't affect spark data processing. If you are using AWS EMR then should try to downgrade it to 5.9.0 or just suppress the warning.

http://stackoverflow.com/q/49002647
tagged with: python
score: -1
type: AnsweredQuestion
has body: My goal is to try to return all the value in the list which has even position as well. The following is my python code. I don't know which part should I update. Please help!! Thanks def evenValue(numbers): results = [] for x in numbers: if results.index(x) %2 ==0: results.append(x) return results My error message is &gt; Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 1, in &lt;module&gt; evenValue([1,2,3,4,5,6]) File "&lt;pyshell#6&gt;", line 4, in evenValue if results.index(x) %2 ==0: ValueError: 1 is not in list
tagged with: list
has answer: http://stackoverflow.com/a/68657154
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/49002689
type: Question
possible better answer: http://stackoverflow.com/a/49002715
has answer: http://stackoverflow.com/a/49002715
has title: Python list as function argument
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/49002689

http://stackoverflow.com/q/49090572
answer count: 1
has body: I am able to open the dropdown menu however I am unable to click any option on the dropdown menu. This is the error I get: selenium.common.exceptions.NoSuchElementException: Message: no such element: `Unable to locate element: {"method":"xpath","selector":"//*[@id="j_c40"]/li[3]"}` This works fine by opening the dropdown menu: self.driver.find_element_by_xpath("//span[@class='va-sm-m']").click() This should press an option from the dropdown but gives me an error. self.driver.find_element_by_xpath('//*[@id="j_c40"]/li[3]').click() The code from the site from where I want to select looks like this: EU M 39 / W 39 What am I doing wrong here? Full code: self.driver.get("https://www.nike.com/de/launch/") ui.WebDriverWait(self.driver, 100).until(EC.visibility_of_element_located((By.ID, "cookie-settings-layout"))) element = self.driver.find_element_by_xpath('//*[@id="cookie-settings-layout"]/div/div/div/div[3]/div[2]/div').click() time.sleep(5) self.driver.find_element_by_xpath("//span[@class='va-sm-m']").click() time.sleep(5) self.driver.find_element_by_xpath('//*[@id="j_c40"]/li[3]').click() Here is the link from the dropdown: https://www.nike.com/de/launch/t/air-vapormax-utility-black-orange-peel
has comment: http://stackoverflow.com/comment/85186898
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49093153
accepted answer: http://stackoverflow.com/a/49093153
has comment: http://stackoverflow.com/comment/85186834
tagged with: selenium
has comment: http://stackoverflow.com/comment/85186769
type: Question
has title: Selenium Python: How to select item from a dropdown
score: 0
has comment: http://stackoverflow.com/comment/85186854
has comment: http://stackoverflow.com/comment/85186965

http://stackoverflow.com/comment/84934212
comment on: http://stackoverflow.com/q/48964009
type: Comment
type: QuestionComment
has text: Its difficult to say without your code. Is there a step in pipeline where computation happens in CPU? For example, you could have data pre processing step, where operations are run on CPU.
score: 0

http://stackoverflow.com/q/49053131
favorite count: 0
tagged with: vtk
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/49053132
upvote count: 2
type: UnansweredQuestion
has title: Failure installing VTK from PyPI on x86_64
tagged with: pip
type: Question
downvote count: 0
answer count: 1
has body: I know that VTK is now available as a wheel in PyPI (https://pypi.python.org/pypi/vtk/8.1.0) but I am not able to install it. Is there a way around this? When I try this is what I get: $ pip install vtk Collecting vtk Could not find a version that satisfies the requirement vtk (from versions: ) No matching distribution found for vtk I have tried pointing to the wheel's URL but still the same problem. $ pip install https://pypi.python.org/packages/13/7f/735fbc0dd78c91ad3693cfdfe5c91603899fc8e24909f935d46d2fde6559/vtk-8.1.0-cp27-cp27mu-manylinux1_x86_64.whl#md5=49c8d620b2affe2dc2284048659115e5 vtk-8.1.0-cp27-cp27mu-manylinux1_x86_64.whl is not a supported wheel on this platform. Here is my platform information: $ uname -a Linux [hostname-withheld] 3.10.0-514.16.1.el7.x86_64 #1 SMP Fri Mar 10 13:12:32 EST 2017 x86_64 x86_64 x86_64 GNU/Linux

http://stackoverflow.com/q/49105196
favorite count: 0
tagged with: typeerror
tagged with: python
tagged with: lambda
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49105279
upvote count: 1
type: Question
has title: Why am i getting the TypeError?
score: 1
has body: Sorry before hand if this is a silly question, but I tried to figure out and unable to get it through I have a dictionary named data of pandas dataframe, where data['class_size'] has the following data CSD SCHOOL CODE SCHOOL NAME 1 M015 P.S. 015 Roberto Clemente 1 M019 P.S. 019 Asher Levy 1 M019 P.S. 019 Asher Levy . .... .......... . .... .......... and many more and i tried the following lambda function as pandas.apply() a parameter to pad the CSD column with 0 if its length is 1 data['class_size']['padded_csd'] = data["class_size"]["CSD"].apply(lambda x: str(x).zfill(2) if len(str(x)) == 1 else x ) That did worked fine, but after using the concatenation, i.e. data['class_size']['DBN'] = data['class_size']['padded_csd'] + data['class_size']['SCHOOL CODE'] I am getting the TypeError of unsupported operand type(s) for '+' 'int' and'str' I even checked the type of both the columns "padded_csd" and "SCHOOL CODE", they both are strings then why is a TypeError there? Thanks in advance for any help P.S. I know i can create a function and use there instead of the lambda and it is even working but for some reasons I really have to use the lambda function
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49105279

http://stackoverflow.com/q/48999493
tagged with: histogram
tagged with: filter
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49000203
has title: Converting OpenCV histogram to curve and vise versa
favorite count: 0
score: -1
type: Question
downvote count: 2
tagged with: python
answer count: 1
has body: Using OpenCV in python, I got the histogram of one channel in an image, Can I convert it to a curve so as to multiply this new curve with another curve then return the output curve to a histogram to act as a filter on my image?
tagged with: opencv
accepted answer: http://stackoverflow.com/a/49000203
upvote count: 1
tagged with: curve

http://stackoverflow.com/q/49033360
possible better answer: http://stackoverflow.com/a/49033452
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49033452
has comment: http://stackoverflow.com/comment/85071590
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49033596
tagged with: python
has body: I have the following code that when run produces identical matrices but I want it to generate a different matrix each time. I believe there is a problem with the sample method from random but am unsure on how to fix it. I also tried creating a random object and using sample with that but it had the same effect. The aim of the createIndividual function is to take the grid given and fill each row with a permutation of 1-9, however the rows come with some pre-fixed values that should not be repeated. This function works. However when calling it multiple times with the createPopulation function it returns identical matrices each time when I want each one to be unique. from random import sample POPULATION_SIZE = 10 prefill = [[4,0,0,1,0,2,6,3,0], [5,0,0,6,4,3,8,0,0], [7,6,0,5,0,8,4,1,2], [6,0,0,0,0,9,3,4,8], [2,4,0,8,3,0,9,5,0], [8,0,9,4,1,5,0,7,0], [0,7,2,0,0,4,0,6,0], [0,5,4,2,0,0,0,8,9], [0,8,6,3,0,7,1,2,4]] def createPopulation(grid): result = [] for i in range(POPULATION_SIZE): result.append(createIndividual(grid)) return result def createIndividual(grid): ''' Populates each row with random permuations from 1-9 avoiding duplicates. ''' for i in range(len(grid)): permutation = [1, 2, 3, 4, 5, 6, 7, 8, 9] temp = set() for j in range(len(grid)): # Remove pre existing if grid[i][j] != 0: permutation.remove(grid[i][j]) temp.add(j) for j in range(len(grid)): # Randomly fill in blanks if grid[i][j] == 0: n = sample(permutation, 1)[0] permutation.remove(n) grid[i][j] = n return grid pop = createPopulation(prefill) for i in pop: print(i)
type: AnsweredQuestion
has title: Python random generating identical matrices
has answer: http://stackoverflow.com/a/49033596
has comment: http://stackoverflow.com/comment/85071743

http://stackoverflow.com/q/49007346
has comment: http://stackoverflow.com/comment/85175544
score: -3
downvote count: 4
linked to: http://stackoverflow.com/q/43018030
answer count: 1
has title: Convert the word " I'm" to "I am" using python
tagged with: string
linked to: http://stackoverflow.com/q/5658369
has comment: http://stackoverflow.com/comment/85020009
has comment: http://stackoverflow.com/comment/127941341
favorite count: 0
has body: Convert the word " I'm" to "I am" and similarly "How're" to "How are" using python. I used lemmatization for this but did not get adequate results. I used the following code: sen="You are great, My Lord. I'm studying with co-workers. How're you?" all_words=regexp_tokenize(sen, "[\w']+") lemmatiser = WordNetLemmatizer() all_words_lem=[] for i in all_words: x=lemmatiser.lemmatize(i, pos="v") all_words_lem.append(x)
accepted answer: http://stackoverflow.com/a/49007514
tagged with: python
tagged with: nlp
type: AnsweredQuestion
upvote count: 1
type: Question
tagged with: nltk
has answer: http://stackoverflow.com/a/49007514

http://stackoverflow.com/comment/85014557
type: QuestionComment
comment on: http://stackoverflow.com/q/49004835
has text: Well, the `mse_path_` attribute provides the MSE across the different alphas that were tested during the modeling process. You would have to find what alpha was selected by the model and then find the corresponding MSE for that alpha value. As for the negative value of MSE, that's just how the developers designed it. That's why the scoring is called `neg_mean_squared_error`. In previous versions of sklearn, the `neg` was not in the scoring description which resulted in confusion for users.
score: 0
type: Comment

http://stackoverflow.com/q/48971247
has comment: http://stackoverflow.com/comment/84947708
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84947876
upvote count: 2
has body: I'm learning python and wanted to use multidimensional array like we use in c and researched about it and have written the code but stuck at one place and I don't understand why the error is occurring. My Code:- a=[] i=0 for record in tablerows: a.append([]) rowcells=record.findAll('td') for data in rowcells[1:4]: a[i].append(data.text) i=i+1 print(a) Error: a[i].append(data.text) IndexError: list index out of range. On second iteration. Can you please guide me...? And I'm doing it right or is there a better way of doing it....?
has comment: http://stackoverflow.com/comment/84947834
has answer: http://stackoverflow.com/a/48971391
has comment: http://stackoverflow.com/comment/84947867
has comment: http://stackoverflow.com/comment/84947945
has comment: http://stackoverflow.com/comment/84947778
type: Question
has comment: http://stackoverflow.com/comment/84947813
has comment: http://stackoverflow.com/comment/84947812
has comment: http://stackoverflow.com/comment/84947853
has comment: http://stackoverflow.com/comment/84947863
has comment: http://stackoverflow.com/comment/84947823
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84947864
linked to: http://stackoverflow.com/q/2574636
favorite count: 0
has title: Multidimensional Array : index out of range
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/84947799
accepted answer: http://stackoverflow.com/a/48971391
tagged with: python

http://stackoverflow.com/comment/85036565
comment on: http://stackoverflow.com/q/49015697
type: Comment
type: QuestionComment
has text: @user2314737,how? by OpenCV?
score: 0

http://stackoverflow.com/comment/84946975
comment on: http://stackoverflow.com/q/48970752
score: 0
has text: I don't think so. You will have to use loop.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48992041
has body: It is fine for small programs or prototypes but it is bad for large and complex projects. In case of long lines you can use \ for move to the next line (but flake8 will give out warnings about the empty space before [): self.data \ ["data"] \ ["someComponent"] \ ["items"] \ [1] \ ["content"] \ ["items"].append(json.load(someVariable)) In serious projects, you should use other data structures. For example, the composition of objects of different classes, which forms the tree you need. Create a class for each entity in your dictionary structure. For example, the Data class, which contains fields someComponent and, for example, someOtherComponent. Create class Component, which contains field items as list or make Component iterable (define method __iter__() and optionally method __getitem__(index)). And so on. And access to it's fields as: self.data.someComponent[1].content.append(myNewContentElement) To get myNewContentElement from json you can create function which takes loaded JSON structure and returns ContentElement object for you.
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/85014703
has comment: http://stackoverflow.com/comment/85027686
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48990825
upvote count: 3
answers question: http://stackoverflow.com/q/48990825
type: Answer

http://stackoverflow.com/a/49074693
type: Answer
answers question: http://stackoverflow.com/q/49073975
upvote count: 1
score: 1
downvote count: 0
has body: I see some incorrect syntax in CMD, please use this: CMD ["uwsgi", "--http", " :8000" , "--wsgi-file", "falconapp.wsgi"] some double quotes are incorrect and -- is not before wsgi-file .
has comment: http://stackoverflow.com/comment/85159386

http://stackoverflow.com/a/49071382
answers question: http://stackoverflow.com/q/49071167
type: Answer
has comment: http://stackoverflow.com/comment/85474758
has comment: http://stackoverflow.com/comment/85474790
has body: Your problem lies in the way you are trying to define yy; you can't call your function on the list x. Instead, call it on each individual item in x, for instance, in a list iteration like this: yy = [exponenial_func(i, *popt) for i in x] Then, everything else in your code works fine: [EDIT]: to extrapolate the zero in your exponential function (as per your comment), you can do this: xx = x.copy() yy = [exponenial_func(i, *popt) for i in [0]+xx] plt.plot(x,y,'o',[0]+xx,yy) Or, to just see the value, do this: exponenial_func(0, *popt)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49071167
score: 0

http://stackoverflow.com/comment/84965271
type: QuestionComment
comment on: http://stackoverflow.com/q/48977889
has text: Yes. Actually, when the workers reach the maximum number of requests they all reloaded at max-request and no worker keeps processing the requests until max-requests-delta.
score: 0
type: Comment

http://stackoverflow.com/comment/85142805
score: 3
has text: @Calaf C++ does not have default-generated comparison operators (yet?). I believe you're mixing it up with the assignment operators.
comment on: http://stackoverflow.com/q/49062365
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49020080
has body: The goal is to make a Pandas Series where every element is a variable-length numpy array. These arrays come from a function getContexts, which gets the masked results of one dataframe cnv and applies it to another dataframe exp. This is done twice: once for the True (loss), and once for the False (no_loss) condition. The error I get is ValueError: setting an array element with a sequence occurring at the second line in getContexts. Here is are some test data to try out: deldf = pd.DataFrame([[0,1,0,1], [1,0,1,0], [1,1,1,0]]) deldf.columns = ['a','b','c','d'] deldf['cnv'] = ['k','l','m'] deldf.set_index(deldf['cnv'], inplace=True, drop=True) del deldf['cnv'] d_mask = deldf == 1 expdf = pd.DataFrame([[0,2,1,4,np.array([1,1,1])], [10,0,12,1,np.array([2,2,2])], [1,1,1,1,np.array([3,3,3])]]) expdf.columns = ['a','b','c','d','arr'] expdf['exp'] = ['x','y','Z'] expdf.set_index(expdf['exp'], inplace=True, drop=True) del expdf['exp'] results = pd.DataFrame(dels.index) results['exp'] = expdf.index results.columns = ['cnv','exp'] Here is my attempt at the solution (note that d_mask is a global variable): def getContexts(exp_g, cnv_gm): lossTrue = d_mask.loc[cnv_g] # error is thrown at line below loss = np.array(expdf.loc[exp_g].where(lossTrue, np.nan).dropna()) no_loss = np.array(expdf.loc[exp_g].where(~lossTrue, np.nan).dropna()) return loss, no_loss Here is my call to getContexts: results['loss'], results['no_loss'] = np.vectorize(getContexts)(results['exp'], results['cnv']) The end result should look like the dataframe below, so that I can check variance, length, mean, and effect-size on the two columns of arrays.
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/85067524
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49091752
has title: ValueError when filling pandas dataframe cell with Numpy array
score: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85045510
tagged with: arrays

http://stackoverflow.com/q/48967664
tagged with: sympy
tagged with: symbolic-math
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48968421
tagged with: python
has body: Given equation x + y + z = 1 y = x Then we can expression z = 1 - 2x And also this is valid as well z = 1 - 2y I hope to write this two equations in Sympy and z is only expressed in x. I know I can get this done by adding y as an unknown as well. I just don't want to use that because I have equations got too many redundant variable that I don't want to write ALL of those variable as output
has answer: http://stackoverflow.com/a/49249411
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has title: How to use Sympy symbolically solve equation using the only variable I design
answer count: 2

http://stackoverflow.com/q/48975347
has comment: http://stackoverflow.com/comment/84955897
tagged with: python
has comment: http://stackoverflow.com/comment/84955796
type: AnsweredQuestion
has body: I'm reading a JSON with: # coding: utf8 import urllib2 import json response = urllib2.urlopen('https://example.com/test.json') data = json.load(response) print data['mykey'] # {u'readme': u'Caf\xe9'} but I see two things: Every string is prefixed with u, i.e. type 'unicode' \xe9 instead of é How to do this properly with Python 2.7?
has comment: http://stackoverflow.com/comment/84956279
type: Question
tagged with: urllib2
score: -2
linked to: http://stackoverflow.com/q/48975692
answer count: 1
has title: Reading JSON from urllib2.open and UTF8 characters
accepted answer: http://stackoverflow.com/a/48975380
tagged with: unicode
tagged with: python-2.7
downvote count: 2
tagged with: utf-8
has answer: http://stackoverflow.com/a/48975380
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/84956105

http://stackoverflow.com/comment/85021134
type: Comment
type: QuestionComment
has text: I created a code like below, `from Tkinter import * root=Tk() root.geometry("900x650+220+20") page1=Frame(root) Entry1=Entry(page1) Entry1.place(x=400, y = 150)` In this case i don't see any output, may i know why? `Entry1=Entry(root) Entry1.place(x=400, y = 150)` In this case i see output, may i know how it's happening
comment on: http://stackoverflow.com/q/49007295
score: 0

http://stackoverflow.com/comment/85188802
has text: and i initialize my iniNumTower = 3
score: 0
comment on: http://stackoverflow.com/q/49091621
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49040511
upvote count: 1
answers question: http://stackoverflow.com/q/49040487
has body: Here is one way: def list3(a,b,c): """if all inputs are int/float return average""" l = [a, b, c] return sum(l)/len(l) if all(isinstance(t, (int, float)) for t in l) else l list3(1, 2, 6) # 3.0 list3('a', 1, 2) # ['a', 1, 2] Explanation all(criteria for t in l) applies a lazy function all on a generator expression, which checks if all items in l are integers or floats. isinstance is generally preferred to checking type. The if / else clause can be replaced by a ternary statement.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/85107682
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49051111
type: QuestionComment
has text: What evidence do you have that the click is happening before all of the keys have been entered? It seems unlikely that `send_keys` would return before it finished. For example, have you tried getting the value of the element right before clicking, to see what the browser returns? Could it be that you have some javascript attached to the input element that is causing some sort of delay?

http://stackoverflow.com/q/49079377
score: 0
has comment: http://stackoverflow.com/comment/85165047
has title: Django + Redis + Celery Struggle to set the tasks
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85165764
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85165115
has comment: http://stackoverflow.com/comment/85193940
answer count: 0
tagged with: django-celery
tagged with: celery
type: Question
has body: I have been trying to set up my scheduled task to run every x minutes, but I am not making any progress. I read the documentation and tried different approaches to the problem but I am obviously still doing something wrong. celery.py CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/1' from datetime import timedelta from celery import Celery app = Celery('taskscheduler', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND) app.autodiscover_tasks() CELERYBEAT_SCHEDULE = { 'schedule-name': { 'task': 'taskscheduler.task.just_print', 'schedule': timedelta(seconds=5), }, } task.py from celery import shared_task @shared_task def just_print(): print("Print from celery task") __init__.py 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 taskscheduler.celery import app as celery_app __all__ = ['celery_app'] All of the files are inside one of the many apps folders. What I am trying to achieve is basically to set up this task when I start the server and run it every x seconds, as long as the server is on. Small Update I changed my files a little to: celery.py from __future__ import absolute_import CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/1' from django.apps import apps from datetime import timedelta from celery import Celery from celery.task.base import periodic_task CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" app = Celery('taskscheduler', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND) app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()]) @periodic_task(run_every=timedelta(seconds=5)) def just_print(): print("Print from celery task") When the function is in celery.py rather than task.py all works fine. However, I want to do it the proper way and make it available from task.py
has comment: http://stackoverflow.com/comment/85641836

http://stackoverflow.com/comment/84939919
type: AnswerComment
score: 0
type: Comment
has text: @Micawber `__wrapped__` is only an attribute in Python3.
comment on: http://stackoverflow.com/a/48967004

http://stackoverflow.com/a/58126417
upvote count: 13
type: Answer
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/135310015
accepted answer of: http://stackoverflow.com/q/49047402
answers question: http://stackoverflow.com/q/49047402
has comment: http://stackoverflow.com/comment/103596042
type: AcceptedAnswer
has body: I had this same issue and wished glob.glob had an optional parameter to include dot files. I wanted to be able to include ALL dot files in ALL directories including directories that start with dot. Its just not possible to do this with glob.glob. However I found that Python has pathlib standard module which has a glob function which operates differently, it will include dot files. The function operates a little differently, in particular it does not return a list of strings, but instead path objects. However I used the following files=[] file_refs = pathlib.Path(".").glob(pattern) for file in file_refs: files.append(str(file)) The other noticeable difference I found was a glob pattern ending with **. This returned nothing in the pathlib version but would return all the files in the glob.glob one. To get the same results I added a line to check if the pattern ended with ** and if so then append /* to it. The following code is a replacement for your example that include the files in directories starting with dot import pathlib for fileref in pathlib.Path('/path/').glob('**/*.ext'): filename = str(fileref) print(filename)

http://stackoverflow.com/comment/84997330
comment on: http://stackoverflow.com/q/48995891
has text: @juanpa.arrivillaga, I have other software which relies on Python 2. However, from what I know, both Python 2 and 3 can be setup on the same machine without too much contention. If you feel like this can be much more easily accomplished using Python 3, then I am open to that.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85078938
score: 0
type: Comment
has text: I would recommend that you post another question with the details of that function.. creating a list of tuples from a CSV is pretty straightforward
comment on: http://stackoverflow.com/a/49036612
type: AnswerComment

http://stackoverflow.com/comment/85202565
score: 0
type: AnswerComment
type: Comment
has text: I have now got to the bottom of this mystery, and I am still in need of help. I wrote several search and sort algorithms that night from pseudocode, and while trying to understand one, got myself in a knot, named it incorrectly, and then posted a similar one (that I understood) to the forum. I don’t want to adjust my original question, (well I do!) but that would make the responses inaccurate. I have therefore posted a second question in hope that those of you that responded to this one, will have a look at my ‘actual query’. Thanks Mr__D
comment on: http://stackoverflow.com/a/49079023

http://stackoverflow.com/comment/85063404
comment on: http://stackoverflow.com/a/49029642
type: AnswerComment
score: 0
type: Comment
has text: Thanks so much, I don't see why you changed from a two-dimensional optimisation problem to a one-dimensional one. Could you please give some explanations ?

http://stackoverflow.com/a/49020771
has comment: http://stackoverflow.com/comment/85048006
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85047520
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49020380
has comment: http://stackoverflow.com/comment/85047616
has body: The problem is at resultlabel.config(text=Labelvar) as text parameter requires a string, but if you pass something else (not sure though) such as StringVar, the label will grab what you passed and apply str() to it. To solve this from tkinter import * kb = Tk() def run(): if var1.get() == "A": Labelvar.set("Label updated") resultlabel.config(textvariable=Labelvar) return Labelvar = StringVar() var1 = StringVar() var1.set("A") resultlabel = Label(kb, textvariable=Labelvar) menu = OptionMenu(kb, var1, "A", "B", "C") generate = Button(kb, text="Go", command=run) menu.grid(row=1, column=2) generate.grid(row=4, column=2, sticky=W) resultlabel.grid(row=5, column=1) #This two methods are simply for testing purposes. It works. run() kb.mainloop()

http://stackoverflow.com/a/49020073
upvote count: 4
answers question: http://stackoverflow.com/q/49019716
type: AcceptedAnswer
downvote count: 0
has body: I'm pretty sure that all the following does: for i in range(71): # generate a number from 1 to the end of all transcripts random_number = randint(1, end_pos_last_gene) # this is the boolean condition - checks which gene a random number falls within mask = (df['start'] &lt;= random_number) &amp; (df['end'] &gt;= random_number) # collect the rows that match data = df.loc[mask] # write data to file. data.to_csv(outfile, sep='\t', index=False, header=False) Is select 71 random rows from the data-frame without replacement. Note, this is taking forever because each time you do (df['start'] &lt;= random_number) &amp; (df['end'] &gt;= random_number) You iterate through the entire data-frame three times, and then an additional time when you do: data = df.loc[mask] This is an incredibly inefficient way to sample rows. You could do this much more efficiently by randomly sampling 71 indices, then using those indices directly on the data-frame (which would not require even a single full pass over the data-frame). But you don't need to do that, pd.DataFrame objects already implement an efficient sample method, so observe: In [12]: df = pd.DataFrame(np.random.randint(0, 20, (10, 10)), columns=["c%d"%d for d in range(10)]) In [13]: df Out[13]: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 0 13 0 19 5 6 17 5 14 5 15 1 2 4 0 16 19 11 16 3 11 1 2 18 3 1 18 12 9 13 2 18 12 3 2 6 14 12 1 2 19 16 0 14 4 17 5 6 13 7 15 10 18 13 8 5 7 19 18 3 1 11 14 6 13 16 6 13 5 11 0 2 15 7 11 0 2 7 0 19 11 3 19 3 3 9 8 10 8 6 8 9 3 12 18 19 8 11 2 9 8 17 16 0 8 7 17 11 11 0 In [14]: df.sample(3, replace=True) Out[14]: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 0 13 0 19 5 6 17 5 14 5 15 3 2 6 14 12 1 2 19 16 0 14 3 2 6 14 12 1 2 19 16 0 14 In [15]: df.sample(3, replace=True) Out[15]: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 9 8 17 16 0 8 7 17 11 11 0 4 17 5 6 13 7 15 10 18 13 8 2 18 3 1 18 12 9 13 2 18 12 In [16]: df.sample(3, replace=True) Out[16]: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 3 2 6 14 12 1 2 19 16 0 14 8 6 8 9 3 12 18 19 8 11 2 4 17 5 6 1…
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49019716

http://stackoverflow.com/q/49027846
score: 1
accepted answer: http://stackoverflow.com/a/49028512
tagged with: dataframe
type: Question
tagged with: export-to-csv
has body: Problem I'm reading in multiple csv which match a certain pattern, concatenating them into a dataframe and doing some processing within the frame (e.g. fill datetime gaps, build averages etc.). In the next step I try to unstack the dataframe, and write them into seperate csv files(name them as the imported files + extension) to same directory where they were imported from. The concatenated processed dataframe looks as follows: Datetime Value 0 2017-03-03 12:15:00 2.3 1 2017-03-03 12:30:00 2.1 ... n 2017-12-19 12:15:00 5.3 0 2017-05-03 12:15:00 1.3 1 2017-05-03 12:30:00 3.1 ... m 2017-12-19 12:15:00 7.3 ... My code so far: import os import glob import pandas as pd pattern = "*whatever*.csv" directory_path = "mypath" files = glob.iglob(directory_path + '/**/' + pattern, recursive=True) def get_files(): dfs = (pd.read_csv(filename) for filename in files) df = pd.concat(dfs) def process_df(): .... # do some processing return processed_df '''this part of code does basically what i want''' def write_to_csv() dict_ = {} for filename in files: dict_[file] = pd.read_csv(file) for file in dict_: with open(os.path.splitext(file)[0] + "_gaps_filled.csv", 'w') as f: dict_[filename].to_csv(f, sep=',', index=False, header=False) The def write_to_csv() does basically want I want for not concatenated / processed data. Question How can split/unstack the concatenated processed dataframe, assign the correct filename to the unstacked/splitted chunk and write it to a csv file in a loop? *Desired Resulut Read in matched csv files into dataframe--->process dataframe--->write processed chunks to the corresponding csv filename and directory a.csv a some data a_pro.csv b.csv to df-------&gt; some data process---&gt;[] to_csv--&gt; b_pro.csv c.csv ... c_pro.csv b some data some data ... c some data some data ... My Approach I tried to set keys (pd.concat(dfs, keys=filenames) so I can assign the filename to corresponding chunk in the concatenated dataframe. But in my def process_df() function i…
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: python
has title: Unstack/split dataframe and write parts/chunks of dataframe to multiple csv's assigned to keys
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49028512

http://stackoverflow.com/q/49054273
downvote count: 0
has comment: http://stackoverflow.com/comment/85113355
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/41079054
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85113264
has comment: http://stackoverflow.com/comment/85113135
type: Question
has body: Can anybody explain why, when testing if no-value ("") is contained within a string or if a string startswith no-value (""), the returned value is True. As in: &gt;&gt;&gt; if "" in "L": print ("YES") ... YES &gt;&gt;&gt; if "" in " ": print ("YES") ... YES &gt;&gt;&gt; if "" in "abc": print ("YES") ... YES &gt;&gt;&gt; if "abc".startswith(""): print (True) ... True https://docs.python.org/3/library/stdtypes.html#truth-value-testing 4.6.1. Common Sequence Operations states x in s True if an item of s is equal to x, else False 4.7.1. String Methods str.startswith(prefix[, start[, end]]) Return True if string starts with the prefix, otherwise return False. I really want to know if I can rely on this behaviour as I came across it with the following code: sub_choices = [c for c in self.choices if Input_Text.casefold() in c.casefold()] and sub_choices = [c for c in self.choices if c.casefold().startswith(Input_Text.casefold())] in this case if Input_Text was blank, sub_choices (by happy accident) was the entire contents of self.choices
has title: Testing if a string contains or startswith "no-value" ("")
duplicate of: http://stackoverflow.com/q/41079054

http://stackoverflow.com/q/49076437
has answer: http://stackoverflow.com/a/49076563
tagged with: list-comprehension
upvote count: 1
answer count: 1
has title: Replacing List value using dictionary that contains an underscore
favorite count: 0
has comment: http://stackoverflow.com/comment/85158861
has body: I am trying to use a dictionary to replace usernames with their real names. For example, if the input is "bob2000", the dictionary will replace the list value as "Bob Doe". However, I am getting an problem with a username with an underscore. The value does not get changed. For example, my_dict = { 'bob2000':'Bob Doe', 'bob_2001':'Bob Smith'} Returns: my_list = ['Bob Doe', 'bob_2001'] The value is simply getting skipped over. My code is shown below. def name_replace(my_list): data = [my_dict.get(item,item) for item in my_list] return (data)
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: list
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85158844
type: Question

http://stackoverflow.com/q/49042729
has comment: http://stackoverflow.com/comment/85090720
tagged with: pandas
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49044244
type: UnansweredQuestion
downvote count: 1
tagged with: dataframe
score: -1
tagged with: slice
type: Question
has comment: http://stackoverflow.com/comment/85100963
has title: dataframe Can I extract the pure values in the list properly?
has body: I am currently a Python self-educating beginner. for index, row in df_price.iterrows(): prod_weight = prod_weight = prod_data.loc[prod_data['sku'] == row['sku']]['weight'].item ------result -------------------------------------- &lt;bound method IndexOpsMixin.item of 18066 0.2 Name: weight, dtype: float64&gt; &lt;bound method IndexOpsMixin.item of 18063 0.1 Name: weight, dtype: float64&gt; &lt;bound method IndexOpsMixin.item of 18064 0.1 Name: weight, dtype: float64&gt; &lt;bound method IndexOpsMixin.item of Series([], Name: weight, dtype: float64)&gt; &lt;bound method IndexOpsMixin.item of 18062 0.1 Name: weight, dtype: float64&gt; &lt;bound method IndexOpsMixin.item of 18058 0.1 Name: weight, dtype: float64&gt; &lt;bound method IndexOpsMixin.item of 18059 0.1 --------------------------------------------------------- The result I want is: 1.0 0.2 0.1 0.1 0.1 0.1 0.1 ... 0.5 0.6 0.3 so,I changed the code as follows. prod_weight = prod_data.loc[prod_data['sku'] == row['sku']]['weight'].item() -------------result-------------------------------- 1.0 0.2 0.1 0.1 0.1 0.1 0.1 ... 0.5 0.6 0.3 Traceback (most recent call last): File "D:/python_project/price_reviser/price_reviser.py", line 58, in prod_weight = prod_data.loc[prod_data['sku'] == row['sku']]['weight'].item() File "C:\Users\tlsdy\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\base.py", line 719, in item return self.values.item() ValueError: can only convert an array of size 1 to a Python scalar So I changed the code again as shown below. prod_weight = prod_data.loc[prod_data['sku'] == row['sku']]['weight'].values -------------result-------------------------------- [1.0] [0.2] [0.1] [0.1] [0.1] [0.1] [0.1] ... [0.5] [0.6] [0.3] So I changed the code again as shown below. prod_weight = re.sub('\[|''\]|''\'|', '', str(prod_data.loc[prod_data['sku'] == row['sku']]['weight'].values)) --------------result------- 1. 0.2 0.1 0.1 0.1 0.1 0.1 ... 0.5 0.6 0.3 but, 1.0 --&gt; 1. 2.0 --&gt; 2. How can I…
has comment: http://stackoverflow.com/comment/85093106
upvote count: 0
answer count: 1

http://stackoverflow.com/q/49097667
has body: I have a 3d array created with numpy, and I was wondering how I can rotate it by a custom angle, not just the rot90 function that numpy has. Can anyone help? The 3d matrix represents an image (such as a cube, or some other shape) ie 0: 1 1 1 1 1 1 1 1 1: 1 1 1 1 2: 1 1 1 1 1 1 1 1 EDIT: Moved solution to answer
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/49179544
tagged with: python
answer count: 4
score: 4
has comment: http://stackoverflow.com/comment/94358157
has comment: http://stackoverflow.com/comment/85206412
has answer: http://stackoverflow.com/a/49164313
has title: How can I rotate a 3d array (nxnxn) by x degrees around x, y, and z axes?
has answer: http://stackoverflow.com/a/49097793
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85200815
accepted answer: http://stackoverflow.com/a/49179544
linked to: http://stackoverflow.com/q/31401812
possible better answer: http://stackoverflow.com/a/49097745
tagged with: rotatetransform
has answer: http://stackoverflow.com/a/49097745
type: Question
upvote count: 4
tagged with: numpy
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49005651
has comment: http://stackoverflow.com/comment/85052100
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85034384
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25776812
has comment: http://stackoverflow.com/comment/85076636
upvote count: 384
has body: This question is motivated by my another question: How to await in cdef? There are tons of articles and blog posts on the web about asyncio, but they are all very superficial. I couldn't find any information about how asyncio is actually implemented, and what makes I/O asynchronous. I was trying to read the source code, but it's thousands of lines of not the highest grade C code, a lot of which deals with auxiliary objects, but most crucially, it is hard to connect between Python syntax and what C code it would translate into. Asycnio's own documentation is even less helpful. There's no information there about how it works, only some guidelines about how to use it, which are also sometimes misleading / very poorly written. I'm familiar with Go's implementation of coroutines, and was kind of hoping that Python did the same thing. If that was the case, the code I came up in the post linked above would have worked. Since it didn't, I'm now trying to figure out why. My best guess so far is as follows, please correct me where I'm wrong: Procedure definitions of the form async def foo(): ... are actually interpreted as methods of a class inheriting coroutine. Perhaps, async def is actually split into multiple methods by await statements, where the object, on which these methods are called is able to keep track of the progress it made through the execution so far. If the above is true, then, essentially, execution of a coroutine boils down to calling methods of coroutine object by some global manager (loop?). The global manager is somehow (how?) aware of when I/O operations are performed by Python (only?) code and is able to choose one of the pending coroutine methods to execute after the current executing method relinquished control (hit on the await statement). In other words, here's my attempt at "desugaring" of some asyncio syntax into something more understandable: async def coro(name): print('before', name) await asyncio.sleep() print('after', name) asyncio.gather(co…
type: Question
score: 380
downvote count: 4
has comment: http://stackoverflow.com/comment/89291004
has answer: http://stackoverflow.com/a/51177895
answer count: 6
linked to: http://stackoverflow.com/q/48989065
linked to: http://stackoverflow.com/q/41204129
has answer: http://stackoverflow.com/a/74137286
has answer: http://stackoverflow.com/a/51116910
tagged with: python-internals
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/49007291
has comment: http://stackoverflow.com/comment/85053370
has answer: http://stackoverflow.com/a/69599319
tagged with: python
has title: How does asyncio actually work?
has answer: http://stackoverflow.com/a/49014143
favorite count: 0

http://stackoverflow.com/q/49118954
has body: I have this script api = ubidots.ApiClient('BBOO-b0c9e35928db729b1e6535be2eeee2e35956') dt = client.get_datasource('5a1db98d180cae4297lld70f') all_variables = my_specific_datasource.get_variables() for variables in all_variables: print (variables.name) + str(variables.get_values(1)) Which gives me the next line rssi[{u'timestamp': 1520277036000, u'created_at': 1520277048408, u'value': -92.0, u'context': {}}] The question is how do i take only the value of timestamp and value from the previous line, to upload it to a csv. I'm not very expert in the subject, I appreciate your help
tagged with: python-2.7
has title: extract values from a result in python
answer count: 1
accepted answer: http://stackoverflow.com/a/49119144
score: 0
tagged with: python
tagged with: dictionary
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49119144
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/49110204
accepted answer of: http://stackoverflow.com/q/49110156
has comment: http://stackoverflow.com/comment/85261130
has comment: http://stackoverflow.com/comment/85228357
has comment: http://stackoverflow.com/comment/85228214
has comment: http://stackoverflow.com/comment/85264966
upvote count: 21
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85262863
downvote count: 0
has comment: http://stackoverflow.com/comment/85228305
has comment: http://stackoverflow.com/comment/85262038
has comment: http://stackoverflow.com/comment/85283908
has comment: http://stackoverflow.com/comment/85253770
has comment: http://stackoverflow.com/comment/85263846
has comment: http://stackoverflow.com/comment/85228070
has comment: http://stackoverflow.com/comment/85228295
type: Answer
has comment: http://stackoverflow.com/comment/85256488
has comment: http://stackoverflow.com/comment/85260952
has comment: http://stackoverflow.com/comment/85292144
has comment: http://stackoverflow.com/comment/85257162
has comment: http://stackoverflow.com/comment/85228035
has comment: http://stackoverflow.com/comment/85265452
has comment: http://stackoverflow.com/comment/85256727
score: 21
has comment: http://stackoverflow.com/comment/85281328
has comment: http://stackoverflow.com/comment/85264552
answers question: http://stackoverflow.com/q/49110156
has comment: http://stackoverflow.com/comment/85280516
has comment: http://stackoverflow.com/comment/85262047
has body: First select only columns for output and add drop_duplicates, last add new column by range: df = df'age','maritalstatus'.drop_duplicates() df['no'] = range(len(df.index)) print (df) age maritalstatus no 0 Young married 0 1 young married 1 2 young Single 2 3 old single 3 4 old married 4 5 teen married 5 7 adult single 6 If want convert all values to lowercase first: df = df'age','maritalstatus'.apply(lambda x: x.str.lower()).drop_duplicates() df['no'] = range(len(df.index)) print (df) age maritalstatus no 0 young married 0 2 young single 1 3 old single 2 4 old married 3 5 teen married 4 7 adult single 5 EDIT: First convert to lowercase: df'age','maritalstatus' = df'age','maritalstatus'.apply(lambda x: x.str.lower()) print (df) user age maritalstatus product 0 A young married 111 1 B young married 222 2 C young single 111 3 D old single 222 4 E old married 111 5 F teen married 222 6 G teen married 555 7 H adult single 444 8 I adult single 333 And then use merge for unique product converted to list: df2 = pd.DataFrame([{'user':'X', 'age':'young', 'maritalstatus':'married'}]) print (df2) age maritalstatus user 0 young married X a = pd.merge(df, df2, on=['age','maritalstatus'])['product'].unique().tolist() print (a) [111, 222] df2 = pd.DataFrame([{'user':'X', 'age':'adult', 'maritalstatus':'married'}]) print (df2) age maritalstatus user 0 adult married X a = pd.merge(df, df2, on=['age','maritalstatus'])['product'].unique().tolist() print (a) [] But if need column use transform: df['prod'] = df.groupby(['age', 'maritalstatus'])['product'].transform('unique') print (df) user age maritalstatus product prod 0 A young married 111 [111, 222] 1 B young married 222 [111, 222] 2 C young single 111 [111] 3 D old single 222 [222] 4 E old married 111 [111] 5 F teen married 222 [222, 555] 6 G teen married 555 [222, 555] 7 H adult single 444 [444, 333] 8 I adult single 333 [444, 333] EDIT1: a = (pd.merge(df, df2, on=['age','maritalstatus']) .groupby('user_y')['product'…

http://stackoverflow.com/comment/85127098
has text: It's not duplicate. The link given was splitting file..Here it's the opposite
comment on: http://stackoverflow.com/q/49058313
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48965867
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/84937565
has comment: http://stackoverflow.com/comment/84937739
has comment: http://stackoverflow.com/comment/84937689
has body: You can groupby column A, then use .transform('first') on column B to generate a series that has the first value of the group for all items in the group, eg: df.loc[:, 'C'] = df.groupby('A').B.transform('first') This'll make your example frame be: A B C 0 2002-01-16 10 10 1 2002-01-16 7 10 2 2002-01-16 2 10 3 2002-01-16 8 10 4 2002-01-16 5 10 5 2002-01-17 54 54 6 2002-01-17 6 54 7 2002-01-17 2 54
score: 3
accepted answer of: http://stackoverflow.com/q/48965791
answers question: http://stackoverflow.com/q/48965791

http://stackoverflow.com/comment/85036134
type: Comment
has text: Oh sorry, I didn't think that'd be something I need to explain. Monogame is a library in C# for creating games. Similar to how Pygame is a module in Python. At least that's how I understand things. I don't consider this an open question in that regard since it has a spritebatch.draw method which handles drawing things, it has a parameter that passes through an Color which it tints to(default is (0, 0, 0) which means it doesn't do anything.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49014660

http://stackoverflow.com/comment/85184198
type: QuestionComment
comment on: http://stackoverflow.com/q/49089165
has text: it works, so im satisfied, thanks. just don't understand why it works.
score: 0
type: Comment

http://stackoverflow.com/a/49009289
answers question: http://stackoverflow.com/q/49009035
score: 4
upvote count: 4
has body: I think you can use recursivity to solve this problem. Here is how your function should work: Do like you do in the first code, until you encounter an opening parenthesis. When you encounter an opening parenthesis, find the corresponding closing parenthesis. This can be done with a counter: initialize it to 1, then when you encounter a new opening parenthesis, you increment the counter, and when you encounter a closing parenthesis you decrement it. When the counter equals 0, you have found the matching closing parenthesis. Cut the string between parentheses and call the same function with this string (here's the recursive aspect). Add the values in the returned dictionary to the current dictionary, multiplied by the number which follows the parenthesis. If you have problems implementing some parts of this solution, tell me and I will give more details. EDIT: about the stack approach The stack approach just simulates recursivity. Instead of calling the function again and having local counter, it has a stack of counters. When an opening parenthesis is opened, it counts in this context, and when it's closed it merges it with the context which contains it, with corresponding multiplicity. I prefer by far the recursive approach, which is more natural.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85023242
has comment: http://stackoverflow.com/comment/85023594

http://stackoverflow.com/q/48995378
tagged with: python
has comment: http://stackoverflow.com/comment/84996493
has comment: http://stackoverflow.com/comment/84996900
has body: I'm trying to write an interpolation function to get any value of CO2 from a value of Ts and Seff. My grids of Ts and Seff are not square. The issue is that for certain values of Ts (eg 275), Seff only goes from 0.4 to 0.8, while for other values of Ts (eg 320), Seff goes from 0.5 to 1.2. But when interpolating, if I ask for a value of CO2 when (Ts=275, S=1.1), I get a value of CO2, even though I should just get NaN (as for Ts=275, Seff of 1.1 does not exist). I tried to resolve this issue with the bounds_error and fill_value arguments below, but this only insures that I get a Nan value when interpolating outside the "absolute" maximum and minimum values of S. import numpy as np from scipy import interpolate Seff =[0.88383316136305645,1.0298932275648676,1.1097533821426062,1.1234656716815736,0.80369957429646033,0.93326566449886517,1.0134725598796075,1.0452557986414284,0.71380176528610517,0.81469788653203512,0.89382224429581447,0.94761085313180471,0.40459228983422418,0.43388658896464499,0.46430015708333283,0.50080988488067069] CO2 = [63.632000000000005,63.632000000000005,63.632000000000005,63.632000000000005,3171.6999999999998,3171.6999999999998,3171.6999999999998,3171.6999999999998,59829.0,59829.0,59829.0,59829.0,760870.0,760870.0,760870.0,760870.0] Tslist = [275,290,305,320,275,290,305,320,275,290,305,320,275,290,305,320] Tsnew = np.arange(280, 315, 0.001) Seffnew = np.arange(0.5, 1.1, 0.001) f=interpolate.interp2d(Tslist,Seff,CO2,bounds_error=False, fill_value='NaN') print f(275,1.1) &gt;&gt; array([ 70446.45005256]) But it seems to still be interpolating outside the bounds of each Ts. Is there a way to remedy this?
tagged with: scipy
has comment: http://stackoverflow.com/comment/85032255
type: Question
has title: 2D interpolate function issue
has comment: http://stackoverflow.com/comment/84998355
score: 0
tagged with: interpolation
has comment: http://stackoverflow.com/comment/84997488
answer count: 0
has comment: http://stackoverflow.com/comment/84996921
type: UnansweredQuestion

http://stackoverflow.com/comment/84976880
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48984586
type: Comment
has text: ...If you don't mind can you practical example like example demo code.

http://stackoverflow.com/comment/85057918
type: QuestionComment
comment on: http://stackoverflow.com/q/49026570
type: Comment
has text: @ Didn't know about! Thanks for info! Why they are missing?
score: 0

http://stackoverflow.com/q/49088108
score: 0
has title: update pyserial data in real time with flask
tagged with: python
duplicate of: http://stackoverflow.com/q/31948285
linked to: http://stackoverflow.com/q/31948285
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49089213
accepted answer: http://stackoverflow.com/a/49089213
type: Question
tagged with: pyserial
answer count: 1
has body: im trying to see data in real time, i have to close the python program to refresh the data. It refreshes only when i close the python file and restart it. i want the data to refresh in real time. from flask import Flask import serial app = Flask(__name__) water = serial.Serial("COM4",9600) water1 = water.readline().decode('ascii') # @ signifies a decorator @app.route('/') def index(): return 'This is home page' @app.route('/plant') def plant(): while True: return ' soil is: ' + water1 + '%' if __name__=="__main__": app.run()
tagged with: flask

http://stackoverflow.com/a/49067278
score: 2
has body: Here's one approach with np.searchsorted - def find_indexes(ar, searched_values, invalid_val=-1): sidx = ar.argsort() pidx = np.searchsorted(ar, searched_values, sorter=sidx) pidx[pidx==len(ar)] = 0 idx = sidx[pidx] idx[ar[idx] != searched_values] = invalid_val return idx Sample run - In [29]: find_indexes(mynumpy, searched_values, invalid_val=-1) Out[29]: array([ 4, -1, 1, 5, 8]) For a generic invalid value specifier, we could use np.where - def find_indexes_v2(ar, searched_values, invalid_val=-1): sidx = ar.argsort() pidx = np.searchsorted(ar, searched_values, sorter=sidx) pidx[pidx==len(ar)] = 0 idx = sidx[pidx] return np.where(ar[idx] == searched_values, idx, invalid_val) Sample run - In [35]: find_indexes_v2(mynumpy, searched_values, invalid_val=None) Out[35]: array([4, None, 1, 5, 8], dtype=object) # For list output In [36]: find_indexes_v2(mynumpy, searched_values, invalid_val=None).tolist() Out[36]: [4, None, 1, 5, 8]
upvote count: 2
has comment: http://stackoverflow.com/comment/85140823
has comment: http://stackoverflow.com/comment/85140278
accepted answer of: http://stackoverflow.com/q/49067127
answers question: http://stackoverflow.com/q/49067127
has comment: http://stackoverflow.com/comment/85140016
has comment: http://stackoverflow.com/comment/85140113
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85155107
type: Answer

http://stackoverflow.com/a/48966066
answers question: http://stackoverflow.com/q/48965985
type: Answer
score: 0
has body: Here is one approach: In [84]: simple_graph = { 'A': ['B'], 'B': ['A', 'C', 'D'], 'C': ['A'], 'D': ['E', 'A', ''], 'E': ['B', ''] } In [85]: [(k, item) for k, v in simple_graph.items() for item in v if item] Out[85]: [('A', 'B'), ('C', 'A'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('E', 'B'), ('D', 'E'), ('D', 'A')]

http://stackoverflow.com/q/49092121
favorite count: 0
downvote count: 2
has body: Newbie here! I have a list. The list contains 200 of these structures. That list contains financial values I would like to plot as candlesticks. Just "Open", "close", "High", "Low" and "Close Time" are the ones I want to plot, as usual. [ [ 1499040000000, # Open time "0.01634790", # Open "0.80000000", # High "0.01575800", # Low "0.01577100", # Close "148976.11427815", # Volume 1499644799999, # Close time "2434.19055334", # Quote asset volume 308, # Number of trades "1756.87402397", # Taker buy base asset volume "28.46694368", # Taker buy quote asset volume "17928899.62484339" # Can be ignored ] ] I would like to do two things. One one hand, plot the candlesticks. On the other hand, extract the "volume" and "Close time" on a separate data structure for further analysis. How can I do it? I am strglugling with Matplot lib and data structures. Thanks in advance.
has answer: http://stackoverflow.com/a/49093835
has title: Python - Plot candlesticks from a list
type: AnsweredQuestion
type: Question
upvote count: 0
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/49093835
tagged with: python

http://stackoverflow.com/comment/89036174
type: Comment
comment on: http://stackoverflow.com/a/49039809
has text: uhm, don't use `os.system(rm...` (potential for shell expansion), when there is a perfectly good python function `os.remove`
type: AnswerComment
score: 3

http://stackoverflow.com/comment/85140661
type: Comment
comment on: http://stackoverflow.com/a/49065251
has text: Yes, every method have special problems but using disk for saving file maybe better than saving on the memory, related to calling this save method rate.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85022506
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49008632
has text: I don't think you've given enough information to explain the problem. However you should definitely remove the `__init__` method. You shouldn't usually have to override `__init__` for Django models, and doing `return self.name` is definitely wrong - that looks more like what you'd do in the `__str__` method.

http://stackoverflow.com/comment/85071331
type: QuestionComment
comment on: http://stackoverflow.com/q/49033015
has text: @monamona I'm especially trying to avoid the statements like `import tools.split_name as tools_split_name`. How can an extra init file help with this? Note that I'm already using an init file for the package.
score: 0
type: Comment

http://stackoverflow.com/q/48994936
score: 3
linked to: http://stackoverflow.com/q/33683840
tagged with: bokeh
has answer: http://stackoverflow.com/a/64813305
type: Question
answer count: 2
downvote count: 0
tagged with: javascript
favorite count: 0
has title: Bokeh Data Table Linked to Select Widget
has answer: http://stackoverflow.com/a/49010464
upvote count: 3
type: UnansweredQuestion
tagged with: python
has body: I am trying to create a Bokeh datatable that is linked to a select widget using a customJS callback. The idea is that when I change the select, the data table will update to show only the relevant rows that correspond with chosen select value. My Code is as follows: from bokeh.io import output_file, show from bokeh.layouts import widgetbox from bokeh.models.widgets import Select, DataTable, TableColumn from bokeh.models.sources import ColumnDataSource, CDSView from bokeh.models import CustomJS output_file("CatDog.html") select = Select(title="Animal", options=["Cat","Dog"]) source=ColumnDataSource(data=dict(Animal=["Cat","Cat","Cat","Cat","Dog","Dog","Dog","Dog",],Breed=["Siamese","Persian","Bengal","Burmese","Lab","Golden", "Poodle","Pug"])) filteredSource = ColumnDataSource(data=dict(Animal=[],Breed=[])) columns = [TableColumn(field="Animal",title="Animal"),TableColumn(field="Breed",title="Breed",sortable=True)] callback = CustomJS(args=dict(source=source,filteredSource = filteredSource), code=""" var data = source.data; var f = cb_obj.value; var d2 = filteredSource.data; d2['Animal']=[] d2['Breed']=[] for(i = 0; i &lt; data['Animal'].length;i++){ if(data['Animal'][i]==f){ d2['Animal'].push(data['Animal'][i]) d2['Breed'].push(data['Breed'][i]) } } alert(d2['Breed']) filteredSource.change.emit() """) select.js_on_change('value',callback) data_table=DataTable(source=filteredSource,columns=columns ) data_table_unfiltered=DataTable(source=source,columns=columns ) show(widgetbox(data_table,select,data_table_unfiltered)) The alert correctly displays the rows that I would expect depending on which category select is on but the "filteredSource" DataTable does not update, it stays blank. Any guidance would be greatly appreciated!

http://stackoverflow.com/q/49116389
tagged with: matrix
tagged with: python
has body: I'm trying to convert an image to grayscale without using OpenCV or Numpy Example : The matrix of my image is [[[116 116 117] [115 115 116] [117 115 115] ..., [135 138 142] [137 139 139] [137 139 139]] [[116 116 116] [116 116 116] [114 116 116] ..., [135 139 140] [135 137 138] [135 137 138]] [[115 118 114] [115 118 114] [112 116 115] ..., [132 141 141] [134 137 141] [133 136 140]] ..., [[ 35 44 163] [ 31 40 159] [ 10 33 158] ..., [ 14 48 53] [ 24 56 55] [ 27 59 58]] [[ 24 38 156] [ 19 33 151] [ 7 28 145] ..., [ 25 55 66] [ 15 59 61] [ 17 61 63]] [[ 0 27 131] [ 0 26 130] [ 0 34 113] ..., [ 11 39 55] [ 6 28 56] [ 4 26 54]]] Using the cv2.COLOR_BGR2GRAY function the matrix is : [[150 150 150 ..., 150 150 150] [150 173 175 ..., 97 91 89] [150 176 179 ..., 95 89 82] ..., [150 66 67 ..., 152 154 152] [150 62 59 ..., 152 152 152] [150 62 64 ..., 155 154 151]] First, i don't get why it returns a 36 integers when i gave 108 and how can i do it manually Thanks for your help :)
has answer: http://stackoverflow.com/a/49117047
type: AnsweredQuestion
has title: Convert an image to grayscale using only matrix (No BGR2GRAY function) in Python
tagged with: image
type: Question
score: 0
tagged with: grayscale
accepted answer: http://stackoverflow.com/a/49117047
answer count: 1

http://stackoverflow.com/comment/85168842
type: Comment
comment on: http://stackoverflow.com/q/49081377
type: QuestionComment
score: 0
has text: You could probably accomplish your overall goal (whatever it is) via [dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries), although I suspect this still isn't the best approach to whatever it is you're trying to do.

http://stackoverflow.com/q/49029751
has answer: http://stackoverflow.com/a/49031025
accepted answer: http://stackoverflow.com/a/49031025
has comment: http://stackoverflow.com/comment/85066342
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/85066878
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85064596
has comment: http://stackoverflow.com/comment/85064163
has body: I'm learning OpenCV (and Python) and have managed to get OpenCV to detect my nose and move the mouse using the movement of my nose, but since it looses track of my nose often I want it to fall back to moving using my face instead of my nose if needed. I've managed to draw rectangles around my face and my nose in video. I tried being cheeky and just putting the loop for my face rectangle in "if cv2.rectangle" (for the nose), but it is always true. My question is how can I create a test to see if nose is detected fallback to move mouse with face, and if nose is re-detected go back to using the nose. My loops as of now # Here we draw the square around the nose, face and eyes that is detected. for (x,y,w,h) in nose_rect: cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 3) if cv2.rectangle: m.move(x * 4, y * 4) # TODO: Write and if that goes into face if nose is not visible break else: for (x, y, w, h) in face_rect: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) break for (x,y,w,h) in eye_rect: cv2.rectangle(frame, (x,y), (x+w,y+h), (205,0,0), 3) break I can post my entire program if that helps, I've tried doing a bunch of the OpenCV official tutorials but did not managed to find an answer to my question there. Thank you for all replies! PS: I'm using Python 3.5
type: Question
has comment: http://stackoverflow.com/comment/85064274
upvote count: 2
has comment: http://stackoverflow.com/comment/85064448
has comment: http://stackoverflow.com/comment/85064810
favorite count: 0
answer count: 1
tagged with: python
has title: Only do action if rectangle exists in OpenCV
has comment: http://stackoverflow.com/comment/85064754
has comment: http://stackoverflow.com/comment/85065094

http://stackoverflow.com/comment/85184072
has text: Sure - but it contains ***URLS***, not simple words.
type: Comment
comment on: http://stackoverflow.com/a/49089234
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85150058
comment on: http://stackoverflow.com/a/49071402
has text: Yes it works. But it deletes the NaN and converts to a blank
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85128399
type: AnswerComment
comment on: http://stackoverflow.com/a/49061598
has text: What if the pattern is user inputted. Like look for this type of pattern and replace it with 1234
type: Comment
score: 0

http://stackoverflow.com/q/49049852
has title: Numpy string array pad with string
has body: I have created a 2d Numpy string array like so: a = np.full((2, 3), '#', dtype=np.unicode) print(a) The output is: array([['#', '#', '#'], ['#', '#', '#']], dtype=`'&lt;U1'`) I would like to pad it with '?' on all sides with a width of 1. I'm expecting output as: array([ ['?', '?', '?', '?', '?'], ['?', '#', '#', '#', '?'], ['?', '#', '#', '#', '?'], ['?', '#', '#', '#', '?'], ['?', '?', '?', '?', '?']], dtype=`'&lt;U1') I tried the following: b = np.pad(a, ((1, 1), (1, 1)), 'constant', constant_values=(('?', '?'), ('?', '?'))) But that gives the following error: File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3/dist-packages/numpy/lib/arraypad.py", line 1357, in pad cast_to_int=False) File "/usr/lib/python3/dist-packages/numpy/lib/arraypad.py", line 1069, in _normalize_shape return tuple(tuple(axis) for axis in arr.tolist()) AttributeError: 'tuple' object has no attribute 'tolist' Similar code works for integers. What am I doing wrong for strings?
tagged with: python-3.x
upvote count: 2
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49050076
possible better answer: http://stackoverflow.com/a/49055460
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/49055460
has comment: http://stackoverflow.com/comment/85115163
downvote count: 0
has comment: http://stackoverflow.com/comment/85104498
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/49050076
tagged with: python

http://stackoverflow.com/q/48969526
answer count: 1
linked to: http://stackoverflow.com/q/32362570
score: 0
has body: I am developing small app with few submodules: src/ setup.py myapp/ myGuiapp.py modules/ __init__.py editorGui.py fileParser.py modules/__ init __.py from editorGui import editorWindow from fileParser import parseMyFile myGuiapp.py from modules import editorWindow from modules import parseMyFile parseMyFile(parms) editorWindow(self) EditorGui.py from fileParser import parseMyFile # from .fileParser import parseMyFile # from modules.fileParser import parseMyFile fileParser(parms) I would like to have my EditorGui.py to be called from myGuiapp.py but also to be able to run it by itself. How should i setup relative importing in such case ? If in EditorGui.py I will set : from modules.fileParser import parseMyFile &gt;python editorGui.py ModuleNotFoundError: No module named 'modules' but from main app &gt;python myGuiapp.py OK ! If in EditorGui.py I will set : from .fileParser import parseMyFile &gt;python EditorGui.py ModuleNotFoundError: No module named '__main__.fileParser'; '__main__' is not a package If in EditorGui.py I will set : from fileParser import parseMyFile &gt;python editorGui.py OK ! &gt;python myGuiapp.py ModuleNotFoundError: No module named 'fileParser' How can I make both work and what i am doing wrong here? I would like to avoid setting up ABSOLETE paths to this dev directory. What would be most pythonic and clean way to structure such app ? EDIT: After @Diego Trazzi post, I've decided to move my EditorGui.py up the level: src/ setup.py myapp/ myGuiapp.py editorGui.py modules/ __init__.py fileParser.py This solves many issues but for curiosity, my question still stands. How can I import module from same level while being imported by code from parent directory?
tagged with: python
has comment: http://stackoverflow.com/comment/84958539
type: UnansweredQuestion
has title: importing module from second module
has answer: http://stackoverflow.com/a/48977016
has comment: http://stackoverflow.com/comment/84945442
type: Question

http://stackoverflow.com/comment/85087218
has text: Please edit your post to include a [**Minimal, Complete, Verifiable Example**](https://stackoverflow.com/help/mcve).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49040837
score: 1

http://stackoverflow.com/comment/85006127
type: Comment
score: 0
has text: QQ : What if I had to consider the Indicator Y as well but when you switch from N to Y, the value corresponding to Y is considered in the first block.
type: AnswerComment
comment on: http://stackoverflow.com/a/49000122

http://stackoverflow.com/a/49096607
type: Answer
answers question: http://stackoverflow.com/q/49096599
score: 0
has body: What worked was using ternary: True if '' else False # False More verbose than in Javascript, but works.
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85198330

http://stackoverflow.com/a/48997882
type: AcceptedAnswer
has body: Never parse JSON with regex, use a JSON parser. With jq : Input file : { "commit" : { "commit" : { "tree" : { "verification" : { "payload" : null, "verified" : false, "signature" : null, "reason" : "unsigned" }, "sha" : "3e4710d0e021a0a7", "comment_count" : 0 }, "author" : { "id" : 5, "login" : "kyle" }, "committer" : { "name" : "GitHub Enterprise", "date" : "2018-02-26T20:14:41Z" }, "message" : "Update README.md" }, "sha" : "adc3208a9ac76262250a" }, "name" : "master" } Command : $ jq '.commit.commit.author.login' file.json Or via a python script : #!/usr/bin/env python3 import json string = """ { "commit" : { "commit" : { "tree" : { "verification" : { "payload" : null, "verified" : false, "signature" : null, "reason" : "unsigned" }, "sha" : "3e4710d0e021a0a7", "comment_count" : 0 }, "author" : { "id" : 5, "login" : "kyle" }, "committer" : { "name" : "GitHub Enterprise", "date" : "2018-02-26T20:14:41Z" }, "message" : "Update README.md" }, "sha" : "adc3208a9ac76262250a" }, "name" : "master" } """ j = json.loads(string) print(j['commit']['commit']['author']['login']) Output : "kyle"
type: Answer
accepted answer of: http://stackoverflow.com/q/48997785
answers question: http://stackoverflow.com/q/48997785
score: 0

http://stackoverflow.com/comment/85179836
has text: This is backwards. Different results are expected here unless python is instructed correctly about ses. Your second question remains.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49086721

http://stackoverflow.com/comment/85117682
score: 1
comment on: http://stackoverflow.com/a/49056402
type: AnswerComment
has text: @PatrickArtner Sure, I suppose thats more pythonic. To me the `int()` is a bit more explicit and clear, but I can see many people disagreeing with that. This answer will still work in cases where the `2` is provided externally (and might be `2.0`) instead of as a magic number. This will also work for a multiplication by `0.5` instead of division by `2`.
type: Comment

http://stackoverflow.com/a/49078956
score: 0
has comment: http://stackoverflow.com/comment/85191193
type: Answer
answers question: http://stackoverflow.com/q/49078654
has comment: http://stackoverflow.com/comment/85164295
has body: Have you tried this? upQuery = db.session.query(Notifications) \ .join(Notifications.rel_tas).filter((Notifications.comm_approval != 'New') | (Taskinfo.startdate &gt;= datetime.utcnow())) \ .paginate(uppage,per_page,error_out=False)

http://stackoverflow.com/q/48975486
tagged with: grammar
answer count: 1
downvote count: 0
tagged with: parsing
favorite count: 0
upvote count: 2
tagged with: python
has title: How to match a pattern in Tatsu in a case insensitive manner
has answer: http://stackoverflow.com/a/48992111
accepted answer: http://stackoverflow.com/a/48992111
type: AnsweredQuestion
score: 2
tagged with: tatsu
type: Question
has comment: http://stackoverflow.com/comment/84960640
has body: anybody knows how to recognize a pattern in Tatsu, in a case-insensitive way? The documentation says to: "Use (?i) in patterns that should ignore case." but I did not actually figure out how to use (?i) in my rule: graph = [ STRICT ] ( GRAPH | DIGRAPH ) [graph_name:id] '{' { rule_list:rule }* '}'; STRICT = 'strict' ; In practice, I've to recognize the word 'strict', regardless of its case. Thanks Tom

http://stackoverflow.com/comment/85128629
comment on: http://stackoverflow.com/q/49061655
has text: with d = data[0] I get error; ' return self.attrs[key]'
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49050848
favorite count: 0
tagged with: boost-python
has body: I am trying to expose a structure in C++ to a python script, which then converts the structure to a JSON format. The structure contains both vector as well as elementary datatypes. So my approach was to scan through the attributes of the structure, if it is a elementary datatype, then just add it to the dictionary. Else, scan through the list, and add all the elementary datatypes. So here is what I came up with: # Get all the attributes of the object, also ensure it is not a function. def getattribs(obj): return [i for i in dir(obj) if not i.startswith('__') and not callable(getattr(obj, i))] def f(obj): for i in getattribs(obj): # Ensure it is not a list if not hasattr(getattr(obj, i), '__iter__'): print((i, getattr(obj, i))) else: for x in list(getattr(obj, i)): # If obj is string, then just add it if(isinstance(x, basestring)): print((i, x)) else: f(x) But as you can see, parsing it to JSON from this point on becomes a pain in the ass. Is there any better way to do the same? Sample structure in C++: struct Hosts { std::string hostName; bool isProvider; bool showVM; std::vector&lt;std::string&gt; vmList; bool operator==(Hosts const&amp; h) const { return h.hostName == hostName; } }; struct ClustersInfo { std::string clusterName; bool showChild; std::vector&lt;Hosts&gt; hosts; bool operator==(ClustersInfo const&amp; ci) const { return ci.clusterName == clusterName; } }; struct Clusters { bool expanded; std::vector&lt;ClustersInfo&gt; clusterInfo; void populateData(); Clusters getData(); };
tagged with: python
tagged with: c++
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
score: 1
has title: Parsing to JSON in python when exposed with boost::python

http://stackoverflow.com/comment/84957284
has text: @user130268 the code works the same in the regular console. I only mention that there's a better solution.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48976152
type: Comment

http://stackoverflow.com/q/49071377
tagged with: python-requests
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/49071462
score: 0
answer count: 1
tagged with: python
has title: Dict of dict url encoded params for post request in Python?
tagged with: discourse
type: UnansweredQuestion
has body: params_for_update_cat = { 'api_key': API_KEY, 'api_username':"ausername", "name": name_and_ticker, "color": bg_colour, "text_color": text_color, "permission": {'admins': 1,'staff': 2} } headers = {"Content-Type": "multipart/form-data"} r = rq.post(url=create_cat_url, data=params, headers=headers) So what I want is and the above certainly doesn't do this: permissions[admin]=1&amp;permissions[staff]=2 as parts of the params list. this should be in the post body of course. Some caveats: The api doesn't support content-type: application/json request headers. The api is expecting the request to be made as data was coming from a form. If I were to do this in curl and this is successfully test btw - it would be: !curl -X POST "http://&lt;mydomaingoeshere&gt;/categories.json" / -H "Content-Type: multipart/form-data;" / -F "api_key=xxxxxxxxx_xxxxx" / -F "api_username=ausername" / -F "name=checkcheckcheck" / -F "text_color=FFFFFF" / -F "color=49d9e9" / -F "permissions[admins]=1" / -F "permissions[staff]=2" 3 days on this - and no one has been able to help. Maybe something like this is a bad idea? I don't know.

http://stackoverflow.com/comment/85175507
type: QuestionComment
has text: https://en.wikipedia.org/wiki/Pulse-code_modulation#Modulation contains a pretty accessible introduction.
score: 0
comment on: http://stackoverflow.com/q/49084535
type: Comment

http://stackoverflow.com/comment/84962085
type: Comment
type: QuestionComment
has text: so what is it you want here? seems like the same exact thing with joins, also you execute `sql` and `sql2` but you label the queries as `query1` and `query2`
comment on: http://stackoverflow.com/q/48978504
score: 0

http://stackoverflow.com/a/49053744
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49053080
type: Answer
has body: In your dataframe it appears that 'Group' is in the index, the purpose of the index is to label each row. Therefore, is unusual and uncommon to have blank row indexes. You you could so this: df2.reset_index().set_index('Group', append=True).swaplevel(0,1,axis=0) Or if you really must show blank row indexes you could do this, but you must change the dtype of the index to str. df1 = df.set_index('Group').astype(str) df1.index = df1.index.where(~df1.index.duplicated(),[' '])
answers question: http://stackoverflow.com/q/49053080

http://stackoverflow.com/comment/85065238
comment on: http://stackoverflow.com/a/49030362
has text: How do you know that it isn't working if you don't try to read it?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85132517
type: QuestionComment
has text: What happen if `0` ?
comment on: http://stackoverflow.com/q/49063738
score: 0
type: Comment

http://stackoverflow.com/comment/85235730
comment on: http://stackoverflow.com/q/49115251
has text: Ok I'll get back home and correct my errors sorry. I'll edit and tell what I got.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/48963698
has body: Trying to count the amount of times a specific value occurs within a Python dictionary but can't seem to get it to work. My dictionary is set up as so: count = ({'John': 2, 'Sam': 1, 'Brian': 2, 'Brian': 2, 'Brian': 1, 'Sam': 2, 'John': 2, 'Henry': 2, 'Brian': 1}) I am to get the result so that if a user inputs 'Brian' the result would be: 4 Or if the user were to enter 'Sam' the result would then be: 2 number = 0 userInput = input("Please enter a player: ") for k, v in count.items(): if k == userInput: number =+ 1 print(number) Is there a better way of doing this, as currently if were to type in 'Sam' it would only output '1'? Thanks !
type: AnsweredQuestion
downvote count: 3
tagged with: loops
has answer: http://stackoverflow.com/a/48963877
type: Question
has answer: http://stackoverflow.com/a/48963728
possible better answer: http://stackoverflow.com/a/48963877
has comment: http://stackoverflow.com/comment/84933219
score: -3
has title: Counting specific values within Python Dictionary
answer count: 2
upvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48963728
tagged with: input
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/85069527
comment on: http://stackoverflow.com/q/49032242
type: QuestionComment
type: Comment
has text: Please include a copy of CA13_JSON.py or a link to it with your question.
score: 0

http://stackoverflow.com/q/48964883
has title: .view() throws an error "matplotlib is currently using a non-GUI backend, "
tagged with: jupyter-notebook
tagged with: view
has comment: http://stackoverflow.com/comment/84935831
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85015708
has body: Here is the code I am working on and refering the following website Link import numpy as np import skfuzzy as fuzz from skfuzzy import control as ctrl soc = ctrl.Antecedent(np.arange(0, 11, 1), 'soc') log = ctrl.Antecedent(np.arange(0, 11, 1), 'log') aut = ctrl.Consequent(np.arange(0, 11, 1), 'aut') log.automf(3) soc.automf(3) aut.automf(3) soc.view() I am running this code in Jupyter notebook
score: 0
tagged with: jupyter

http://stackoverflow.com/comment/85489751
type: QuestionComment
comment on: http://stackoverflow.com/q/49012747
score: 0
has text: This is not a programming question but one about setup of KVM. Just because you wrap your XML into some alibi lines of Python doesn't make it on-topic.
type: Comment

http://stackoverflow.com/comment/85235048
comment on: http://stackoverflow.com/q/49114286
type: Comment
type: QuestionComment
has text: have a look on it
score: 0

http://stackoverflow.com/q/49022769
has body: I would like to convert a column of float value to string, following is my current way: userdf['phone_num'] = userdf['phone_num'].apply(lambda x: "{:.0f}".format(x) if x is not None else x) However, it also converts the NaN to string "nan" which is bad when I check the missing value in this column, any better idea? Thanks!
has answer: http://stackoverflow.com/a/49022810
has comment: http://stackoverflow.com/comment/85050486
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pandas
has title: how to convert float to string excluding NaN in pandas within one line code?
tagged with: python
accepted answer: http://stackoverflow.com/a/49022810
upvote count: 6
type: AnsweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/85050849
type: Question

http://stackoverflow.com/comment/85041450
score: 0
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165931/discussion-between-teja-and-yotam-salmon).
comment on: http://stackoverflow.com/a/49017761
type: AnswerComment

http://stackoverflow.com/comment/84966001
type: QuestionComment
has text: I got the solution. I had to read it as utf-8.
comment on: http://stackoverflow.com/q/48980425
score: 0
type: Comment

http://stackoverflow.com/comment/84979610
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48980602
type: QuestionComment
has text: Update the question with more of the publish code, you need to be running the client loop for QOS2 publishes because it's a multi step process.

http://stackoverflow.com/comment/85050081
score: 0
comment on: http://stackoverflow.com/q/48984203
type: Comment
has text: Because the browser doesn't open up on the target host
type: QuestionComment

http://stackoverflow.com/comment/84961255
has text: So an individual `input()` statement reads *one line*. For multi-line inputs, we need to keep calling `input()` over and over again. However, we need to know when to stop calling this as otherwise the program would never stop multi-line inputting! So, we need a "signal" , or special input line that tells us when to break out of our infinite `while` loop. This could be *anything*. In the first snippet, I used an empty string (`''`) and in the second I used the string: `'END'`. This method definitely works and I am testing it, so I don't know what's going wrong for you. Please elaborate on errs.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48976616

http://stackoverflow.com/q/49112356
type: AnsweredQuestion
has title: I want to create a genric format function, what is default value of top,bottom,right,left
has answer: http://stackoverflow.com/a/49115685
accepted answer: http://stackoverflow.com/a/49115685
tagged with: xlsxwriter
has body: def columnandcellformate(sheet_name,bold = 0,font_color = '#000000',bg_color = '#ffffff',align = '' ,bottom = 0 ,top = 3,right = 0,left = 0,font_size = 10 ,starcolumn = 0, endrow = 0 ): global sheet_format sheet_format=sheet_name.add_format({ 'bottom':bottom, 'top' : top, 'bg_color':bg_color, 'font_color' : font_color, 'align':align, 'font_size':font_size, 'bold': bold, 'font_name':'Batang' }) What is default value of top,bottom,right,left, My function is making cell top,bottom,right and left blank
has answer: http://stackoverflow.com/a/49115748
type: Question
score: -1
possible better answer: http://stackoverflow.com/a/49115748
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85230856
upvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: python

http://stackoverflow.com/comment/85244657
type: AnswerComment
comment on: http://stackoverflow.com/a/49118837
score: 0
has text: Thanks for the info, now i'm able to get all the details in `data` . Just to add 1 more question, how am i able to only print 1 header's details from `data = json_content['observations']['data']' ? For example, I want to only get all `local_date_time` from all dict in `data`
type: Comment

http://stackoverflow.com/q/49012613
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49013866
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/85029858
answer count: 1
has title: Convert Single Element of Numpy Array into Another Type
has comment: http://stackoverflow.com/comment/85029868
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I have a Numpy array with data type float64. For example: [1.35623 , 2.35124 , 5.12276, 0.12466]. How can I change the data type of a single element of this array. I have tried using astype(), but it seems to return a scalar number rather a numpy array. How can I do this in Python 3.x?
score: 1
has comment: http://stackoverflow.com/comment/85029848
linked to: http://stackoverflow.com/q/11309739

http://stackoverflow.com/comment/85112456
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49053919
has text: @Harry_pb -No, i didn't tried
score: 0

http://stackoverflow.com/comment/85001494
has text: I'm not sure I understand your question, but if you remove `protocols/__init__.py` you will not be able to `from protocols.prot1 import Prot1` at all. Alternative is to have `protocols.py` instead of directory, and have all classes defined in it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48997734

http://stackoverflow.com/a/49113696
has body: Simple Explanation No. But internally, all Python objects (except those defined with __slots__, or Python builtins) use dictionaries for dynamic attribute access. As you can see in the following example, using __slots__ makes the type not store an internal dictionary, which prevents dynamically setting methods, fields, or other information to the type. However, the size of the type is reduced as a result. In [7]: class A: ...: __slots__ = ('fields') ...: def __init__(self): ...: self.fields = 1 ...: In [9]: dir(A) Out[9]: ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'fields'] If you take a look at the CPython source code, you will also see most builtin types are not stored as dictionaries, either: #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD double ob_fval; } PyFloatObject; #endif Rationale To understand why all classes that allow dynamically setting variables, methods, and other information use dicts internally to store this information, we need to consider what dictionaries are extremely good at: O(1) information access with O(1) insertions and deletions. Since the interpreter does not know which attributes the class may have, if that attribute is a variable, method, etc. until runtime, this requires using some sort of container bound to the class at runtime. In other languages, like C++, this is achieved using an array of function pointers (typically, although not guaranteed), or a virtual table, allowing you to dynamically change a predefined set of methods to the class. However, since the method name is already harded-coded, this does not allow dynamically adding or removing methods to the class. Any approach except a hashmap or binary search tree may be unable to efficie…
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49113676
type: Answer

http://stackoverflow.com/comment/85309561
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49112304
type: Comment
has text: but the value which i get from the input i need it to print in one variable so i can add that value with few other categories

http://stackoverflow.com/comment/85081166
score: 0
type: QuestionComment
type: Comment
has text: If your queries work when fed directly into SQL, you are probably having a problem with your double and single quotes with Python strings.
comment on: http://stackoverflow.com/q/49037807

http://stackoverflow.com/comment/85124626
type: QuestionComment
score: 0
has text: when i print (product) i get: First name How can I now get the value of _CsrfToken and put it into my payload ?
type: Comment
comment on: http://stackoverflow.com/q/49059489

http://stackoverflow.com/a/68134932
answers question: http://stackoverflow.com/q/49119745
has comment: http://stackoverflow.com/comment/138221893
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: I ended up here troubleshooting for a day on this. Maybe this will help someone else. I was also sometimes missing function parse_websearch instead of tsq_parse but I wasn't able to narrow down why it gave one or the other before I fixed it. My issue was I upgraded sqlalchemy_searchable (from 0.10.2 to 1.4) and my database version (Postgres 9.6) was too old now. I needed to manually create some functions now from sqlalchemy_searchable but I was missing a Postgres function (specifically websearch_to_tsquery that was added in 11). I was using Flask-Migrate/Alembic for migrations. I got help from here and ended up making a blank migration (flask db revision to do that). I pasted in the SQL from here. My new migration looked like this. from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'AAA' down_revision = 'BBB' branch_labels = None depends_on = None def upgrade(): command = &quot;&quot;&quot; CREATE OR REPLACE FUNCTION parse_websearch(config regconfig, search_query text) RETURNS tsquery AS $$ SELECT string_agg( ( CASE WHEN position('''' IN words.word) &gt; 0 THEN CONCAT(words.word, ':*') ELSE words.word END ), ' ' )::tsquery FROM ( SELECT trim( regexp_split_to_table( websearch_to_tsquery(config, lower(search_query))::text, ' ' ) ) AS word ) AS words $$ LANGUAGE SQL IMMUTABLE; CREATE OR REPLACE FUNCTION parse_websearch(search_query text) RETURNS tsquery AS $$ SELECT parse_websearch('pg_catalog.simple', search_query); $$ LANGUAGE SQL IMMUTABLE;&quot;&quot;&quot; op.execute(command) def downgrade(): op.execute('DROP FUNCTION public.parse_websearch(regconfig, text);') op.execute('DROP FUNCTION public.parse_websearch(text);')

http://stackoverflow.com/q/49080194
has answer: http://stackoverflow.com/a/49080337
type: UnansweredQuestion
tagged with: python
has body: I write a program to print a 2x2 matrix where the digits represented in each matrix is given through user input. For instance: userin = 1 2 #two digit input with a spacing in between userin2 = 3 4 #userin and userin2 is first matrix userin3 = 5 6 userin4 = 7 8 #userin3 and userin4 is second matrix The program would then print out: [[1,2],[3,4]], #first matrix [[5,6],[7,8]] #second matrix I got the program to work as I want but i feel that the code I wrote is so inefficient that I'm creating too many empty list to cater for the user input. userin = input("Enter first two digit for first 2x2 matrix: ").split(' ') userin2 = input("Enter last two digit for first 2x2 matrix: ").split(' ') userin3 = input("Enter first two digit for second 2x2 matrix: ").split(' ') userin4 = input("Enter last two digit for second 2x2 matrix: ").split(' ') lst1 = [] lst2 = [] lst3 = [] lst4 = [] matrix = [] matrix2 = [] for x in userin: x = int(x) lst1.append(x) for j in userin2: j = int(j) lst2.append(j) for x in userin3: x = int(x) lst3.append(x) for j in userin4: j = int(j) lst4.append(j) matrix.append(lst1) matrix.append(lst2) matrix2.append(lst3) matrix2.append(lst4) print(matrix) print(matrix2) The program outputs in the format I want which is [[1,2],[3,4]],[[5,6],[7,8]] but I'm looking for a more efficient way of doing this. Note that I'm not advised to use numpy and other built in library. Thanks for your help.
has title: Printing 2x2 matrix
type: Question
has answer: http://stackoverflow.com/a/49080318
has comment: http://stackoverflow.com/comment/85166256
has answer: http://stackoverflow.com/a/49080304
score: 0
answer count: 3
tagged with: matrix
has comment: http://stackoverflow.com/comment/85166336

http://stackoverflow.com/a/49094542
type: AcceptedAnswer
has body: Thanks to this working example, I figured out what was wrong. The reason is that scipy.minimize() sends a 1D Weights array (W) to my Gradient and Cost functions whereas my functions supported only 2D arrays. So reshaping W in the dot product as below fixed the issue : def loOutput(X, W): Z = np.dot(X, W.reshape(-1, 1)) # reshape(-1, 1) because scipy.minimize() sends 1-D W !!! O = misc.sigmoid(Z) return O By the way, I encountered another similar problem after fixing this one. The Gradient function should return a 1D gradient. So I added : def loGradEntroFlatten(W, X, Y, lmbda=0): return loGradEntro(W, X, Y, lmbda).flatten() and I updated : res = minimize(loCostEntro, W, args=(XX,Y,lmbda), method='CG', jac=loGradEntroFlatten, options={'maxiter': 500})
accepted answer of: http://stackoverflow.com/q/49093070
type: Answer
answers question: http://stackoverflow.com/q/49093070
score: 0

http://stackoverflow.com/q/48980503
has answer: http://stackoverflow.com/a/49042336
possible better answer: http://stackoverflow.com/a/48980547
has answer: http://stackoverflow.com/a/48980547
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/48980545
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84966078
tagged with: python-3.x
upvote count: 1
has comment: http://stackoverflow.com/comment/84966135
has title: Why can't I change a substring within a string?
downvote count: 1
has answer: http://stackoverflow.com/a/48980548
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84966154
has answer: http://stackoverflow.com/a/48980545
has body: I am trying to write a function that will convert a dedicated word within a string into asterisks. Basically, I want to censor a word from a string (ex. change "Hello World" into "Hello *****" if I made "World" the dedicated word). I tried to write the following code, but the code will not convert words into asterisks. def censor(text, word): a = text.split() replace = "" for i in word: replace += "*" for i in a: if i == word: i = replace result =' '.join(a) return result Can someone help me? Everything in the code seems to work except for the line i = replace. Thanks!

auc
tags question: http://stackoverflow.com/q/49061575
tag name: auc
type: Tag

http://stackoverflow.com/comment/85236367
comment on: http://stackoverflow.com/a/49104002
has text: I'm guessing that each entity is located inside some tag. So, find and save those tags which have entities in them using `find_all()` and then use the code I've provided inside the loop. Just replace `soup` with the new variable in the loop.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84965753
has text: @bro-grammer technically, in Python 3.6, the fact that dictionaries preserve insertion order is an implementation detail. It will be a part of the spec in versions >= 3.7
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48980285

http://stackoverflow.com/q/49094009
upvote count: 1
tagged with: opencv
has body: I need to generate an intersection matrix from the following image: this image is a maze 4x4 grid board with some red and blue dots located randomly and the image will be taken from a mini-drone, I need to be able to find the location of red and blue dots to provide this information to a line follower that needs to pass through the blue dots avoiding the red ones. I already applied some filters to this image to generate the contour but I don't know how to convert this to coordinates. Here is what I did: import numpy as np import cv2 import random original = cv2.imread('laberinto.jpg',1) img = cv2.resize(original, (600,600), interpolation=cv2.INTER_NEAREST) # cv2.imshow("Original",img) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3,3),0) thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 205, 1) # cv2.imshow("Binary",thresh) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print(len(contours)) filtered = [] for c in contours: if cv2.contourArea(c) &lt; 1000:continue filtered.append(c) print(len(filtered)) objects = np.zeros([img.shape[0],img.shape[1],3], 'uint8') for c in filtered: col = (random.randint(0,255), random.randint(0,255), random.randint(0,255)) cv2.drawContours(objects,[c], -1, col, -1) area = cv2.contourArea(c) p = cv2.arcLength(c,True) print(area,p) cv2.imshow("Contours",objects) cv2.waitKey(0) cv2.destroyAllWindows() result:
type: UnansweredQuestion
has title: how to convert 4x4 grid image to coordinates in Python
answer count: 0
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python

bigint
tags question: http://stackoverflow.com/q/49089920
tag name: bigint
type: Tag

append
tags question: http://stackoverflow.com/q/48988580
tags question: http://stackoverflow.com/q/49018551
tags question: http://stackoverflow.com/q/49107405
tags question: http://stackoverflow.com/q/48996006
tag name: append
tags question: http://stackoverflow.com/q/49086866
tags question: http://stackoverflow.com/q/48979977
tags question: http://stackoverflow.com/q/49019919
tags question: http://stackoverflow.com/q/49055559
tags question: http://stackoverflow.com/q/48994761
tags question: http://stackoverflow.com/q/48985034
tags question: http://stackoverflow.com/q/49067407
tags question: http://stackoverflow.com/q/49088179
type: Tag

http://stackoverflow.com/q/49067070
has answer: http://stackoverflow.com/a/61587939
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49070294
tagged with: type-hinting
has answer: http://stackoverflow.com/a/74579112
has body: I would like to implement validation for Python 3.6 type annotation within my project. I have a method that uses __annotations__ dict to check if all attributes of the class have the correct value. It works perfectly for basic types like int, str or bool, but fails for more sophisticated elements like typing.Union or typing.Optional (which is also a Union). The failure is caused by isinstance() method within Union object that throws TypeError. I even cannot find a way to ensure that the annotation is a Union so I cannot validate if a value complies with a type. The typing module does not have any solution for it. Is there a way to validate if specified variable complies with typing.Union?
type: Question
has title: Python typing validation
tagged with: python-3.6
score: 2
has answer: http://stackoverflow.com/a/49070294
downvote count: 0
has answer: http://stackoverflow.com/a/63427314
favorite count: 0
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/63427314
tagged with: python

http://stackoverflow.com/q/49040641
favorite count: 0
has answer: http://stackoverflow.com/a/49040681
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49040681
has comment: http://stackoverflow.com/comment/85086762
type: Question
score: 5
upvote count: 5
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85087189
has title: Regular expression must contain and may only contain
has body: I want a regular expression for python that matches a string which must contain 4 digits, it may not contain any special character other than "-" or ".", and it may only contain uppercase letters. I know the following matches text with 4 digits or more. How would I add the rest of the criteria? [0-9]{4,} An example would be: ART-4.5-11 is good, ART5411 is good, 76543 is good, but aRT-4!5-11 is bad since it contains a lowercase char and a special char that is not "-" or "."
tagged with: python
tagged with: regex

http://stackoverflow.com/q/49014896
tagged with: python
has comment: http://stackoverflow.com/comment/85035696
tagged with: macos
linked to: http://stackoverflow.com/q/3898574
has comment: http://stackoverflow.com/comment/85035297
has comment: http://stackoverflow.com/comment/85034796
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/85034954
has comment: http://stackoverflow.com/comment/85034984
type: Question
has body: I want to know how I can show a simple gui window and open a link to google.com with python on MacOS. Does somebody know how to do this ? Thank you for answers
has answer: http://stackoverflow.com/a/49015018
upvote count: 0
score: -2
answer count: 1
tagged with: window
has title: How can I show a gui window with python on Mac
favorite count: 0
has comment: http://stackoverflow.com/comment/85034821
has comment: http://stackoverflow.com/comment/85037036

http://stackoverflow.com/q/49098792
has answer: http://stackoverflow.com/a/49099037
type: UnansweredQuestion
downvote count: 0
score: 1
has body: I'd like to route multiple pages to the sample template, with a parameter, and let the other static files to be automatically routed as well: @route('/test1') @route('/hello2') @route('/page3') @view('tpl/page.html') def page(): context = {'request': request, 'pagename': ??} return (context) @route('/<filename>') def files(filename): return static_file(filename, root='./static/') and I'd like page.html to display the request name: This is the page that was requested: {{pagename}} I expect here: This is the page that was requested: hello2 How to direct multiple pages to the same template, and have access to the pagename? I tried str(request).split('example.com/')[1].replace('>', '') but this is a dirty hack, I imagine there's a cleaner way to get test1, hello2, etc. from a @route.
favorite count: 0
type: Question
tagged with: python
tagged with: bottle
upvote count: 1
has title: Route multiple pages to same template, with a parameter, with Bottle or Flask
answer count: 1

http://stackoverflow.com/comment/84963815
type: Comment
comment on: http://stackoverflow.com/a/48977923
score: 0
type: AnswerComment
has text: ...And if you have a valid reason for downvoting, that's fine, just explain it with a comment!

http://stackoverflow.com/q/48991892
has answer: http://stackoverflow.com/a/48997271
tagged with: datetime
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I am trying to get a proper datetime-visulization for my plot. It just shows the numerical values for the datetime-axis. When I hover over the plot the proper datetime is not displayed. You can see it here. Any suggestions for my code? Timestamp is in 2016-01-01 00:45:00 format. # define source for ColumnDataSource source = ColumnDataSource(df) # define figure plot = figure(plot_height=300, x_axis_type="datetime", sizing_mode="scale_width") # add a glyph plot.line('Datetime', 'Preis', source = source, legend='Ausgleichsenergiepreis') # define hoverTool hover_tool = HoverTool(tooltips=[('Time', '$Datetime'),('Price', '@Preis')], mode='vline') hover_tool.formatters = {"Datetime": "datetime"} plot.add_tools(hover) # show plot output_file('Ausgleichenergiepreise.html') show(plot)
score: 1
tagged with: bokeh
type: Question
accepted answer: http://stackoverflow.com/a/48997271
upvote count: 1
has title: Python: HoverToool with Datetime-Axis
answer count: 1
favorite count: 0

http://stackoverflow.com/a/49097897
upvote count: 27
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/104490471
type: Answer
answers question: http://stackoverflow.com/q/49097715
has body: Apparently the naming of the selection depends on the operating system, but the Python interpreter can be selected as follows: Menu File → Preferences → Project → Python Interpreter (macOS) Menu File → Settings → Project → Python Interpreter (Windows and Linux) Using the dropdown, select the right Python interpreter. Depending on your OS and setup, this can be the default interpreter (e.g., ~/anaconda3/bin/python) or the interpreter corresponding to the Conda environment of your choice (e.g., C:\users\username\.conda\envs\projectname\python.exe). Now all the packages installed with Anaconda should be listed.
score: 26
accepted answer of: http://stackoverflow.com/q/49097715
downvote count: 1
has comment: http://stackoverflow.com/comment/124066747
has comment: http://stackoverflow.com/comment/123956328
has comment: http://stackoverflow.com/comment/137510485

http://stackoverflow.com/a/49107831
has comment: http://stackoverflow.com/comment/85220949
has comment: http://stackoverflow.com/comment/85222302
has comment: http://stackoverflow.com/comment/85222003
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85221635
has body: Fixed the issue by refeeding the client_reader (ReaderStream) Thanks to Vincent for comments to point out the request tampering situation and reconstructing the request back to its native form async def accept_client(client_reader, client_writer): try: # Get proxy service - [Proxy-Type] from header via client_reader # Set remote_address and remote_port based on it data = await client_reader.read(2048) # -------- Edited -------- # perform operations based on data and obtain remote_address, remote_port (remote_reader, remote_writer) = await asyncio.wait_for( asyncio.open_connection(host = remote_address, port = remote_port), timeout = 30) except asyncio.TimeoutError: client_writer.close() except Exception as e: client_writer.close() else: # Write the data to remote remote_writer.write(data) await remote_writer.drain() # Pipe the streams asyncio.ensure_future(proxy_data(client_reader, remote_writer)) asyncio.ensure_future(proxy_data(remote_reader, client_writer))
type: Answer
accepted answer of: http://stackoverflow.com/q/49106456
score: 2
answers question: http://stackoverflow.com/q/49106456
upvote count: 2

http://stackoverflow.com/comment/133687091
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49112662
type: Comment
has text: @AshishJohnson in fact i think deleting search history do the thing. If anyone needs to preserve cache and cookies

http://stackoverflow.com/comment/85221617
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49108265
has text: @Graipher it could be the case, however it would broke `str: int` dict convention(if such exist). But Thank you, i updated my answer!
score: 1

http://stackoverflow.com/q/48966108
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Identifying values from one histogram into another
tagged with: matplotlib
type: Question
upvote count: 2
tagged with: numpy
answer count: 1
has body: I have a program (a model about some population) that produces some data (what interests us: ranking and payoffs), with which I plot two histograms. The data: I write two lists, rank and payoffs, in which the i-th index represents the position in a ranking and how much has earned the i-th member of the population. E.g: rank = [3, 6, 7, 15,..., 1, 2] payoffs = [334, 54, 123, 34,..., 12, 100] The histograms: I plot the lists rank and payoffs as histograms, and I get something like this: The problem: I want to identify IN THE PAYOFFS' HISTOGRAM where are the members with the HIGHEST RANKING. I do not know how to get them, in order to plot them with different color.
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49015674
accepted answer: http://stackoverflow.com/a/49015674
tagged with: python

http://stackoverflow.com/q/48997474
has answer: http://stackoverflow.com/a/48998262
type: Question
answer count: 1
score: -1
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48998262
favorite count: 0
has body: I have this dataset: Field A A A B C C C D C C C A This has been read into pandas through the following code: data = read_csv('data.csv', header=None) print(data.describe()) How can I transform the column to get the below result? Field A A A Others C C C Others C C C A I want to transform values B and D, since they have low frequency, to an aggregate value "Others".
tagged with: aggregate
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Python - Group multiple values from a column to create "Other" values

multithreading
tags question: http://stackoverflow.com/q/49037570
tags question: http://stackoverflow.com/q/48993459
type: Tag
tags question: http://stackoverflow.com/q/49090416
tags question: http://stackoverflow.com/q/49121313
tags question: http://stackoverflow.com/q/49106526
tags question: http://stackoverflow.com/q/49025189
tags question: http://stackoverflow.com/q/49101624
tags question: http://stackoverflow.com/q/49035495
tags question: http://stackoverflow.com/q/49077039
tags question: http://stackoverflow.com/q/49096804
tags question: http://stackoverflow.com/q/48984512
tags question: http://stackoverflow.com/q/48970857
tags question: http://stackoverflow.com/q/49084922
tags question: http://stackoverflow.com/q/49019238
tags question: http://stackoverflow.com/q/49089235
tags question: http://stackoverflow.com/q/49081260
tags question: http://stackoverflow.com/q/49011601
tags question: http://stackoverflow.com/q/49036944
tags question: http://stackoverflow.com/q/49028537
tags question: http://stackoverflow.com/q/49061818
tags question: http://stackoverflow.com/q/49086827
tags question: http://stackoverflow.com/q/48971121
tags question: http://stackoverflow.com/q/49114725
tags question: http://stackoverflow.com/q/49063703
tags question: http://stackoverflow.com/q/49047255
tags question: http://stackoverflow.com/q/49073811
tags question: http://stackoverflow.com/q/49090208
tags question: http://stackoverflow.com/q/48993338
tags question: http://stackoverflow.com/q/48997207
tags question: http://stackoverflow.com/q/49080298
tags question: http://stackoverflow.com/q/49091372
tags question: http://stackoverflow.com/q/49010738
tags question: http://stackoverflow.com/q/48986505
tags question: http://stackoverflow.com/q/48979460
tags question: http://stackoverflow.com/q/48994243
tags question: http://stackoverflow.com/q/49110919
tags question: http://stackoverflow.com/q/48994440
tags question: http://stackoverflow.com/q/49020182
tags question: http://stackoverflow.com/q/49010952
tags question: http://stackoverflow.com/q/49121178
tags question: http://stackoverflow.com/q/49074715
tag name: multithreading
tags question: http://stackoverflow.com/q/49053956
tags question: http://stackoverflow.com/q/49082914

http://stackoverflow.com/q/49021823
favorite count: 0
has answer: http://stackoverflow.com/a/49022071
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85049288
has body: I understand that Python built-in types have a "truthiness" value, and the empty string is considered False, while any non-empty string is considered True. This makes sense I can check this using the built-in function bool. &gt;&gt;&gt; bool("") False &gt;&gt;&gt; bool("dog") True I can also make use of these truthiness values when using conditionals. For example: &gt;&gt;&gt; if "dog": ... print("yes") ... yes This is confusing This doesn't work with the == operator though: &gt;&gt;&gt; "dog" == True False &gt;&gt;&gt; "dog" == False False Can anyone explain why == seems to act differently than a conditional?
has comment: http://stackoverflow.com/comment/85048808
downvote count: 3
accepted answer: http://stackoverflow.com/a/49022071
type: Question
possible better answer: http://stackoverflow.com/a/49021934
has comment: http://stackoverflow.com/comment/85048778
tagged with: boolean
has comment: http://stackoverflow.com/comment/85048963
has answer: http://stackoverflow.com/a/49021934
upvote count: 5
has title: Understanding the truthiness of strings
tagged with: truthiness
has comment: http://stackoverflow.com/comment/85048812
answer count: 3
has answer: http://stackoverflow.com/a/49021882

http://stackoverflow.com/a/49110119
score: 3
downvote count: 0
has body: I recommend using collections.namedtuple: import collections Image = collections.namedtuple('Image',['size', 'values', 'cooridinates']) #for example my_image = Image([20, 200], [300,24], [209, 300]) #mock values then the output will be: In []: my_image Out[]: Image(size=[20, 200], values=[300, 24], cooridinates=[209, 300])
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49109903

matrix
tags question: http://stackoverflow.com/q/49052934
tags question: http://stackoverflow.com/q/49062092
tag name: matrix
tags question: http://stackoverflow.com/q/49120688
tags question: http://stackoverflow.com/q/48966782
tags question: http://stackoverflow.com/q/49001478
tags question: http://stackoverflow.com/q/48970179
tags question: http://stackoverflow.com/q/49048189
tags question: http://stackoverflow.com/q/48994666
tags question: http://stackoverflow.com/q/49010686
tags question: http://stackoverflow.com/q/49038622
tags question: http://stackoverflow.com/q/49038780
tags question: http://stackoverflow.com/q/49116389
tags question: http://stackoverflow.com/q/49023304
tags question: http://stackoverflow.com/q/48970514
tags question: http://stackoverflow.com/q/49019189
tags question: http://stackoverflow.com/q/49094026
tags question: http://stackoverflow.com/q/49005887
tags question: http://stackoverflow.com/q/48978463
tags question: http://stackoverflow.com/q/49001510
tags question: http://stackoverflow.com/q/49066690
tags question: http://stackoverflow.com/q/48967305
tags question: http://stackoverflow.com/q/48969217
tags question: http://stackoverflow.com/q/49055062
tags question: http://stackoverflow.com/q/49089407
tags question: http://stackoverflow.com/q/49080194
tags question: http://stackoverflow.com/q/49110245
tags question: http://stackoverflow.com/q/49060520
type: Tag
tags question: http://stackoverflow.com/q/49058586
tags question: http://stackoverflow.com/q/49036579

http://stackoverflow.com/comment/85126323
score: 2
comment on: http://stackoverflow.com/q/49060671
has text: You said that already. Please post the complete error message including traceback.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49097315
score: 3
downvote count: 0
has body: dicom.read_file() needs an open file object or a string for the path not a Path instance. If it is not a strings it considers it an open file and tries to read from it. Convert the Path instance to a string with str(path_object): for i in len(path_to_dcm_objects): record = dicom.read_file(str(path_to_dcm_objects[i])) The help for converting a Path object into a string: Return the string representation of the path, suitable for passing to system calls. You can also use: path_object.as_posix() This gives you a Posix path: Return the string representation of the path with forward (/) slashes. BTW, the pythonic way to iterate over all paths would look more like this: for path_obj in data.glob('**/*.dcm'): record = dicom.read_file(str(path_obj))
accepted answer of: http://stackoverflow.com/q/49097181
answers question: http://stackoverflow.com/q/49097181
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/85200103
type: Answer

http://stackoverflow.com/comment/85045979
type: QuestionComment
has text: "couldn't open "resources/bg.png": no such file or directory" Provide a /complete/path/to/the_file to tell the computer where to find it. Computers have no psychic powers.
comment on: http://stackoverflow.com/q/49018192
score: 0
type: Comment

http://stackoverflow.com/q/49086721
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/49190192
has comment: http://stackoverflow.com/comment/85187331
tagged with: mlogit
tagged with: python
tagged with: stata
type: AnsweredQuestion
score: 7
has title: Multinomial Logit model Python and Stata different results
upvote count: 7
type: Question
accepted answer: http://stackoverflow.com/a/49190192
has comment: http://stackoverflow.com/comment/85383906
has comment: http://stackoverflow.com/comment/85179836
has body: I am trying to build multinomial logit model using python and stata. My data is as follows: ses_type prog_type read write math prog ses 0 low Diploma 39.2 40.2 46.2 0 0 1 middle general 39.2 38.2 46.2 1 1 2 high Diploma 44.5 44.5 49.5 0 2 3 low Diploma 43.0 43.0 48.0 0 0 4 middle Diploma 44.5 36.5 45.5 0 1 5 high general 47.3 41.3 47.3 1 2 I am trying to predict prog using ses read write and math. Where ses represent socioeconomic status and is a nominal variable therefore I created my model in stata using following command: mlogit prog i.ses read write math, base(2) Stata output is as follows: Iteration 0: log likelihood = -204.09667 Iteration 1: log likelihood = -171.90258 Iteration 2: log likelihood = -170.13513 Iteration 3: log likelihood = -170.11071 Iteration 4: log likelihood = -170.1107 Multinomial logistic regression Number of obs = 200 LR chi2(10) = 67.97 Prob &gt; chi2 = 0.0000 Log likelihood = -170.1107 Pseudo R2 = 0.1665 ------------------------------------------------------------------------------ prog | Coef. Std. Err. z P&gt;|z| [95% Conf. Interval] -------------+---------------------------------------------------------------- 0 | ses | 1 | .6197969 .5059335 1.23 0.221 -.3718146 1.611408 2 | -.5131952 .6280601 -0.82 0.414 -1.74417 .7177799 | read | -.0405302 .0289314 -1.40 0.161 -.0972346 .0161742 write | -.0459711 .0270153 -1.70 0.089 -.09892 .0069779 math | -.0990497 .0331576 -2.99 0.003 -.1640373 -.0340621 _cons | 9.544131 1.738404 5.49 0.000 6.136921 12.95134 -------------+---------------------------------------------------------------- 1 | ses | 1 | -.3350861 .4607246 -0.73 0.467 -1.23809 .5679176 2 | -.8687013 .5363968 -1.62 0.105 -1.92002 .182617 | read | -.0226249 .0264534 -0.86 0.392 -.0744726 .0292228 write | -.011618 .0266782 -0.44 0.663 -.0639063 .0406703 math | -.0591301 .0299996 -1.97 0.049 -.1179283 -.000332 _cons | 5.041193 1.524174 3.31 0.001 2.053866 8.028519 -------------+------------------------------------------------------------…
tagged with: statistics
has comment: http://stackoverflow.com/comment/85193946
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85177244
type: Comment
comment on: http://stackoverflow.com/a/49085929
score: 0
type: AnswerComment
has text: Traceback (most recent call last): File "C:/Program Files (x86)/Python36-32/ak/t.py", line 12, in <module> print (paragraph) UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 378-378: Non-BMP character not supported in Tk

http://stackoverflow.com/q/49033473
has comment: http://stackoverflow.com/comment/85071720
upvote count: 1
tagged with: python
downvote count: 1
has body: I have the following code running and I would like to have the output of the script exported to a .txt file for later viewing. How could I go about doing this? import socket, threading def TCP_connect(ip, port_number, delay, output): TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) TCPsock.settimeout(delay) try: TCPsock.connect((ip, port_number)) output[port_number] = 'Listening' except: output[port_number] = '' def scan_ports(host_ip, delay): threads = [] # To run TCP_connect concurrently output = {} # For printing purposes # Spawning threads to scan ports for i in range(10000): t = threading.Thread(target=TCP_connect, args=(host_ip, i, delay, output)) threads.append(t) # Starting threads for i in range(10000): threads[i].start() # Locking the script until all threads complete for i in range(10000): threads[i].join() # Printing listening ports from small to large for i in range(10000): if output[i] == 'Listening': print(str(i) + ': ' + output[i]) def main(): host_ip = input("Enter host IP: ") delay = int(input("How many seconds the socket is going to wait until timeout: ")) scan_ports(host_ip, delay) if __name__ == "__main__": main() print ("Thank you for scanning") Any help would be greatly appreciated.
type: Question
tagged with: export
has comment: http://stackoverflow.com/comment/85071760
has title: How would I export my results to a .txt
has answer: http://stackoverflow.com/a/49033583
answer count: 1
favorite count: 0
score: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/85180299
type: Comment
comment on: http://stackoverflow.com/q/49053059
score: 0
type: QuestionComment
has text: I just updated the question. It now contains a minimal, complete, and verifiable example.

nlp
tags question: http://stackoverflow.com/q/49108041
tags question: http://stackoverflow.com/q/49029837
tags question: http://stackoverflow.com/q/49064114
tags question: http://stackoverflow.com/q/49039586
tags question: http://stackoverflow.com/q/49044379
tags question: http://stackoverflow.com/q/48967040
tags question: http://stackoverflow.com/q/49035812
tags question: http://stackoverflow.com/q/49087762
tags question: http://stackoverflow.com/q/49058777
tags question: http://stackoverflow.com/q/48970035
tags question: http://stackoverflow.com/q/48984071
tags question: http://stackoverflow.com/q/49094311
tags question: http://stackoverflow.com/q/49090600
tags question: http://stackoverflow.com/q/49098056
tags question: http://stackoverflow.com/q/48990935
tags question: http://stackoverflow.com/q/49081175
tags question: http://stackoverflow.com/q/49007346
tags question: http://stackoverflow.com/q/49109014
tags question: http://stackoverflow.com/q/49100615
tags question: http://stackoverflow.com/q/48973447
tags question: http://stackoverflow.com/q/49083826
tags question: http://stackoverflow.com/q/49010792
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/49091931
tags question: http://stackoverflow.com/q/48980120
tags question: http://stackoverflow.com/q/49104624
tags question: http://stackoverflow.com/q/49009386
tags question: http://stackoverflow.com/q/48986146
tags question: http://stackoverflow.com/q/49017069
tags question: http://stackoverflow.com/q/49081024

http://stackoverflow.com/comment/85071127
has text: Hey, are you sure the data is the same one in the link? because it doesn't have anything called tweets.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49029837
type: QuestionComment

http://stackoverflow.com/comment/85200841
type: Comment
type: QuestionComment
score: 0
has text: I also don't understand the problem. But I suggest you to remove the 3 blocks that look almost the same by using a dict with `ar`/`ir`/`er` as keys and lists of endings as values. Also, note that the lines: `list = zip(persons, conjugated_forms); final_conjugated_forms = dict(list)` don't have to be in loops.
comment on: http://stackoverflow.com/q/49095885

http://stackoverflow.com/comment/84961837
type: AnswerComment
comment on: http://stackoverflow.com/a/48971412
score: 0
type: Comment
has text: You are trying to create a list of objects? Do those object already exists in the code and now you need to iterate through them based on file or user input?

http://stackoverflow.com/comment/119123617
type: AnswerComment
comment on: http://stackoverflow.com/a/48968101
score: 0
type: Comment
has text: When this is done and you have an image that has transparent parts it comes up as white and not what the background colour is. I there any way to make the button transparent so all you could see is the image

http://stackoverflow.com/q/48992776
has body: I've used regular expressions module to get a sentence out of a string by using an adapted method from this post: Extract words surrounding a search word re.search(r'((keyword)\W+((?:\w+\W+){,22}', sentence) My resulting list looks like so: ['AL', 'KHOR\\r\\n&lt;https://www.fleetmon.com/vessels/al-khor-f_0_11569260&gt;', 'departed\\r\\nat'] How can I remove the url from the list element and the \r\n from the middle of the elements? Is there a way to exclude it in the re.search that would be better than trying to remove it after I've searched? EDIT: URL will vary as it relates to individual ships. The address is the same up to /vessels
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48992933
has comment: http://stackoverflow.com/comment/84993492
tagged with: python-3.x
has title: Remove a URL from a list element in Python
upvote count: 1
accepted answer: http://stackoverflow.com/a/48992933
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84990962
type: Question
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/17645701

http://stackoverflow.com/comment/85007056
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49000947
score: 1
has text: You have a for loop in which all paths do a return.

http://stackoverflow.com/q/49028399
type: Question
has comment: http://stackoverflow.com/comment/85061374
score: 0
answer count: 2
tagged with: trace
linked to: http://stackoverflow.com/q/48988799
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49028672
has title: Creating/destroying widgets with tkinter depending on a traced variable
tagged with: python
has body: I would like to create a button depending on the current status of an entry widget: If there is something written there, the button should be created, but if it is cleared again, the button should be destroyed again. In the following code I achieved something 'similar': from tkinter import * from tkinter import Tk root = Tk() check = StringVar() def create(*args): if check.get() != '': grid_014 = Button(root, width=40, text='something changed', bd=5) else: grid_014 = Label(root, width=40, text='', bd=5) grid_014.grid(column=1, row=2) grid_entry = Entry(root, width=40, textvariable=check) grid_entry.grid(column=1, row=1) check.trace('w', create) root.mainloop() But then I realized, not quite. Because, as far as I understand, what I am doing is replacing the button widget with the label widget and vice versa, always on top of each other. This is visible, because the boundary of the button widget does not vanish. As far as I understand, this is also creating a memory leak. My question now is, what would be the best way of 'clearing' the previous widget if a change in the entry widget causes a change in the if condition? The reason behind this is, that I want to give the user of the program possibilities to interact with certain parts of it, only if certain conditions are met before, say a 'save' button would only appear, after a file name is written, things like this. For instance, rather than destroying a widget greying it out, using a traced variable, could be an alternative. (A working solution for this is given by the link of Nae, thanks (!), using the 'normal' and 'disabled' state of a button; However, I would like to see other suggestions, too, which would comment on the possibility of clearing widgets, too, because in the general case, as given in the above code, it would not be the same widget in the if condition, thus one would not be able to use 'normal'/'disabled' state of the same widget).
tagged with: tkinter
has answer: http://stackoverflow.com/a/49029033

http://stackoverflow.com/comment/85066318
score: 0
type: Comment
type: QuestionComment
has text: Yes, I mean z-order. I just moved code from `QMainWindow` to `QWidget` and added custom `QLayout`.
comment on: http://stackoverflow.com/q/49029780

http://stackoverflow.com/comment/85037023
has text: Why do you need a `while` ? If there is a requirement for loop on condition use `if` and `while` nested.
score: 0
comment on: http://stackoverflow.com/q/49016088
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49238364
has body: paramiko definitely won't help to leverage the Python modules present on remote machines. Python is definitely meant for distributed systems. For this, one solution I can think of is need to use Remote Procedure Call mechanism. There are several modules in Python using which you can achieve RPC. XML-RPC (In-Built) RPyC PyRo Stackoverflow link with multiple Python RPC solutions. Some links with comparison between above three Pyro and RPyC XML-RPC vs PyRo
score: 0
answers question: http://stackoverflow.com/q/49070442
type: Answer

http://stackoverflow.com/comment/84979059
score: 0
type: Comment
type: QuestionComment
has text: shouldn't you be passing like `MyThread(target = add, args = (a, b))`
comment on: http://stackoverflow.com/q/48986505

http://stackoverflow.com/comment/84943203
comment on: http://stackoverflow.com/q/48967987
type: QuestionComment
type: Comment
has text: Also, make totally sure whether `process_countries()` is being called or not. Like set a breakpoint inside it, or print something out at the beginning of it.
score: 0

http://stackoverflow.com/a/49050472
type: Answer
upvote count: 17
has comment: http://stackoverflow.com/comment/85105321
downvote count: 0
has comment: http://stackoverflow.com/comment/85105628
score: 17
has comment: http://stackoverflow.com/comment/121714372
accepted answer of: http://stackoverflow.com/q/49050455
has comment: http://stackoverflow.com/comment/85105342
answers question: http://stackoverflow.com/q/49050455
type: AcceptedAnswer
has body: I think you need groupby with custom lambda function or with loop: f = lambda x: x.to_csv(os.getcwd() + "/data_{}.csv".format(x.name.lower()), index=False) df.groupby('CITY').apply(f) for i, x in df.groupby('CITY'): x.to_csv(os.getcwd() + "/data_{}.csv".format(i.lower()), index=False) EDIT by comment, thanks @Anton vBR: for i, x in df.groupby('CITY'): p = os.path.join(os.getcwd(), "data_{}.csv".format(i.lower())) x.to_csv(p, index=False)
has comment: http://stackoverflow.com/comment/85105341

http://stackoverflow.com/a/49027387
downvote count: 0
type: Answer
has body: It looks like the final slice is just to remove an unused :, so how about: print(':'.join(map(str, range(20, 1, -3)))) Python is generally not about compactness but readability.
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49027271
has comment: http://stackoverflow.com/comment/85059985

http://stackoverflow.com/comment/84981975
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48986863
has text: Are the server and client on the same host?
score: 0

http://stackoverflow.com/q/49089984
type: Question
has comment: http://stackoverflow.com/comment/85185513
tagged with: proxy
tagged with: openssl
score: 0
has title: Request/Proxy error in my Python application
has body: I try making a request using this proxy but keep getting this same error. Proxies in the PaaS have worked fine but these are from a new provider and I'm getting this issue with all of their proxies. import requests proxies = {'http': 'http://104.153.47.242:1374', 'https': 'https://104.153.47.242:1374'} r = requests.get('https://undefeated.com/products.json',proxies=proxies) print (r.status_code) The error: Traceback (most recent call last): File "proxtest.py", line 5, in &lt;module&gt; r = requests.get('https://undefeated.com/products.json',proxies=proxies) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 72, in get return request('get', url, params=params, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/adapters.py", line 506, in send raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='undefeated.com', port=443): Max retries exceeded with url: /products.json (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_record', 'wrong version number')],)",),)) Can you help please?
has comment: http://stackoverflow.com/comment/85188116
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85185467
answer count: 0
has comment: http://stackoverflow.com/comment/85185507
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85185554
tagged with: ssl

http://stackoverflow.com/q/48993695
duplicate of: http://stackoverflow.com/q/11017466
has answer: http://stackoverflow.com/a/48993953
tagged with: azure
tagged with: python
has title: Share file from python-flask app from azure app service
score: -1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20646822
downvote count: 1
tagged with: azure-storage
type: Question
accepted answer: http://stackoverflow.com/a/48993953
has body: I've a python-flask webapp which is deployed on Azure which serves as backend for a chatbot. Based on the user query, the bot performs an action and saves the file locally. This file needs to be shared to the user. Is there a way that I can share a hyperlink to the user in chat for the user to download the file without having to create a storage on azure. (The file need not be stored and can be deleted after a timeout. File sizes are very small(10-20 kB))
has comment: http://stackoverflow.com/comment/84992789
duplicate of: http://stackoverflow.com/q/20646822
tagged with: chatbot
upvote count: 0
answer count: 1
tagged with: flask
favorite count: 0

http://stackoverflow.com/comment/85070897
has text: Out of interest, have you ever done any programming before? And if so, from which language have you come?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49032953
score: 0

http://stackoverflow.com/comment/85137107
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49065465
has text: The class source code isn't available to display in Jupyter-console
type: AnswerComment

http://stackoverflow.com/a/49108278
upvote count: 4
has comment: http://stackoverflow.com/comment/85222087
type: AcceptedAnswer
downvote count: 0
has body: You can use itertools.groupy with a list-comprehension to achieve your result &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; d = {1: 'a', 2:'b', 3:'c', 4:'c', 5:'c', 6:'c'} &gt;&gt;&gt; n = [(min([k[0] for k in list(g)]),k) for k,g in groupby(d.items(),key=lambda x: x[1])] &gt;&gt;&gt; n &gt;&gt;&gt; [(1, 'a'), (2, 'b'), (3, 'c')] The above expression can also be written as &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; n = [(min(map(itemgetter(0), g)), k) for k, g in groupby(d.items(), key=itemgetter(1))] You can cast this to dict by simply using &gt;&gt;&gt; dict(n) &gt;&gt;&gt; {1: 'a', 2: 'b', 3: 'c'} This obviously don't maintain order of keys, so you can use OrderedDict &gt;&gt;&gt; OrderedDict(sorted(n)) &gt;&gt;&gt; OrderedDict([(1, 'a'), (2, 'b'), (3, 'c')])
score: 4
answers question: http://stackoverflow.com/q/49107640
type: Answer
accepted answer of: http://stackoverflow.com/q/49107640
has comment: http://stackoverflow.com/comment/85221597
has comment: http://stackoverflow.com/comment/85222373

http://stackoverflow.com/comment/85148311
type: AnswerComment
has text: Maybe, let's see if someone else proposes something different. If not, I will select your answer in a day or so.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49059505

http://stackoverflow.com/a/49058228
type: Answer
accepted answer of: http://stackoverflow.com/q/49058179
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: I am assuming you are using the Keras to_categorical method which computes a one-hot encoding matrix such that each row is the one-hot encoded label of a training sample. In that case, your comparison is not correct. You need to first find where the elements are not equal, then impose that if any of them are not correct, you write out the image to file. Therefore, first find all positions where the one-hot encoding vector do not correspond to each other: y_pred[i] != y_test[i] and only then do you impose the any method on it that checks for any elements that aren't equal (y_pred[i] != y_test[i]).any(). This means your if statement needs to change: for i in range(0, len(y_test)): if (y_pred[i] != y_test[i]).any(): # Change image = x_test_copy[i] path = 'path' cv2.imwrite(os.path.join(path , str(i)+'.jpg'), image)
answers question: http://stackoverflow.com/q/49058179

http://stackoverflow.com/comment/106689691
type: AnswerComment
has text: just stumbled upon your solution. did you check for ```[[1,4],[2,3]]```? I think it will fail.let me know if I am mistaken.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49076157

http://stackoverflow.com/comment/85242067
type: Comment
type: QuestionComment
has text: Your code (the bottom example) works without error on both Python 2.7 and Python 3.6
comment on: http://stackoverflow.com/q/49117806
score: 0

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/49058713
tags question: http://stackoverflow.com/q/49023789
type: Tag

http://stackoverflow.com/comment/84959634
comment on: http://stackoverflow.com/a/48977105
type: AnswerComment
has text: Do you expect me to be chasing changing requirements? I answered the question as presented. I frankly saw your stacked if as a naive implementation, not a requirement.
type: Comment
score: 1

http://stackoverflow.com/q/49048413
has answer: http://stackoverflow.com/a/49164956
score: 0
answer count: 1
tagged with: fipy
has comment: http://stackoverflow.com/comment/85243241
type: UnansweredQuestion
tagged with: python
has body: I am interesting in solving differential equation using fipy. The following code is working correctly when I am using Grid2D. from fipy import * mesh = Grid2D(nx=3, ny=3) #mesh = Grid3D(nx=3, ny=3, nz=3) phi = CellVariable(name='solution variable', mesh=mesh, value=0.) phi.constrain(0, mesh.facesLeft) phi.constrain(10, mesh.facesRight) coeff = CellVariable(mesh=mesh, value=1.) eq = DiffusionTerm(coeff) == 0 eq.solve(var=phi) When I am using Grid3D instead of Grid2D (commented line), I get following error: Traceback (most recent call last): File "/home/user/Programming/python/fdms/forSo.py", line 11, in &lt;module&gt; eq.solve(var=phi) File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/terms/term.py", line 211, in solve solver = self._prepareLinearSystem(var, solver, boundaryConditions, dt) File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/terms/term.py", line 169, in _prepareLinearSystem diffusionGeomCoeff=self._getDiffusionGeomCoeff(var), File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/terms/abstractDiffusionTerm.py", line 458, in _getDiffusionGeomCoeff return self._getGeomCoeff(var) File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/terms/term.py", line 465, in _getGeomCoeff self.geomCoeff = self._calcGeomCoeff(var) File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/terms/abstractDiffusionTerm.py", line 177, in _calcGeomCoeff tmpBop = (coeff * FaceVariable(mesh=mesh, value=mesh._faceAreas) / mesh._cellDistances)[numerix.newaxis, :] File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/variables/variable.py", line 1151, in __mul__ return self._BinaryOperatorVariable(lambda a,b: a*b, other) File "/home/user/Programs/miniconda2/envs/FipyEnv2/lib/python3.6/site-packages/fipy/variables/variable.py", line 1116, in _BinaryOperatorVariable if not v.unit.isDimensionless() or le…
has title: Fipy Grid3D 'an index can only have a single ellipsis' error
type: Question

http://stackoverflow.com/comment/84963374
type: Comment
has text: Someone correct me if I am wrong, but you should be able to just download the `win_amd64` installer from the PyPI [pygame package index](https://pypi.python.org/pypi/Pygame). Match up the version of Python that you are using with the version in the download file name. For example, `cp34` relates to Python 3.4. Once you have downloaded the `.whl` file you can look at [this article](https://www.webucator.com/blog/2015/03/installing-the-windows-64-bit-version-of-pygame/) which will tell you how to install the wheel file using pip.
comment on: http://stackoverflow.com/q/48976342
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85761617
type: AnswerComment
score: 0
type: Comment
has text: Sounds like there are not only numeric values in the file, is that correct?
comment on: http://stackoverflow.com/a/49112903

http://stackoverflow.com/q/49053739
answer count: 1
favorite count: 0
upvote count: 14
tagged with: python
has title: sqlalchemy how to generate (many-to-many) relationships with automap_base
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49399347
tagged with: orm
has body: As a background: I'm creating an ORM based on a schema of an already existing database. - This due to the fact that the python application won't be the "owner" of said database. Now in this database there is a table called "task" and a table called "task_notBefore__task_relatedTasks" - this latter is a many-to-many relation between different entries in the "task" table. now automap_base() has an automated detection of these relationships as described here. However this fails for my case, and no relationship is being build. I then try to manually create the relationship: from sqlalchemy.ext.automap import automap_base from sqlalchemy.ext.automap import generate_relationship from sqlalchemy.orm import sessionmaker, interfaces, relationship from sqlalchemy import create_engine class DBConnection: def __init__(self, connection_url, **kwargs): self.engine = create_engine(connection_url, **kwargs) self._Base = automap_base() self._Base.prepare(self.engine, reflect=True) self.Task = self._Base.classes.task self.Order = self._Base.classes.order self.Poller = self._Base.classes.poller rel = generate_relationship(self._Base, interfaces.MANYTOMANY, relationship, 'related', self.Task, self.Task, secondary=self._Base.classes.task_notBefore__task_relatedTasks, backref='notBefore') self._Session = sessionmaker() self._Session.configure(bind=self.engine) self.session = self._Session() However this still doesn't "do" anything: it doesn't add anything to the self.Task "class". How would one do this?
tagged with: sqlalchemy
type: Question
score: 14
tagged with: many-to-many

numba
tags question: http://stackoverflow.com/q/49090810
tags question: http://stackoverflow.com/q/49051835
tags question: http://stackoverflow.com/q/49058729
tags question: http://stackoverflow.com/q/49092630
tags question: http://stackoverflow.com/q/49074194
tag name: numba
tags question: http://stackoverflow.com/q/49102528
tags question: http://stackoverflow.com/q/49028860
tags question: http://stackoverflow.com/q/49075935
type: Tag
tags question: http://stackoverflow.com/q/49017958
tags question: http://stackoverflow.com/q/49089713
tags question: http://stackoverflow.com/q/49057801

http://stackoverflow.com/q/49093916
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85192998
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/85193179
has comment: http://stackoverflow.com/comment/85193593
tagged with: list
has comment: http://stackoverflow.com/comment/85193066
has answer: http://stackoverflow.com/a/49096502
has title: Checking to see if a list is sorted
downvote count: 3
type: Question
has body: I've tried sorted, value_sort, all(a, b...zip), etc. but my function to check if the list is sorted, "is_solved" will not work. The function should check if the list of marbles is sorted in ascending order. I've commented out other approaches that I've tried that haven't worked. Any help would be most appreciated. def is_solved(self, list_of_marbles, i): #returns true if the game is solved if self.list_of_marbles[i] &lt; self.list_of_marbles[i+1]: #all(self.list_of_marbles[i] &lt;= self.list_of_marbles[i+1] for i #in range(len(self.list_of_marbles)-1)) #if self.is_solved(board2, i) == True: #if self.list_of_marbles[i] &lt; self.list_of_marbles[i+1]: return True else: return False
tagged with: sorting
answer count: 2
linked to: http://stackoverflow.com/q/3755136
has comment: http://stackoverflow.com/comment/85193520
has answer: http://stackoverflow.com/a/49096035
upvote count: 0
has comment: http://stackoverflow.com/comment/85193137
tagged with: undefined
has comment: http://stackoverflow.com/comment/85193015
favorite count: 0

http://stackoverflow.com/q/49072866
tagged with: while-loop
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: once again thank you in advance for any help you might be able to give me. I have a data set that has all values for devices on a fiber network, rolling down from a central node to a node's multiple amplifier,and finally to all addresses attached to that node. The issue is that there can be multiple amps between the node and an address. I am trying to find which node each address is attached to. Each device(address, amp, node) has an ID, DEVICE_TYPE_DESC and a UPSTREAM_DEVICE_ID. So as an example: ID:1 DEVICE_TYPE_DESC:ADDRESS UPSTREAM_DEVICE_ID: 2 ID:2 DEVICE_TYPE_DESC:AMP UPSTREAM_DEVICE_ID: 3 ID:3 DEVICE_TYPE_DESC:AMP UPSTREAM_DEVICE_ID: 4 ..... ID:10 DEVICE_TYPE_DESC:NODE UPSTREAM_DEVICE_ID: 9 So I want to be able to join ID:1 to ID:10, but to do that I need to join to each and every amp in between. I'm new to python so I'm not sure if what I am trying to do is even possible, but I'm working on creating a while loop that will iteratively join to the device table again, and create a flag that will change to 1 when the join brings in the node, and stop when the sum of the node_flag=len(address_table). I have written the code to manually join for the first round, and partially written what I think the general look of the while loop might look like. The main issue I am having is trying to figure out how to rename the columns in the right table each time, and then using that most recently appended 'upstream_device_id' to use as the left key for the next iteration of joining. ADD_DEV is a filtered table from DEVICE that contains only addresses. NO_ADD is a second filtered table from DEVICE that contains everything else except addresses add_dev.merge( no_add"id","device_type","upstream_device_id", how="left", left_on="upstream_id", right_on="id" ) add_dev["left_join"] = add_dev["upstream_device_id"] count = len(add_dev.index) x=0 while count &gt; 0: x=x+1 add_dev.merge( no_add"id","device_type","upstream_device_id".rename( index=str, columns={ "id":"id_[x]", "d…
tagged with: python
score: 2
upvote count: 2
tagged with: join
has title: While loop to join panda dataframes
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/49074988

http://stackoverflow.com/comment/85229000
type: QuestionComment
comment on: http://stackoverflow.com/q/49109884
has text: Instead of including the JS in your template, just pass a JSON object with a 'log' of the fight. Keep all your JS in a separate file, when you want to 'run' the fight, just make an AJAX request using JS to your Django server. In the success function of your AJAX you'll have your JSON for the fight, you can then use an interval in JS to replay it slowly. See this question: https://stackoverflow.com/questions/1445989/passing-python-data-to-javascript-via-django
score: 0
type: Comment

http://stackoverflow.com/comment/85013855
score: 0
type: Comment
type: AnswerComment
has text: just use explode function on event_date and you should be fine
comment on: http://stackoverflow.com/a/48991071

http://stackoverflow.com/comment/85164389
type: Comment
comment on: http://stackoverflow.com/a/49079215
has text: I like this, but instead of using `__dict__` directly, do something like `namespace = vars(self)` then `namespace[s1] += namespace[s2]` At the very least, since performance seems to be an issue, you're avoiding an extra attribute look-up, plus I think it just reads nicer
type: AnswerComment
score: 1

http://stackoverflow.com/a/49105552
has body: To me it looks like you might getting individual rows from the reader. I'm guessing these are probably available via index. for row in reader url.append = urllib.unquote(row[0]).decode('utf8') There is a also a DictReader in case list abstraction doesn't suffice.
type: Answer
answers question: http://stackoverflow.com/q/49105159
score: 0

http://stackoverflow.com/comment/116595495
type: Comment
type: QuestionComment
has text: This question really isn't on-topic here.
comment on: http://stackoverflow.com/q/48973038
score: 0

http://stackoverflow.com/comment/85239802
comment on: http://stackoverflow.com/a/49077235
has text: np.where(TableC.Field1_x.isin([1000 , 800 , 700]),20,0) @babz
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84944763
score: 0
has text: Expected result.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48969595

http://stackoverflow.com/a/49000236
has body: I believe the API asked for application/json, if this is really the case, you should send it like this headers = {} update_contact = {"import_data": [{"email_addresses": ["test@test.com"],"first_name": "test","last_name": "test"},{"email_addresses": ["Jane@Doe.com"],"first_name": "Jane","last_name": "Doe"}, {"email_addresses": ["Pradeep@Patel.com"],"first_name": "Pradeep","last_name": "Patel"}],"lists": ["1234567890"]} r = requests.post('url', headers=headers ,json= update_contact) print(r.text)
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85005663
has comment: http://stackoverflow.com/comment/85005681
score: 3
answers question: http://stackoverflow.com/q/49000198
has comment: http://stackoverflow.com/comment/85005763
has comment: http://stackoverflow.com/comment/85072002
upvote count: 3
has comment: http://stackoverflow.com/comment/85005779

http://stackoverflow.com/q/49052983
tagged with: python
has comment: http://stackoverflow.com/comment/85110908
has answer: http://stackoverflow.com/a/49342891
type: AnsweredQuestion
tagged with: odoo-11
tagged with: pycharm
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/49054457
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/85112879
possible better answer: http://stackoverflow.com/a/49342891
type: Question
answer count: 2
has title: Odoo 11 : ImportError No Module Named 'PyPDF2'
has answer: http://stackoverflow.com/a/49054457
has comment: http://stackoverflow.com/comment/85110528
has comment: http://stackoverflow.com/comment/85112985
upvote count: 1
has comment: http://stackoverflow.com/comment/85111517
has body: I'm using a script to run Odoo11 via PyCharm in Ubuntu (openerp_openserver script) When I try to run the program, it fails at some point, when it import pdf module and I have this error: ImportError No Module Named 'PyPDF2' as you can see in this image: I Already installed PyPDF2 via this command (i have python3.5 already installed) : sudo apt-get install python3-pypdf2 So I'm wondering, what is the problem, why PyCharm cannot find and import pypdf2? EDIT: When I Try to import PyPDF2 using the Python command, I don't have error
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85112965

http://stackoverflow.com/comment/85193305
type: QuestionComment
has text: It would be nice to know what your pattern is supposed to be doing, unless this is a purely academic question, in which case you should mention that.
comment on: http://stackoverflow.com/q/49094060
score: 0
type: Comment

http://stackoverflow.com/comment/84958717
type: Comment
type: QuestionComment
has text: Can you post a sample of `z230`? Also, how many unique values are in your number range?
comment on: http://stackoverflow.com/q/48976764
score: 0

http://stackoverflow.com/comment/85099397
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/49047517
has text: `[hex(ord(x))[2:] for x in list_input]`?
type: Comment

tcp
type: Tag
tags question: http://stackoverflow.com/q/49106456
tags question: http://stackoverflow.com/q/48979150
tag name: tcp
tags question: http://stackoverflow.com/q/49039653

http://stackoverflow.com/a/49027181
downvote count: 0
score: 1
has body: You can use in to check if value is in tuple. Ex: d = [(123456, '123_ABC', 'abc123defa', '/path/whatever', 11111, 'YES'),(789456, '123_DEF', 'abc123defb', '/path/whatever/0', 11111, 'NO'),(234567, '123_GHI', 'abc123defc', '/path/whatever/1', 11111, 'NO')] for i in d: if 789456 in i: print i Output: (789456, '123_DEF', 'abc123defb', '/path/whatever/0', 11111, 'NO')
has comment: http://stackoverflow.com/comment/85058953
has comment: http://stackoverflow.com/comment/85059088
answers question: http://stackoverflow.com/q/49027108
upvote count: 1
has comment: http://stackoverflow.com/comment/85059334
has comment: http://stackoverflow.com/comment/85059079
type: Answer

http://stackoverflow.com/comment/85022491
score: 0
comment on: http://stackoverflow.com/q/49009114
has text: sorry I had to add a lot of thanks or I couldn't post the question as there is a lot of code.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49058317
has body: I suspect the problem is to do with contour labels, which are known not to work well in Cartopy (see https://github.com/SciTools/cartopy/issues/13 and https://github.com/SciTools/cartopy/issues/327). If you remove the labels the contours should render correctly.
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49048411
has comment: http://stackoverflow.com/comment/85151787
has comment: http://stackoverflow.com/comment/85147819

http://stackoverflow.com/comment/85109712
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49051910
has text: test_data.rdd.take(1) ? can you show us the data a little bit ?
score: 0

http://stackoverflow.com/a/49114772
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Use -2 to get the second from last. json_stub[-2] In Python negative index points to an element from right-to-left of the list as opposed to the default left-to-right. -1 for the the last element (left-to-right), -2 for the second from last (left-to-right) etc.
type: Answer
accepted answer of: http://stackoverflow.com/q/49114714
answers question: http://stackoverflow.com/q/49114714
upvote count: 2

http://stackoverflow.com/a/49000590
has comment: http://stackoverflow.com/comment/85006524
downvote count: 0
answers question: http://stackoverflow.com/q/49000514
has comment: http://stackoverflow.com/comment/85006447
type: Answer
score: 2
has body: Is this what you are after: ( poke_df.apply(lambda x: x.apply(pd.Series) .stack() .reset_index(level=1, drop=True)) .rename_axis('Type') .reset_index() ) Out[885]: Type Basic Evo1 Evo2 0 Fire Cyndaquil Quilava Typhlosion 1 Fire Charmander Chameleon Charizard 2 Fire Torchic Combusken Blaziken 3 Grass Chikorita Bayleef Meganium 4 Grass Bulbasaur Ivysaur Venusaur 5 Grass Treecko Grovyle Sceptile 6 Water Totodile Croconaw Feraligatr 7 Water Squirtle Wartortle Blastoise 8 Water Mudkip Marshtomp Swampert
upvote count: 2

http://stackoverflow.com/a/49004284
type: Answer
downvote count: 2
has body: You can use the csv module to read the file as a csv remove the columns and write it to a different file.
answers question: http://stackoverflow.com/q/49004148
upvote count: 1
score: -1

http://stackoverflow.com/a/49007287
score: 0
answers question: http://stackoverflow.com/q/49007215
has body: It's not clear whether you want a critique of your current attempt or a pythonic solution. Below is one way where output is a dictionary. from collections import Counter mystr = "Foo Fighters" c = Counter(mystr) Result Counter({' ': 1, 'F': 2, 'e': 1, 'g': 1, 'h': 1, 'i': 1, 'o': 2, 'r': 1, 's': 1, 't': 1}) Output as list I purposely do not combine the tuples in this list, as it's a good idea to maintain structure until absolutely necessary. It's a trivial task to combine these into one list of strings. list(c.items()) # [('F', 2), # ('o', 2), # (' ', 1), # ('i', 1), # ('g', 1), # ('h', 1), # ('t', 1), # ('e', 1), # ('r', 1), # ('s', 1)]
has comment: http://stackoverflow.com/comment/85019030
type: Answer
has comment: http://stackoverflow.com/comment/85025929
has comment: http://stackoverflow.com/comment/85026115

http://stackoverflow.com/q/48966639
tagged with: python
accepted answer: http://stackoverflow.com/a/48966666
tagged with: module
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48966718
has comment: http://stackoverflow.com/comment/84938937
has answer: http://stackoverflow.com/a/48966718
has comment: http://stackoverflow.com/comment/84938966
score: 0
answer count: 2
has title: Finding which script contains a particular function or class
favorite count: 0
has answer: http://stackoverflow.com/a/48966666
has body: How can I find out the file path and correct script containing a particular function or class of a module? Example: Say I want to take a look at the tkinter source code for tkinter.Button(). I found where the __init__.py file is located for tkinter using: &gt;&gt;&gt;import tkinter &gt;&gt;&gt;tkinter.__file__ 'C:\\Users\\Simon\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\tkinter\\__init__.py' I searched through that folder but was unable to locate any function or class named Button. My guess that it is contained inside the run-times and not a .py file but I am not definite and want to be sure of this. I could not find anything useful in the Python documentation special attributes either. Any suggestions are welcome but please note that this post is not set only on the tkinter module but most packages or modules, tkinter just being an example.
linked to: http://stackoverflow.com/q/697320

http://stackoverflow.com/comment/85345904
type: AnswerComment
comment on: http://stackoverflow.com/a/49147938
score: 0
type: Comment
has text: That's amazing! Thanks a lot! :) Also, could you tell me how i could extract the digits if they touch the top or the bottom horizontal lines? Like in the case of an image as such: https://www.dropbox.com/s/o4swx5821v5qea7/4K1CDD61780143.jpg?dl=0

http://stackoverflow.com/a/49073540
has comment: http://stackoverflow.com/comment/85171044
upvote count: 13
score: 13
answers question: http://stackoverflow.com/q/49073252
has comment: http://stackoverflow.com/comment/85154114
accepted answer of: http://stackoverflow.com/q/49073252
has comment: http://stackoverflow.com/comment/85153170
has comment: http://stackoverflow.com/comment/85152886
has comment: http://stackoverflow.com/comment/85171359
has comment: http://stackoverflow.com/comment/85153997
type: AcceptedAnswer
downvote count: 0
has body: Here is one way. Solution import pandas as pd df = pd.DataFrame({'A': ['AV', 'AV Snow', 'Test', 'AV (Some)', 'Nothing', 'Me AV', 'Available', 'NA']}) df = df[df['A'].str.contains('AV', regex=False, case=False, na=False)] Result A 0 AV 1 AV Snow 3 AV (Some) 5 Me AV 6 Available Explanation regex=False disables regex as it is not required for your particular task. case=False makes the search case insensitive. na=False means you won't see errors if there are unusual types in your series, e.g. non-strings.
has comment: http://stackoverflow.com/comment/85174828
has comment: http://stackoverflow.com/comment/85176136
has comment: http://stackoverflow.com/comment/85153926
has comment: http://stackoverflow.com/comment/85152980
type: Answer

http://stackoverflow.com/a/57204835
answers question: http://stackoverflow.com/q/49084143
downvote count: 0
has comment: http://stackoverflow.com/comment/135708627
type: Answer
has comment: http://stackoverflow.com/comment/135571145
score: 9
upvote count: 9
has body: I'm the author of VidGear Video Processing python library that now also provides NetGear API, which is exclusively designed to transfer video frames synchronously between interconnecting systems over the network in real-time. You try it as follows: A. Server End:(Bare-Minimum example) Open your favorite terminal and execute the following python code: Note: You can end streaming anytime on both server and client side by pressing [Ctrl+c] on your keyboard on server end! # import libraries from vidgear.gears import VideoGear from vidgear.gears import NetGear stream = VideoGear(source='test.mp4').start() #Open any video stream server = NetGear() #Define netgear server with default settings # infinite loop until [Ctrl+C] is pressed while True: try: frame = stream.read() # read frames # check if frame is None if frame is None: #if True break the infinite loop break # do something with frame here # send frame to server server.send(frame) except KeyboardInterrupt: #break the infinite loop break # safely close video stream stream.stop() # safely close server writer.close() B. Client End:(Bare-Minimum example) Then open another terminal on the same system and execute the following python code and see the output: # import libraries from vidgear.gears import NetGear import cv2 #define netgear client with `receive_mode = True` and default settings client = NetGear(receive_mode = True) # infinite loop while True: # receive frames from network frame = client.recv() # check if frame is None if frame is None: #if True break the infinite loop break # do something with frame here # Show output window cv2.imshow("Output Frame", frame) key = cv2.waitKey(1) & 0xFF # check for 'q' key-press if key == ord("q"): #if 'q' key-pressed break out break # close output window cv2.destroyAllWindows() # safely close client client.close() NetGear as of now supports two ZeroMQ messaging patterns: i.e zmq.PAIR and zmq.REQ and zmq.REP and the supported protocol are: 'tcp' and 'ipc' More advanced usage c…

http://stackoverflow.com/comment/85179533
score: 0
comment on: http://stackoverflow.com/q/49083727
has text: Have you stored the value of `latitude, longitude` in location? That's a tuple and should be accessed as `location[0]` for latitude and `location[1]` for longitude
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85126375
score: 0
has text: I don't have access to Pandas on this machine (which I agree is ridiculous). I could possibly do a user-only install. I was hoping that numpy had something fast that would suffice, but if someone has a pandas one-liner then I'll get to work on making Pandas happen.
comment on: http://stackoverflow.com/q/49060645
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49092491
downvote count: 0
has comment: http://stackoverflow.com/comment/85203574
type: Answer
has comment: http://stackoverflow.com/comment/85202962
has comment: http://stackoverflow.com/comment/85203375
has comment: http://stackoverflow.com/comment/85203317
score: 2
has comment: http://stackoverflow.com/comment/85202486
upvote count: 2
has comment: http://stackoverflow.com/comment/85203236
answers question: http://stackoverflow.com/q/49092258
accepted answer of: http://stackoverflow.com/q/49092258
has comment: http://stackoverflow.com/comment/85195716
has comment: http://stackoverflow.com/comment/85203170
has comment: http://stackoverflow.com/comment/85201934
has body: If you only need to check 3 variables, I would use an if, else if block. It ends up being pretty quick. Please note that this assumes your askGoogle(term1, self.queryParams(term1)) that I took from your question works properly and you've imported numpy as np. def askOracle(term1, term2, term3): if term1 != np.nan and askGoogle(term1, self.queryParams(term1)) != 'NotFound': return term1 elif term1 != np.nan and askGoogle(term1, self.queryParams(term1)) != 'NotFound': return term2 elif term1 != np.nan and askGoogle(term1, self.queryParams(term1)) != 'NotFound': return term3 else: return 'Nothing found' Also note that this will run askGoogle() at least once for term one. To fix this you'll have to split the if statement into the two ifs for all three terms. if term1 != np.nan: return term1 elif askGoogle(term1, self.queryParams(term1)) != 'NotFound': return term1 If you can place term1, term2, term3 in a list we can loop through the list making the code a bit shorter. Putting all the pieces together I came up with this. The below has also been updated to return the result of query instead of the term1 as this requirement was added in a comment. l = [term1, term2, term3] def askOracle(l): for term in l: if term != np.nan: return askGoogle(term, self.queryParams(term)) query = askGoogle(term, self.queryParams(term)) if query != 'NotFound': return query return 'Nothing found' then call the method by passing the list l like so askOracle(l) Old Answer (before question was revised and the fact that a dictionary is not used was clarified in the comments): Firstly, I wanted to note that dictionaries are not ordered in python (before python 3.6, as noted by @johnashu) so you cannot loop through the keys and values in the dictionary in order, which could have been a nice solution otherwise. For the answer below I am assuming that when you say nan and notFound you mean the dictionary contains the strings 'nan' and 'NotFound'. If you are looking for whether 'term1' is actually a k…
type: AcceptedAnswer

http://stackoverflow.com/q/49097915
tagged with: python
has comment: http://stackoverflow.com/comment/85203386
linked to: http://stackoverflow.com/q/48621130
answer count: 0
has comment: http://stackoverflow.com/comment/85201234
tagged with: python-requests
type: Question
has body: i want to send mulitpart/form-data to a server. it is working fine with postman . But when i use python requests it is giving 500 error. create_api = "http://..." AuthToken = "bearer ...." headers = {} headers["content-type"] = 'multipart/form-data' headers["Authorization"] = AuthToken data = {} data["owner"] = "test" data["email"] = "" data["mobile"] = "" data["badge"] = "" req = requests.post(create_api,data=data,headers=headers) when i print req.content it is showing the status code 500 i went through so many related questions in stackoverflow. But none of the answers worked for me.
score: 0
has comment: http://stackoverflow.com/comment/85252527
has comment: http://stackoverflow.com/comment/85203368
type: UnansweredQuestion
has title: python requests multipart/form-data
has comment: http://stackoverflow.com/comment/85203568

http://stackoverflow.com/q/49100282
tagged with: fibonacci
has answer: http://stackoverflow.com/a/49100366
tagged with: tuples
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/85205834
answer count: 1
has body: This is my code; I know its a mess, but I'm just getting through the basics if that. The question that I have is with the printing of a list at the end. You see, I've tried quite a few things, but it keeps telling me either that "'list' object is not callable" or "Unexpected type: Tuple..." Now, tuple doesn't mean anything to me because we haven't reached that point in class, but I don't want a tuple anyway. I want to print a list that starts at the indicated point "f" with a range of "f2". But I just can't get that. What am I doing wrong? def main(): f = int(input("Starting Place in Code: ")) message = input("simple message: ") f2 = len(message) messageList = [] fibonacciNumbers = [0, 1] messageNumList = [] f3 = fibonacciNumbers[f: f+f2] for let in message: messageList.append(let) for let in messageList: messageNumList.append(ord(let)) for i in range(2, 700): fibonacciNumbers.append(fibonacciNumbers[i - 1] + fibonacciNumbers[i - 2]) #print(fibonacciNumbers) print(f3) print(f2) print(messageList) print(messageNumList) main() Starting Place in Code: 5 simple message: fish [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...] [5, 8, 13, 21, 34, 55] 4 ['f', 'i', 's', 'h'] [102, 105, 115, 104] Process finished with exit code 0
accepted answer: http://stackoverflow.com/a/49100366
tagged with: python
has comment: http://stackoverflow.com/comment/85206890
has title: Python: Printing a List from a starting point to a defined range
type: AnsweredQuestion
tagged with: list
type: Question

http://stackoverflow.com/comment/128894238
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49044972
has text: You can iterate over the lists to get a pair of words and then use the model to get similarity between 2 words. Keeping a running maximum will help you return the highest similarity.

http://stackoverflow.com/q/49050674
type: Question
score: 0
answer count: 1
tagged with: tensorflow-estimator
has title: sampled_softmax_loss complains about a misshapen tensor (but it doesn't seem to be)
tagged with: python
type: UnansweredQuestion
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50357345
has body: I'm trying to build a model that uses sampled_softmax_loss and I can't seem to get the input tensors shaped properly for the function. Here is an example that as best I can tell should match the documentation, but throws this exception: ValueError: Shape must be rank 2 but is rank 1 for 'sampled_softmax_loss/LogUniformCandidateSampler' (op: 'LogUniformCandidateSampler') with input shapes: [?]. Code: import tensorflow as tf import numpy as np f1 = np.random.randint(low = 0, high = 4,size = 100) labels = np.random.randint(low = 0, high = 5,size = 100) f1_t = tf.feature_column.categorical_column_with_vocabulary_list('f1', vocabulary_list = [0,1,2,3]) base_columns = [f1_t] feat_dict = {'f1' : f1} def my_model_fn( features, labels, mode, params): logits = tf.feature_column.linear_model(features, base_columns,units = params["n_classes"]) if mode == tf.estimator.ModeKeys.PREDICT: predictions = { 'probabilities': tf.nn.softmax(logits), } return tf.estimator.EstimatorSpec(mode, predictions=predictions) weights = [v for v in tf.global_variables() if v.name == 'linear_model/f1/weights:0'][0] biases = [v for v in tf.global_variables() if v.name == 'linear_model/bias_weights:0'][0] if mode == "train": loss = tf.nn.sampled_softmax_loss( weights=tf.transpose(weights), biases=biases, labels=labels, inputs=logits, num_classes = 5, num_sampled= 11, num_true=1, partition_strategy="div") elif mode == "eval": None # implement later if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec( mode, loss=loss, ) optimizer = tf.train.FtrlOptimizer(learning_rate=.1,l2_regularization_strength=0.1)#AdagradOptimizer(0.001) train_op = optimizer.minimize( loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec( mode, loss=loss, train_op=train_op) classifier = tf.estimator.Estimator( model_fn = my_model_fn, params = { "feature_columns" : base_columns, "n_classes" : 5 }) classifier.train( input_fn = tf.estimator.inputs.numpy_input_fn(feat_dict, labels, batch_si…

http://stackoverflow.com/comment/84966401
has text: @orange yw~ :-) happy coding
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48980447

http://stackoverflow.com/comment/85016235
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49005887
has text: Share with us your attempt at trying to solve this problem

flask-restplus
tag name: flask-restplus
type: Tag
tags question: http://stackoverflow.com/q/49011630

http://stackoverflow.com/comment/85134439
has text: @aliouawalid That is a requirement you should specify in the question. We cannot guess which part of your code is actually different. As written , `list('0123456789')` would answer your question. But I guessed you probably meant something else which you were not telling us, which is why I did not post that as an answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49055208

http://stackoverflow.com/q/49109500
answer count: 1
favorite count: 0
has body: why python's subprocess.Popen() behavior is odd when running shell command as string and as list? when should we pass shell command as string and as list? &gt;&gt;&gt; import subprocess &gt;&gt;&gt; p = subprocess.Popen('du -sh *', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) &gt;&gt;&gt; stdout, _ = p.communicate() &gt;&gt;&gt; print stdout[:1000] 244M bin 3.1M bmps 14M buildweb 10M contrib 4.0M gobuild 168K gobuild-starter-kit 468K gobuild-test 3.6M lib 46M machines 1.4M machineweb 75M microservices 1.4M monthly_maintenance 20K perforce 9.1M scheduler 196K service 2.5M statusweb 516K storage 228K symindex 7.2M webapps &gt;&gt;&gt; p = subprocess.Popen('du -sh *'.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) &gt;&gt;&gt; stdout, _ = p.communicate() &gt;&gt;&gt; print stdout[:1000] 8 ./statusweb/infrastructure/management/commands 12 ./statusweb/infrastructure/management 16 ./statusweb/infrastructure 48 ./statusweb/statusweb/settings 56 ./statusweb/statusweb 164 ./statusweb/dashboard/migrations 8 ./statusweb/dashboard/tests/fixtures 64 ./statusweb/dashboard/tests 12 ./statusweb/dashboard/static/dashboard/img 12 ./statusweb/dashboard/static/dashboard/css 48 ./statusweb/dashboard/static/dashboard/js/status 12 ./statusweb/dashboard/static/dashboard/js/spec 72 ./statusweb/dashboard/static/dashboard/js 100 ./statusweb/dashboard/static/dashboard 104 ./statusweb/dashboard/static 36 ./statusweb/dashboard/templates/dashboard/dust 32 ./statusweb/dashboard/templates/dashboard/emails 88 ./statusweb/dashboard/templates/dashboard 8 ./statusweb/dashboard/templates/admin/dashboard/issue 8 ./statusweb/dashboard/templates/admin/dashboard/maintenance 20 ./statusweb/dashboard/templates/admin/dashboard 28 ./statusweb/dashboard/templates/admin 8 ./statusweb/dashboard/templates/registra
duplicate of: http://stackoverflow.com/q/3172470
tagged with: python
tagged with: shell
tagged with: subprocess
downvote count: 0
type: UnansweredQuestion
has title: running shell command using python subprocess
score: 2
linked to: http://stackoverflow.com/q/3172470
has answer: http://stackoverflow.com/a/49109986
type: Question
upvote count: 2

http://stackoverflow.com/a/49834998
answers question: http://stackoverflow.com/q/49111583
type: Answer
downvote count: 0
score: 5
has body: The sslopt={"cert_reqs": ssl.CERT_NONE} way is correct. When you get a NameError: NameError: name 'ssl' is not defined you need to import ssl and it should work. Worked for my SSL-related problem.
upvote count: 5

http://stackoverflow.com/a/48981297
has body: You should filter your a,b,c,d tuples by what is actually available: possible = set(itertools.product(As, Bs, Cs, Ds)) available = set(tuple(x) for x in df'A', 'B', 'C', 'D'.unique()) for a, b, c, d in (possible &amp; available): # ...
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48981238

http://stackoverflow.com/comment/85232213
comment on: http://stackoverflow.com/q/49113585
score: 0
has text: what are you *actually* trying to achieve? `df.apply` isn't designed for printing strings. It's hugely inefficient to use it for this purpose.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85024424
type: Comment
has text: @PaulFleming Glad to help!
comment on: http://stackoverflow.com/a/48998730
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85004244
has text: Your seconds _are_ zero padded. And your example months 10 and 12 will never be zero padded. In any case, strptime will attempt to parse even if the expected zero padding is missing.
comment on: http://stackoverflow.com/q/48998640
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49119668
tagged with: python
has body: I want to write a script that simulates a key press and release so that the input goes to a specific window, even if it's not the focused one and in background or minimized. I was wondering if that's possible. The script I made does it every 2 seconds when the focused window (where the inputs go) is the one I decided, otherwise nothing happens, then it loops again. But it's not what I was aiming for. #!/usr/bin/env python # -*- coding: utf-8 -*- import win32api, win32gui, win32con import time def press(): win32api.keybd_event(0x08, 0,0,0) # 0x08 is the hex for the return key time.sleep(.1) win32api.keybd_event(0x08,0 ,win32con.KEYEVENTF_KEYUP ,0) def __get_window(): CurrentWindow = win32gui.GetWindowText(win32gui.GetForegroundWindow()) return CurrentWindow if __name__ == "__main__": while True: if __get_window() == "PROCESS_NAME": # Name of the process press() time.sleep(2) Thank you for any help.
has title: Keypress event to an unfocused window - Win32api
tagged with: bots
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52567995
type: Question
tagged with: automation
tagged with: win32gui
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/comment/84987487
score: 0
type: Comment
has text: ...err you only want to provide a portion of your code. Don't post your entire source. It makes it harder to look through..
comment on: http://stackoverflow.com/a/48965545
type: AnswerComment

http://stackoverflow.com/comment/85037977
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49016477
has text: Not sure why the downvote. Of course @chrisz solved for the toy example but if you want something more general then good luck my friend
type: AnswerComment

http://stackoverflow.com/comment/85136614
comment on: http://stackoverflow.com/a/49065216
score: 0
type: AnswerComment
has text: It truncates the file now, but it doesn't print what was in the file initially after opening the file.
type: Comment

http://stackoverflow.com/a/48969119
answers question: http://stackoverflow.com/q/48968918
type: Answer
score: 1
upvote count: 1
has body: You have to convert your request to bytes which involves the use of bytes() arguement: response = urllib.request.urlopen(chemcalcURL, bytes(urllib.parse.urlencode(params), encoding="utf-8") bytes() must take an encoding which for websites is almost always utf-8.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48968918

http://stackoverflow.com/comment/84958842
has text: And I doubt if this is working for you. As pointed by @Kishan I can see that you are passing target func as core with args which are return by core. And here core method do not accept any args.
comment on: http://stackoverflow.com/q/48974903
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85110021
comment on: http://stackoverflow.com/a/49052374
type: Comment
score: 0
type: AnswerComment
has text: As you see, the name entry is listed two times. one for 2016 and one for 2017.( in this example). in your example it calculates me the distance 366 days on date 2016-01-01 and Neujahr(new year). so in your example he takes the new year date for 2017 and not 2016

http://stackoverflow.com/q/49120597
has answer: http://stackoverflow.com/a/49120673
accepted answer: http://stackoverflow.com/a/49120705
score: -1
has answer: http://stackoverflow.com/a/49120705
favorite count: 0
possible better answer: http://stackoverflow.com/a/49120676
answer count: 3
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49120676
upvote count: 0
has body: I am trying to compute the number of sublists each term appears in the list but I am stuck at the very first step. For example, collection = [['a','b','b','c','d','e','f'],['b','b','d','f']] It should return me (a,1) (b,2) (c,1) (d,2) (e,1) (f,2) I am able to iterate through the collection to print everything out [item for sublist in collection for item in sublist] The issue I have is that I'm not sure how I can receive the count and go to the next loop after finding an occurence. [item for sublist in collection for item in sublist if 'b' == item] This returns me ['b', 'b', 'b', 'b'] Id like it to return me 2. This is how I envisioned the code to be. count = [count++ for sublist in collection for item in sublist if 'b' == item]
has title: Compute the number of sublists each term appears in the list
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/48973285
type: Answer
answers question: http://stackoverflow.com/q/48971454
score: 3
upvote count: 3
downvote count: 0
has body: One more sulution without using zip or accessing element every time by it's index prev, *lst = [3, 5, 2, 3, 1, 2, 3, 1, 3] greater = [] for i in lst: if prev &lt; i: greater.append(i) prev = i And test cases as @Jan presented: def mushif(lst): greater = [] for i in range(1, len(lst)): if lst[i] &gt; lst[i-1]: greater.append(lst[i]) def jan(lst): greater = [item[1] for item in filter(lambda x: x[1] &gt; x[0], zip(lst, lst[1:]))] def roadrunner(lst): greater = [y for x, y in zip(lst, lst[1:]) if y &gt; x] def vishes_shell(lst): start, *lst = lst greater = [] for i in lst: if start &lt; i: greater.append(i) start = i import timeit, functools, random lst = [3, 5, 2, 3, 1, 2, 3, 1, 3] print('Runnig with {} elements'.format(lst)) print('mushif', timeit.timeit(functools.partial(mushif, lst), number=10**5)) print('jan', timeit.timeit(functools.partial(jan, lst), number=10**5)) print('roadrunner', timeit.timeit(functools.partial(roadrunner, lst), number=10**5)) print('vishes_shell', timeit.timeit(functools.partial(vishes_shell, lst), number=10**5)) lst = [random.randint(1, 100) for _ in range(100)] print('Runnig with 100 elements') print('mushif', timeit.timeit(functools.partial(mushif, lst), number=10**5)) print('jan', timeit.timeit(functools.partial(jan, lst), number=10**5)) print('roadrunner', timeit.timeit(functools.partial(roadrunner, lst), number=10**5)) print('vishes_shell', timeit.timeit(functools.partial(vishes_shell, lst), number=10**5)) lst = [random.randint(1, 100) for _ in range(1000)] print('Runnig with 1000 elements') print('mushif', timeit.timeit(functools.partial(mushif, lst), number=10**5)) print('jan', timeit.timeit(functools.partial(jan, lst), number=10**5)) print('roadrunner', timeit.timeit(functools.partial(roadrunner, lst), number=10**5)) print('vishes_shell', timeit.timeit(functools.partial(vishes_shell, lst), number=10**5)) Outputs: Runnig with [3, 5, 2, 3, 1, 2, 3, 1, 3] elements mushif 0.22174075798830017 jan 0.367339823016664 roadrunner 0.16411117…

http://stackoverflow.com/comment/85098402
type: Comment
has text: Your xlsx file might be using features that the underlying `xlrd` library does not support. You could use something like [pastebin](https://pastebin.com/) to upload your file to and paste the URL to it here.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49042976

http://stackoverflow.com/comment/85030848
type: AnswerComment
has text: Just noticed my typo: @jezrael. Sorry.
score: 0
comment on: http://stackoverflow.com/a/49003301
type: Comment

http://stackoverflow.com/q/49053624
answer count: 1
has answer: http://stackoverflow.com/a/49054602
accepted answer: http://stackoverflow.com/a/49054602
has body: I'm trying to download a couple of files in a test that are randomly generated on the back-end with a unique name I use this preferences that I pass to the chrome driver both directly or in a selenium hub CHROME_PREFERENCES = { "profile.default_content_settings.popups": 0, "download.prompt_for_download": "false", "download.directory_upgrade": "true", "download.default_directory": "/mnt/hgfs/down/", "profile.default_content_setting_values.notifications": 2, "profile.default_content_setting_values.automatic_downloads": 1 } But Chrome keeps asking me for the download location every time that I make the get call to the download URL from the driver, rendering the automation useless... I also tried, using bool values as True / False instead of "true" / "false"
tagged with: python
tagged with: selenium-chromedriver
type: AnsweredQuestion
tagged with: selenium
tagged with: google-chrome
type: Question
has title: Chrome keep asking me for a download location on Selenium Hub/Driver on Python
score: 0

http://stackoverflow.com/q/49097952
has title: Installation of Anaconda2 on Windows 10
has answer: http://stackoverflow.com/a/49098069
possible better answer: http://stackoverflow.com/a/49098003
has answer: http://stackoverflow.com/a/49098003
type: AnsweredQuestion
tagged with: windows
has body: While installing Anaconda2 on Windows 7, there is an advanced options dialog box that asks if the user wants to Add Anaconda to my PATH environment variable and if the user wants to Register Anaconda as my default Python 2.7. However, on Windows 10, this dialog box does not appear, thus no option on whether the user wants to register Anaconda as their default Python 2.7. I have two questions: 1) Is there a way to make this dialog box appear during a Win10 install? I'm currently installing it without Admin privileges, perhaps the advanced options dialog appears if I run it with Admin privileges? 2) If there is no option to have the advanced options dialog box show with Windows 10, is there a way to ensure that Anaconda is NOT registered as the default Python 2.7?
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49098069
tagged with: python
tagged with: anaconda
tagged with: installation
score: 0

http://stackoverflow.com/q/49080919
answer count: 2
has answer: http://stackoverflow.com/a/49080977
downvote count: 0
favorite count: 0
tagged with: python
tagged with: kivy
has title: getting an error AttributeError: 'FlashDisplayPage' object has no attribute 'label_name'
has body: I am using carousel in FlashDisplayPage of my app. and I want to use label inside the carousel. I searched relevant sites and made the below code. I am new to kivy so I don't know if this is the right way. If its not how can I make it right? And an error is also occurring here, even though I have defined label_name in FlashDisplayPage I am getting this error-AttributeError: 'FlashDisplayPage' object has no attribute 'label_name'. Why this error is showing up? how can I remove it? here the part of the code where the error is occurring- class FlashDisplayPage(Screen): def on_enter(self): Num=self.index card=['flash_card1.json','flash_card2.json','flash_card3.json','flash_card4.json','flash_card5.json','flash_card6.json','flash_card7.json','flash_card8.json','flash_card9.json','flash_card10.json'] label_name='Flash Card '+ Num #here I have defined label_name with open(card[Num+1]) as frfile: flash_data=json.load(frfile) for i in flash_data: self.ids.CarDisplay.add_widget(Label(text=i['word']+' : '+i['meaning'])) # here I am adding label to carousel def next_one(self): self.ids.CarDisplay.direction='right' # next label in carousel def previous_one(self): self.ids.CarDisplay.direction='left' # previous label in carousel here the part of kv code related to this- &lt;FlashDisplayPage&gt;: BoxLayout: orientation: 'horizontal' spacing:15 padding: 20 Label: id: l text: root.label_name sixe_hint_y: None height: 100 Carousel: id: CarDisplay loop: True Button: text:'next' size_hint: None,.20 width: 30 on_press:root.next_one() Button: text:'next' size_hint: None,.20 width: 130 on_press:root.previous_one()
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49080977
upvote count: 1
possible better answer: http://stackoverflow.com/a/49080981
type: Question
has answer: http://stackoverflow.com/a/49080981
score: 1

http://stackoverflow.com/q/49065255
has answer: http://stackoverflow.com/a/49065373
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: flask
has title: memory leak caused bu stringio in flask with nginx
linked to: http://stackoverflow.com/q/9885217
tagged with: stringio
has body: @app.route('/') def index(): strIO = StringIO.StringIO() strIO.write('Hello from Dan Jacob and Stephane Wirtel !') strIO.seek(0) return send_file(strIO, attachment_filename="testing.txt", as_attachment=True) in above code, we can use StringIO to avoid use temp file when download, but when the file is very large, we can find that the memory of this process is increasing if we download many times, and the memory will not decrease. anyone know how to fix this problem? thx!
type: Question
tagged with: python

http://stackoverflow.com/a/49087253
upvote count: 1
has body: The discussion of reasons for implementation belongs on GitHub (where I raised this issue), not here. A short answer is that units are a bolted-on structure; the core of SymPy is not really unit-aware. You can create 0*meter expression by passing evaluate=False parameter to Mul: &gt;&gt;&gt; Mul(0, u.meter, evaluate=False) 0*meter However, it will become 0 if combined with something else. &gt;&gt;&gt; 3*Mul(0, u.meter, evaluate=False) 0 Wrapping in UnevaluatedExpr prevents the above, but causes more problems than it solves. &gt;&gt;&gt; 3*UnevaluatedExpr(Mul(0, u.meter, evaluate=False)) 3*(0*meter)
score: 1
answers question: http://stackoverflow.com/q/49084526
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85186277

http://stackoverflow.com/comment/85014654
has text: @FrankAK check the topic again, i added it
type: Comment
comment on: http://stackoverflow.com/q/49004788
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85201022
has text: Next step is installing `cartopy`.
type: AnswerComment
comment on: http://stackoverflow.com/a/49095417
type: Comment
score: 1

http://stackoverflow.com/a/49034672
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49034325
has body: Since you use pandas, the simplest would to use to_csv(): u = testset'Latitude' ,'Longitude'.to_csv(index=False) print(u) Output: Latitude,Longitude 42.357778,-71.059444 39.952222,-75.163889 25.787778,-80.22416700000001 30.267221999999997,-97.763889 If you want to avoid the 30.267221999999997,, round: u = testset'Latitude' ,'Longitude'.round(6).to_csv(index=False) print(u) Output: Latitude,Longitude 42.357778,-71.059444 39.952222,-75.163889 25.787778,-80.224167 30.267222,-97.763889
has comment: http://stackoverflow.com/comment/85078957
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49034325
score: 1

http://stackoverflow.com/q/49014904
tagged with: python
has comment: http://stackoverflow.com/comment/85823219
tagged with: combinatorics
has title: Combinatorially generating subgraphs between a given upper and lower bound (Sage)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85841489
type: Question
has answer: http://stackoverflow.com/a/49420121
has comment: http://stackoverflow.com/comment/85795025
tagged with: sage
score: 0
answer count: 1
has body: I am new to sage and I have been reading the documentation but this is very new territory for me and it is a bit tough to get a good grasp on everything. What I want to do is, given an adjacency matrix, an upper bounds, and a lower bounds - generate all pathways through that matrix, where a "pathway" is comprised of one entry from each row, such that the weight of the pathway is equal to or between the bounds. Even better would be if I could organize the given pathways by 1.) The amount amount of edges with a lower weight in each row than the entry in the pathway, and/or 2.) Minimum overlap with other pathways in regards to #1. For clarity, a quick example. Given the 4x4 matrix: [[1,2,3,4], [5,6,7,8], [10,11,12,13], [20,21,22,23]] And an upper bound 38, and a lower bound 37, possible pathways could be: 2,5,10,20 3,5,10,20 2,6,10,20 2,5,11,20 2,5,10,21 etc etc. I don't want to write out all the pathways, so hopefully you get the idea. Even better would be if I could quickly filter out redundancy, by not including pathways that are subsets of other pathways (for example, 2,5,10,20 is encompassed by 3,5,10,20 - since for each pathway I plan on including all lower-weight edges of the each respective row).

http://stackoverflow.com/comment/84994888
score: 0
type: Comment
has text: what is the difference with ~ and no ~ @Sebastian ?
type: AnswerComment
comment on: http://stackoverflow.com/a/48994699

http://stackoverflow.com/comment/85020251
has text: SymPy does not integrate functions, it integrates expressions. A symbolic expression does not need anything to be plugged in, it already contains symbols. When you write Python functions like `def fx...` for use in SymPy, you are probably overcomplicating.
score: 0
comment on: http://stackoverflow.com/q/49006951
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85013763
has text: some of the `'` are wrong in the sample data
score: 0
comment on: http://stackoverflow.com/q/49004503
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85051910
score: 0
type: Comment
type: QuestionComment
has text: You could make getter functions that will get the properties to print.
comment on: http://stackoverflow.com/q/49023563

http://stackoverflow.com/a/49036097
accepted answer of: http://stackoverflow.com/q/49035843
answers question: http://stackoverflow.com/q/49035843
has body: I hacked out what I think are the relevant parts. def Midpoint_meth(def_fn, a, b, N, ya): """ Test the Midpoint Method to solve initial value problem y'=f(t,y) with t in [a,b] and y(a) = ya. Step size h is computed according to input number of mesh points N """ print(type(N)) f = def_fn #input definining function h = (b-a)/N # developing step size h, from input values divided by N t = np.arange(a, b+h, h) #array intialized to hold mesh points t y = np.zeros((N+1,)) #array to hold Midpoint Method approximated y values y[0] = ya #intial condition #iterative method for i in range(0, N): tau = t[i] #current mesh point t w = y[i] #current value y(t) # next iteration using midpoint method y[i + 1] = w + h*f(tau + h/2.0, w + h*f(tau, w /2.0)) return (t, y) ############ Example #1 Given Points N_mdeul1 = 20.0 # number of mesh points a_mdeul1 = 0.0 # left end point of interval [a,b] b_mdeul1 = 2.0 # right end point of interval [a,b] ya_mdeul1 = 0.5 # initial value y(a) # run Euler's method from ODE_Approx_methods for example #1 (t_mdeul1,w_mdeul1) = Midpoint_meth(1, a_mdeul1, b_mdeul1, ya_mdeul1, N_mdeul1) I am getting the error: TypeError Traceback (most recent call last) &lt;ipython-input-31-51b398a6cbbd&gt; in &lt;module&gt;() 43 # run Euler's method from ODE_Approx_methods for example #1 44 ---&gt; 45 (t_mdeul1,w_mdeul1) = Midpoint_meth(1, a_mdeul1, b_mdeul1, ya_mdeul1, N_mdeul1) 46 &lt;ipython-input-31-51b398a6cbbd&gt; in Midpoint_meth(def_fn, a, b, N, ya) 20 #iterative method 21 ---&gt; 22 for i in range(0, N): 23 24 tau = t[i] #current mesh point t TypeError: 'float' object cannot be interpreted as an integer Which made me see that in your call: (t_mdeul1,w_mdeul1) = Midpoint_meth(1, a_mdeul1, b_mdeul1, ya_mdeul1, N_mdeul1) The 4th argument (N in your function call), which is the variable ya_mdeul1 is ya_mdeul1 = 0.5 Definitely not an int
has comment: http://stackoverflow.com/comment/85078416
score: 0
has comment: http://stackoverflow.com/comment/85078593
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85078244
type: Answer
has comment: http://stackoverflow.com/comment/85077875
has comment: http://stackoverflow.com/comment/85077929
has comment: http://stackoverflow.com/comment/85078177
has comment: http://stackoverflow.com/comment/85077777
has comment: http://stackoverflow.com/comment/85078289

http://stackoverflow.com/a/58062042
has body: The quick answer is to pass log=None when you create your WSGIServer: pywsgi.WSGIServer(('', 5000), app, log=None).serve_forever() The gevent WSGI server logging is apparently a bit special according to the documentation: [...] loggers are likely to not be gevent-cooperative. For example, the socket and syslog handlers use the socket module in a way that can block, and most handlers acquire threading locks. If you want to have more control over the gevent WSGI server logging, you can pass in your own logger (and error_log). Just make sure to wrap it in a LoggingLogAdapter first: from gevent.pywsgi import LoggingLogAdapter server_log = LoggingLogAdapter(logging.getLogger(__file__)) # server_log.disabled = True # Now you can disable it like a normal log ... pywsgi.WSGIServer(('', 5000), app, log=server_log).serve_forever() As a side note, I checked which loggers were instantiated with this little patch to logging.getLogger. Maybe it will be helpful for others trying to understand where log output comes from: import logging old_getLogger = logging.getLogger def getLogger(*args, **kwargs): print('Getting logger', args, kwargs) return old_getLogger(*args, **kwargs) logging.getLogger = getLogger The output was something like: Getting logger ('concurrent.futures',) {} Getting logger ('asyncio',) {} Getting logger ('engineio.client',) {} Getting logger ('engineio.server',) {} Getting logger ('socketio.client',) {} Getting logger ('socketio',) {} Getting logger ('socketio',) {} Getting logger ('socketio',) {} Getting logger ('socketio.server',) {} Getting logger ('socketio.client',) {} Getting logger () {} Getting logger ('main',) {} Getting logger ('flask.app',) {} Getting logger ('flask',) {} Getting logger ('werkzeug',) {} Getting logger ('wsgi',) {} But of course disabling any of these loggers doesn't work since the default gevent WSGI logger is just printing directly to stderr.
downvote count: 0
answers question: http://stackoverflow.com/q/49038678
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/a/49086088
type: AcceptedAnswer
has body: EOF while input raises EOFError so you can use try … except block with break statement: flag = True; while True: #I want That loop is terminated when getting EOF try: txt = input() for var in txt: if var == '"': if flag: print("``", end='') else: print("''", end='') flag = not flag else: print(var, end='') print(end='\n') except EOFError: break
has comment: http://stackoverflow.com/comment/85177762
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49085914
answers question: http://stackoverflow.com/q/49085914
has comment: http://stackoverflow.com/comment/85178287
upvote count: 2

http://stackoverflow.com/comment/84962220
has text: BTW, don't use the same name for instances and classes because that overrides the class and you can't create new instances anymore. Use snake_case names for variables, instances and functions, e.g. `my_variable`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48978596
type: AnswerComment

http://stackoverflow.com/comment/99335343
has text: @PKKid There seem to be some ways to restrict fields explicitly in the source code https://github.com/graphql-python/graphene-django/blob/master/graphene_django/types.py but they're not documented as far as I know, and they don't allow conditional based access
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49283138
type: Comment

http://stackoverflow.com/q/49010426
favorite count: 0
has answer: http://stackoverflow.com/a/49011016
tagged with: python
accepted answer: http://stackoverflow.com/a/49011016
upvote count: 3
tagged with: django
has body: currently I'm attempting to create a custom validator to validate usernames. Django only provides two validators: ASCIIUsernameValidator and UnicodeUsernameValidator. But both of them accept special characters like @, but I want to accept only alphanumeric characters (A-Za-z0-9) and underscores. I did read the validator documentation and I believe that something like this should work: # project_name/validators.py from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class AlphanumericUsernameValidator(validators.RegexValidator): regex = r'^[\w]+$' message = _( 'Enter a valid username. This value may contain only English letters, ' 'numbers and underscores.' ) flags = re.ASCII But how would I actually use it? I checked and AbstractUser contains this line: username_validator = UnicodeUsernameValidator(). Would I have to create an AbstractUser like below (not sure if I even can make one because I already have some users registered)? from django.db import models from django.contrib.auth.models import AbstractUser from project_name.validators import AlphaNumericUsernameValidator class User(AbstractUser): username_validator = AlphaNumericUsernameValidator() Would I have to create a custom AbstractUser? Or is there some other simpler way that doesn't require the creation of one just to change a single validator?
type: AnsweredQuestion
score: 3
tagged with: django-authentication
type: Question
has title: Create and use a custom username validator for a registration form
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85151927
has text: Try remove `.reset_index(level=0, drop=True)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49071595
score: 0

http://stackoverflow.com/q/49103406
type: UnansweredQuestion
has title: How do I use a python variable in a SQLITE SELECT statement
tagged with: python
has answer: http://stackoverflow.com/a/49110566
has comment: http://stackoverflow.com/comment/85211949
has comment: http://stackoverflow.com/comment/85212306
type: Question
has body: So i was trying to use a local varibale made in python to be used in my SQL statement but I get the error sqlite3.OperationalError: unrecognized token: "1AM" if schchoice==int("1"): schchoice=str("12AM") elif schchoice == int("2"): schchoice="1AM" else: print("INVALID") if schchoice2==int("1"): schchoice=str("12AM") elif schchoice2==int("2"): schchoice2="1AM" else: print("INVALID") conn = sqlite3.connect('Employee.db') c = conn.cursor() def read_from_db(): c.execute("SELECT FName,LName, monstarthour, monendhour FROM MondayHours WHERE monstarthour ='"+schchoice+"'AND monendhour='"+schchoice2+'"') #data = c.fetchall() for row in c.fetchall(): print(row) read_from_db()
has comment: http://stackoverflow.com/comment/85211912
score: 0
tagged with: sqlite
answer count: 1
tagged with: variables

http://stackoverflow.com/comment/85051854
comment on: http://stackoverflow.com/q/49022088
has text: Anaconda version 4.3.1 is working fine. I'm going ahead with that till I get a solution here.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85086327
comment on: http://stackoverflow.com/q/49040401
score: 0
has text: Yep, I you are right kindda my bad I didnt get the whole conept of encoding right and thought that I need to encode into utf8 or something like this.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85220888
comment on: http://stackoverflow.com/a/49108030
has text: given that this question is tagged with `argparse` I don't think that this is the behavior OP is looking for.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84938186
has text: thank you. im trying to simply get the coordinates from HTML5 Geolocation and send the results to my flask/python.
comment on: http://stackoverflow.com/a/48964455
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85153539
comment on: http://stackoverflow.com/q/49073842
type: Comment
type: QuestionComment
has text: How did you get the xpath? Is it correct? In the first image if you right click on the element you want, then move over to "Copy", then click on "Copy xpath", you should get the xpath of that element. You will need separate xpaths for each element, so one for dt, and one for dd. Let me know if this works
score: 0

http://stackoverflow.com/a/49011320
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49003983
upvote count: 1
has body: itertools.chain is convenient for this purpose: from itertools import chain s = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] list(map(str, chain.from_iterable(s))) # ['1', '2', '3', '4', '5', '6', '7', '8', '9']

http://stackoverflow.com/comment/85010291
comment on: http://stackoverflow.com/a/49002715
score: 1
type: AnswerComment
type: Comment
has text: Clever use of heuristics to find even indexes in a sequence: take every other element... ;)

http://stackoverflow.com/q/49111500
tagged with: openssl
score: 0
has comment: http://stackoverflow.com/comment/85228897
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/85255235
has body: When trying to install some 3rd party apps with something like pip install or run apps that uses the requests module. I end up having this error: requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'ssl_cipher_list_to_bytes', 'no ciphers available')],)",) I didn't have this issue before. So I guess there's some conflict with the libraries. But I don't seem to get where the problem is coming from.
tagged with: ssl
has title: python-requests SSL Error; bad handshake; no ssl cipher list
has comment: http://stackoverflow.com/comment/85229381

http://stackoverflow.com/comment/85177253
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49079811
type: AnswerComment
has text: @ely The `axis=1` kwargs is to `.apply` not `.argsort`. Additionally `.argsort` is applied to a Series in this example so no need to specify `axis`.

http://stackoverflow.com/comment/85156604
has text: Your param should be sequence. A tuple of one element is `(4,)` but you have `(4)` which is a scalar.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49075238

cartopy
tags question: http://stackoverflow.com/q/49048411
tag name: cartopy
type: Tag
tags question: http://stackoverflow.com/q/49071176
tags question: http://stackoverflow.com/q/49053816

http://stackoverflow.com/a/50519530
type: Answer
score: 2
has body: I wrote this package to read from the new api https://query1.finance.yahoo.com from datetime import datetime import py_yahoo_prices.price_fetcher as pf st_dt = datetime(2017, 6, 1) comp_codes = ["IMM.L", "AAPL", "TSLA", ....] # get the raw prices from yahoo, auto retries on a 401 error raw_prices = pf.multi_price_fetch(code=comp_codes, start_date=st_dt)
downvote count: 0
answers question: http://stackoverflow.com/q/49081837
has comment: http://stackoverflow.com/comment/88051953
upvote count: 2

http://stackoverflow.com/q/49014127
has answer: http://stackoverflow.com/a/49014297
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Special method like __str__ that returns a number representation of an object
has comment: http://stackoverflow.com/comment/85033011
has answer: http://stackoverflow.com/a/49014233
type: Question
possible better answer: http://stackoverflow.com/a/49014233
tagged with: class
has answer: http://stackoverflow.com/a/49014984
has comment: http://stackoverflow.com/comment/85033439
has comment: http://stackoverflow.com/comment/85033565
answer count: 3
has comment: http://stackoverflow.com/comment/85034895
downvote count: 0
linked to: http://stackoverflow.com/q/19750394
has body: Say I have a Python class as follows: class TestClass(): value = 20 def __str__(self): return str(self.value) The __str__ method will automatically be called any time I try to use an instance of TestClass as a string, like in print. Is there any equivalent for treating it as a number? For example, in an_object = TestClass() if an_object &gt; 30: ... where some hypothetical __num__ function would be automatically called to interpret the object as a number. How could this be easily done? Ideally I'd like to avoid overloading every normal mathematical operator.
favorite count: 0
has comment: http://stackoverflow.com/comment/85033462
tagged with: python
accepted answer: http://stackoverflow.com/a/49014984

http://stackoverflow.com/q/49052359
has answer: http://stackoverflow.com/a/49052472
tagged with: python
has answer: http://stackoverflow.com/a/63960772
type: AnsweredQuestion
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/85109441
has body: ## class restaurant ## Implemented superclass class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('This restaurant is called ' + self.restaurant_name + '.') print('This restaurant serves dishes acoording to ' + self.cuisine_type + '.') def open_restaurant(self, hours): self.hours = hours print(self.restaurant_name.title() + ' is opened ' + str(hours) + '!') class IceCreamStand(Restaurant): def __init__(self, restaurant_name, cuisine_type): super().__init__(restaurant_name, cuisine_type) self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type flavours = ['chocolate', 'vanilia', 'strawberry', 'lime', 'orange'] def flavours(self): print('Available flavours: ') for flavour in flavours: print(flavour) IceCreamStand = Restaurant(' Matt IceCream ', 'ice creams') IceCreamStand.describe_restaurant() IceCreamStand.flavours()
score: 1
type: Question
has title: AttributeError: 'Restaurant' object has no attribute 'flavours' - why?
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/63960772
favorite count: 0
tagged with: class
accepted answer: http://stackoverflow.com/a/49052472
has comment: http://stackoverflow.com/comment/85109337
downvote count: 0

http://stackoverflow.com/a/48975249
has comment: http://stackoverflow.com/comment/84956381
score: 0
accepted answer of: http://stackoverflow.com/q/48975137
has comment: http://stackoverflow.com/comment/84956756
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84956356
has comment: http://stackoverflow.com/comment/84956938
type: Answer
answers question: http://stackoverflow.com/q/48975137
has comment: http://stackoverflow.com/comment/84955643
has body: you should first train and then check the results. If you check it before training, obviously two results will be different. you can just once again calculate the results after training, hopefully, this will solve your bug.
has comment: http://stackoverflow.com/comment/84957271

http://stackoverflow.com/comment/111377056
type: AnswerComment
comment on: http://stackoverflow.com/a/49038522
score: 0
type: Comment
has text: Thanks @Borut for your explanation. I was facing "Authentication credentials were not provided" error on postman. Then I add 'rest_framework.authentication.TokenAuthentication' in my INSTALLED_APPS. The problem got resolved.

http://stackoverflow.com/q/49089436
has comment: http://stackoverflow.com/comment/85246367
has comment: http://stackoverflow.com/comment/85245779
has answer: http://stackoverflow.com/a/49453084
accepted answer: http://stackoverflow.com/a/49453084
tagged with: python
has comment: http://stackoverflow.com/comment/85262779
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49223634
has body: I am having trouble using Batch Normalization with tensorflow. I have build the following model: def weight_variable(kernal_shape): weights = tf.get_variable(name='weights', shape=kernal_shape, dtype=tf.float32, trainable=True, initializer=tf.truncated_normal_initializer(stddev=0.02)) return weights def bias_variable(shape): initial = tf.constant(0.0, shape=shape) return tf.Variable(initial) # return 1 conv layer def conv_layer(x, w_shape, b_shape, is_training, padding='SAME'): W = weight_variable(w_shape) tf.summary.histogram("weights", W) b = bias_variable(b_shape) tf.summary.histogram("biases", b) # Note that I used a stride of 2 on purpose in order not to use max pool layer. conv = tf.nn.conv2d(x, W, strides=[1, 2, 2, 1], padding=padding) + b conv = tf.contrib.layers.batch_norm(conv, scale=True, is_training=is_training) activations = tf.nn.relu(conv) tf.summary.histogram("activations", activations) return activations # return deconv layer def deconv_layer(x, w_shape, b_shape, is_training, padding="SAME", activation='relu'): W = weight_variable(w_shape) tf.summary.histogram("weights", W) b = bias_variable(b_shape) tf.summary.histogram('biases', b) x_shape = tf.shape(x) # output shape: [batch_size, h * 2, w * 2, input_shape from w]. out_shape = tf.stack([x_shape[0], x_shape[1] * 2, x_shape[2] * 2, w_shape[2]]) # Note that I have used a stride of 2 since I used a stride of 2 in conv layer. conv_trans = tf.nn.conv2d_transpose(x, W, out_shape, [1, 2, 2, 1], padding=padding) + b conv_trans = tf.contrib.layers.batch_norm(conv_trans, scale=True, is_training=is_training) if activation == 'relu': transposed_activations = tf.nn.relu(conv_trans) else: transposed_activations = tf.nn.sigmoid(conv_trans) tf.summary.histogram("transpose_activation", transposed_activations) return transposed_activations def model(input): with tf.variable_scope('conv1'): conv1 = conv_layer(input, [4, 4, 3, 32], [32], is_training=phase_train) # image size: [56, 56] with tf.variable_scope('conv2'):…
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85281251
has comment: http://stackoverflow.com/comment/85313060
has title: How to use BatchNormalization with tensorflow?
has comment: http://stackoverflow.com/comment/85301458
score: 0
answer count: 2
tagged with: batch-normalization
has answer: http://stackoverflow.com/a/49223634

http://stackoverflow.com/a/48995086
score: 5
accepted answer of: http://stackoverflow.com/q/48995011
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48995011
has body: A dict is unordered in the sense that Python makes no guarantees that the order will be consistent. That doesn't mean that you won't see a consistent ordering sometimes though. If you need a dict that is ordered you should check out collections.OrderedDict.
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85248681
has text: I want to construct Wb for each batch size so the final answer be with shape (? , 15 ,100)
type: Comment
comment on: http://stackoverflow.com/a/49100795
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85182966
has text: How is your computer connected to the internet? And where do you expect will your client sit?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49086604
type: QuestionComment

http://stackoverflow.com/comment/85026605
type: QuestionComment
comment on: http://stackoverflow.com/q/49011007
score: 0
has text: what could be the fix here? how do I know my default encoding and what to change to? thoughts?
type: Comment

http://stackoverflow.com/a/49058853
has comment: http://stackoverflow.com/comment/85128090
has comment: http://stackoverflow.com/comment/85128276
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: To run a cron job only on weekdays you can define a "custom interval": schedule: every mon,tue,wed,thu,fri 00:10 Would need to see your code for the publish/daily-tick handler to see why you're not getting an email
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49053112
answers question: http://stackoverflow.com/q/49053112

http://stackoverflow.com/a/49179544
has comment: http://stackoverflow.com/comment/125004796
answers question: http://stackoverflow.com/q/49097667
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49097667
downvote count: 0
has comment: http://stackoverflow.com/comment/125770409
type: Answer
has body: After some trial and error I came up with some code for my purposes (0 means empty in the array, another number will mean a filled voxel. def rotate(self, deg_angle, axis): d = len(self.matrix) h = len(self.matrix[0]) w = len(self.matrix[0][0]) min_new_x = 0 max_new_x = 0 min_new_y = 0 max_new_y = 0 min_new_z = 0 max_new_z = 0 new_coords = [] angle = radians(deg_angle) for z in range(d): for y in range(h): for x in range(w): new_x = None new_y = None new_z = None if axis == "x": new_x = int(round(x)) new_y = int(round(y*cos(angle) - z*sin(angle))) new_z = int(round(y*sin(angle) + z*cos(angle))) elif axis == "y": new_x = int(round(z*sin(angle) + x*cos(angle))) new_y = int(round(y)) new_z = int(round(z*cos(angle) - x*sin(angle))) elif axis == "z": new_x = int(round(x*cos(angle) - y*sin(angle))) new_y = int(round(x*sin(angle) + y*cos(angle))) new_z = int(round(z)) val = self.matrix.item((z, y, x)) new_coords.append((val, new_x, new_y, new_z)) if new_x &lt; min_new_x: min_new_x = new_x if new_x &gt; max_new_x: max_new_x = new_x if new_y &lt; min_new_y: min_new_y = new_y if new_y &gt; max_new_y: max_new_y = new_y if new_z &lt; min_new_z: min_new_z = new_z if new_z &gt; max_new_z: max_new_z = new_z new_x_offset = abs(min_new_x) new_y_offset = abs(min_new_y) new_z_offset = abs(min_new_z) new_width = abs(min_new_x - max_new_x) new_height = abs(min_new_y - max_new_y) new_depth = abs(min_new_z - max_new_z) rotated = np.empty((new_depth + 1, new_height + 1, new_width + 1)) rotated.fill(0) for coord in new_coords: val = coord[0] x = coord[1] y = coord[2] z = coord[3] if rotated[new_z_offset + z][new_y_offset + y][new_x_offset + x] == 0: rotated[new_z_offset + z][new_y_offset + y][new_x_offset + x] = val self.matrix = rotated The way I use the above code is: cube = Rect_Prism(20, 20, 20) # creates a 3d array similar to above example, just bigger cube.rotate(20, "x") cube.rotate(60, "y") Rect_Prism creates a MxNxD matrix, but in this case NxNxN. And result when printing: # # # # …
has comment: http://stackoverflow.com/comment/93973291
score: 7
upvote count: 7

http://stackoverflow.com/q/49086873
score: 1
favorite count: 0
tagged with: python-3.x
has title: Less cluttered if condition
has answer: http://stackoverflow.com/a/49086925
downvote count: 2
tagged with: python
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/49086919
possible better answer: http://stackoverflow.com/a/49087221
has answer: http://stackoverflow.com/a/49087221
type: Question
has body: I am new in Python and i was wondering if there is a more elegant way to express the following if condition: a=0 b=0 c=0 d=0 e=0 f=0 if a!=0 and c!=0 and b==0 and d==0 and e==0 and f==0: print("Hello World!") This is a simple toy example but in practice i have more than 6 letters and things get really cluttered.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49086919

http://stackoverflow.com/a/49081131
has comment: http://stackoverflow.com/comment/85167957
type: Answer
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/49080613
upvote count: 7
has body: I'd never heard of "thermometer encoding" before, but when you realise how it's so similar to one-hot encoding, it becomes clear you can get there using bit shift ops: &gt;&gt;&gt; a = np.array([2, 3, 4, 1], dtype=np.uint8) &gt;&gt;&gt; print(np.fliplr(np.unpackbits((1 &lt;&lt; a) - 1).reshape(-1,8))) [[1 1 0 0 0 0 0 0] [1 1 1 0 0 0 0 0] [1 1 1 1 0 0 0 0] [1 0 0 0 0 0 0 0]] Edit: You can generalise the idea to arbitrary size integers by working in 8 column chunks: a = np.array([2, 13, 4, 0, 1, 17], dtype=np.uint8) out = np.empty((len(a), 0), dtype=np.uint8) while a.any(): block = np.fliplr(np.unpackbits((1 &lt;&lt; a) - 1).reshape(-1,8)) out = np.concatenate([out, block], axis=1) a = np.where(a&lt;8, 0, a-8) print(out) [[1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0] [1 1 1 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] [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0]]
has comment: http://stackoverflow.com/comment/85168168

http://stackoverflow.com/q/49094768
upvote count: 9
answer count: 6
has answer: http://stackoverflow.com/a/58858964
score: 9
has body: still advancing in my tutorial to learn python, I was told to do sudo -H pip install requests I get the following : pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting requests Could not fetch URL https://pypi.python.org/simple/requests/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement requests (from versions: ) No matching distribution found for requests would someone know what I need to do to fix that once for all ? thanks so much in advance
has title: "ssl module in Python is not available"
downvote count: 0
has answer: http://stackoverflow.com/a/54468038
favorite count: 0
has comment: http://stackoverflow.com/comment/85194683
has answer: http://stackoverflow.com/a/55517908
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50888765
tagged with: python
linked to: http://stackoverflow.com/q/41328451
tagged with: pip
has answer: http://stackoverflow.com/a/68707671
has answer: http://stackoverflow.com/a/61981666
type: Question

http://stackoverflow.com/comment/89218527
score: 1
comment on: http://stackoverflow.com/q/48976611
has text: Can you provide an example notebook so that we can try to figure out?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85207605
score: 0
comment on: http://stackoverflow.com/a/49086936
type: Comment
type: AnswerComment
has text: I am working on a similar application (A client on an android that needs to connect to a server on my local machine). I haven’t lunched it, but from my research it appears as if you would set both the client and the server to the local machine IP. However, I believe that it could work if you only change the client script to the machines IP, and you may be able to keep the server script set to localhost. I would try both methods. If I finish my program before you, I will update you on which method works. I assume both can work.

http://stackoverflow.com/comment/84938966
has text: @MartijnPieters Thank you. So I would need to look at the C source and not the Python code for the `Button()` attribute?
score: 0
comment on: http://stackoverflow.com/q/48966639
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85129470
comment on: http://stackoverflow.com/q/49061132
score: 0
has text: Just reverse the synthax in am_recommande,in mean Time, can I add my answer for approval for the question that was asked?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49019898
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49020136
tagged with: tensorflow
type: Question
score: 4
has title: Is there a way to use tf.data.Dataset inside of another Dataset in Tensorflow?
upvote count: 4
accepted answer: http://stackoverflow.com/a/49020136
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm doing segmentation. Each training sample have multiple images with segmentation masks. I'm trying to write input_fn to merge all mask images in to one for each training sample. I was planning on using two Datasets, one that iterates over samples folders and another that reads all masks as one large batch and then merges them to one tensor. I'm getting an error when nested make_one_shot_iterator is called. I Know that this approach is a bit of a stretch and mostlikely datasets wheren't designed for such usage. But then how should I approach this problem so that I avoid using tf.py_func? Here is a simplified version of the dataset: def read_sample(sample_path): masks_ds = (tf.data.Dataset. list_files(sample_path+"/masks/*.png") .map(tf.read_file) .map(lambda x: tf.image.decode_image(x, channels=1)) .batch(1024)) # maximum number of objects masks = masks_ds.make_one_shot_iterator().get_next() return tf.reduce_max(masks, axis=0) ds = tf.data.Dataset.from_tensor_slices(tf.glob("../input/stage1_train/*")) ds.map(read_sample) # ... sample = ds.make_one_shot_iterator().get_next() # ...
tagged with: tensorflow-datasets

http://stackoverflow.com/q/49095019
tagged with: python
has answer: http://stackoverflow.com/a/51592217
type: AnsweredQuestion
tagged with: flask-wtforms
possible better answer: http://stackoverflow.com/a/51592217
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49095040
has body: Am new in flask , but am getting this error , i tired searching on different questions on stackoverflow but i have found none which work, below is the error am getting: Traceback (most recent call last): File "C:/Users/Huzy_Kamz/PycharmProjects/articles/articles.py", line 6, in &lt;module&gt; from wtforms import Form,StringField,TextAreaField,PasswordField, validators ModuleNotFoundError: No module named 'wtforms' Then the area which the error is expected is in below the code: from flask import Flask, render_template, request,flash,redirect,url_for,session,logging,jsonify #from data import Articles from flask_mysqldb import MySQL from _mysql_exceptions import MySQLError from wtforms import Form,StringField,TextAreaField,PasswordField, validators from passlib.hash import sha256_crypt from _mysql_exceptions import IntegrityError from functools import wraps
linked to: http://stackoverflow.com/q/45660399
has title: ModuleNotFoundError: No module named 'flask_wtforms'
score: 0
answer count: 2
tagged with: python-import
tagged with: flask
favorite count: 0
accepted answer: http://stackoverflow.com/a/49095040
tagged with: python-3.x

http://stackoverflow.com/q/48966738
has comment: http://stackoverflow.com/comment/84939227
type: Question
tagged with: for-loop
downvote count: 0
has answer: http://stackoverflow.com/a/48966795
accepted answer: http://stackoverflow.com/a/48966810
tagged with: while-loop
answer count: 3
has body: if i have this list car=['Mazda','ford','Honda','corvette','Mercedes'] price=['300','450','350','490','500'] and i want to print the following sentence for each one at once print ("that", car,"car price is:",price ,"in thousands dollar") how to write the condition i usually use this but how to do it for a list ? car=input("enter car name:") price=float(input("price of the car:")) because it will only print for the values that i have entered in car=input("enter car name:") price=float(input("price of the car:"))
favorite count: 0
has answer: http://stackoverflow.com/a/48966810
has title: while statement that goes with list and length
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48966795
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48966917

http://stackoverflow.com/a/49064377
answers question: http://stackoverflow.com/q/49059592
score: 0
type: Answer
has body: This will work. &gt;&gt;&gt; element = driver.find_element_by_id('contact-link') &gt;&gt;&gt; element.text '(hidden)' &gt;&gt;&gt;

http://stackoverflow.com/a/49114253
score: 1
has comment: http://stackoverflow.com/comment/85234200
upvote count: 1
has body: I think you can remove the code duplication by defining a generator of segments outside the loop def _locate(self, text): """ This method accesses preceding locators if these exist, it then calls an overridable helper method called _relocate which receives text with readjusted boundaries and searches inside, the basic implemented behaviour is that of a logical or """ if self.precedents: segments = (seg for precedent in self.precedents for seg in precedent.locate(text)) else: segments = (Segment(0, len(text), 1),) for segment in segments: for sub_segment in self._relocate(text, segment): if self._multiple: yield sub_segment elif self.max_segment.prob &gt; self._prob_threshold: yield self.max_segment return # if we haven't found a good enough segment return the best one we came across while trying if not self._multiple: yield self.max_segment
answers question: http://stackoverflow.com/q/49113965
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49113965
type: Answer

http://stackoverflow.com/comment/85020888
has text: Use `r'^-\d+\$$'`, add `-` after `^`. See [this post](https://stackoverflow.com/a/15814681/3832970).
comment on: http://stackoverflow.com/q/49008237
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/comment/85098311
has text: Understood. as you can access the attributes using getattr, you can save all frames to a list (or any collection) and later filter/select them based on the attributes of the instance. Does the new solution work better for you?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49046596

http://stackoverflow.com/comment/84961658
type: AnswerComment
score: 0
type: Comment
has text: I have the server set up and the script in the mentioned location. However, I don't know how to retrieve the json (of the type {name : value}) from the request body using python. Please let me know how to retrieve the json from the request body using python code.
comment on: http://stackoverflow.com/a/48969166

http://stackoverflow.com/comment/85040292
type: Comment
has text: Do you want to know what its doing or what its called?
comment on: http://stackoverflow.com/q/49017577
score: 0
type: QuestionComment

http://stackoverflow.com/a/49044110
downvote count: 0
has comment: http://stackoverflow.com/comment/85093688
score: 3
has comment: http://stackoverflow.com/comment/85093635
upvote count: 3
has body: I think you can use re module to search the correct count. import requests import re username_extract = 'lazada_my' url = 'https://www.instagram.com/'+ username_extract r = requests.get(url) m = re.search(r'"followed_by":\{"count":([0-9]+)\}', str(r.content)) print(m.group(1))
has comment: http://stackoverflow.com/comment/85093653
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49043857
has comment: http://stackoverflow.com/comment/85093391
answers question: http://stackoverflow.com/q/49043857
type: Answer
has comment: http://stackoverflow.com/comment/85093629

http://stackoverflow.com/a/48996721
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85000042
has comment: http://stackoverflow.com/comment/84999500
has body: You are currently printing the list. [...] is because of it being the list. Just use " ".join(reverseEachCharacter) to join your strings in the list to create another string as: myList = ['string21', 'string43', 'string65'] reverseEachCharacter = [x[::-1] for x in myList] print (repr(" ".join(reverseEachCharacter))) Output: '12gnirts 34gnirts 56gnirts' Edit: Found that repr is made just for printing with the quotes! Though "'{}'".format() will be still better for the flexibility.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48996679
has comment: http://stackoverflow.com/comment/84999319
answers question: http://stackoverflow.com/q/48996679
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/84998944

http://stackoverflow.com/q/48990688
score: 8
accepted answer: http://stackoverflow.com/a/49736941
has comment: http://stackoverflow.com/comment/85020936
tagged with: parallel-processing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85282015
has body: I am trying to run parallel processes under python (on ubuntu). I started using multiprocessing and it worked fine for simple examples. Then came the pickle error, and so I switched to pathos. I got a little confused with the different options and so wrote a very simple benchmarking code. import multiprocessing as mp from pathos.multiprocessing import Pool as Pool1 from pathos.pools import ParallelPool as Pool2 from pathos.parallel import ParallelPool as Pool3 import time def square(x): # calculate the square of the value of x return x*x if __name__ == '__main__': dataset = range(0,10000) start_time = time.time() for d in dataset: square(d) print('test with no cores: %s seconds' %(time.time() - start_time)) nCores = 3 print('number of cores used: %s' %(nCores)) start_time = time.time() p = mp.Pool(nCores) p.map(square, dataset) # Close p.close() p.join() print('test with multiprocessing: %s seconds' %(time.time() - start_time)) start_time = time.time() p = Pool1(nCores) p.map(square, dataset) # Close p.close() p.join() print('test with pathos multiprocessing: %s seconds' %(time.time() - start_time)) start_time = time.time() p = Pool2(nCores) p.map(square, dataset) # Close p.close() p.join() print('test with pathos pools: %s seconds' %(time.time() - start_time)) start_time = time.time() p = Pool3() p.ncpus = nCores p.map(square, dataset) # Close p.close() p.join() print('test with pathos parallel: %s seconds' %(time.time() - start_time)) I get about - 0.001s with plain serial code, without parallel, - 0.100s with multiprocessing option, - 0.100s with pathos.multiprocessing, - 4.470s with pathos.pools, - an AssertionError error with pathos.parallel I copied how to use these various options from http://trac.mystic.cacr.caltech.edu/project/pathos/browser/pathos/examples.html I understand that parallel processing is longer than a plain serial code for such a simple example. What I do not understand is the relative performance of pathos. I checked discussions, but could n…
tagged with: multiprocessing
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49736941
downvote count: 0
has title: pathos: parallel processing options - Could someone explain the differences?
tagged with: parallelism-amdahl
favorite count: 0
has comment: http://stackoverflow.com/comment/85282340
possible better answer: http://stackoverflow.com/a/48991606
has comment: http://stackoverflow.com/comment/85281729
upvote count: 8
has answer: http://stackoverflow.com/a/48991606
tagged with: python
linked to: http://stackoverflow.com/q/47551850
tagged with: pathos

http://stackoverflow.com/a/49058583
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49053953
accepted answer of: http://stackoverflow.com/q/49053953
has comment: http://stackoverflow.com/comment/85122182
downvote count: 0
has body: webapp2 has a built-in redirect method: return redirect('/some-path') However, I think you would probably rather send the gathered data to the greetings.html template? Under the POST method, you could do: template_values = { 'guestbook_name': guestbook_name, # etc., } template = JINJA_ENVIRONMENT.get_template('greetings.html') self.response.write(template.render(template_values))
type: AcceptedAnswer
score: 1

http://stackoverflow.com/a/49094944
score: 0
answers question: http://stackoverflow.com/q/49085577
type: Answer
has comment: http://stackoverflow.com/comment/85194952
has body: I got the answer guys: locals() I just need write some like: data= [["Name1",point],["Name2",point]] n=0 while n&lt;len(data): new_name="label"+str(n) locals()[new_name]= Text(data[n][1], data[n][0]) n+=1
has comment: http://stackoverflow.com/comment/85195018
has comment: http://stackoverflow.com/comment/85195126
has comment: http://stackoverflow.com/comment/85195325

http://stackoverflow.com/comment/84967233
has text: @LeviLesches I copied and pasted my exact code aswell as changed the print location/added the exact error log to show how my program executes.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48980908

http://stackoverflow.com/q/49063868
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49069610
tagged with: class
has answer: http://stackoverflow.com/a/49063946
downvote count: 0
score: 1
favorite count: 0
has title: pass a class as a parameter to a method in a different class in python
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: oop
has body: I am new to python and I have a project that is asking for building a shopping cart. it has a specific requirement that I should go with. I am stuck with the idea of make add method and remove. How can I use a class as a parameter to a method and why? Here is how my ItemToPurchase looks like class ItemToPurchase: def __init__(self, item_name, item_price, item_quantity, item_description): self.item_name = item_name self.item_price = item_price self.item_quantity = int(item_quantity) self.item_description = item_description def print_item_cost(self): if self.item_price &lt;=0: raise ValueError('Invaild price') price_for_quntatity = self.item_price * self.item_quantity print('%s %d @ %d = %d'%(self.item_name, self.item_quantity, self.item_price, price_for_quntatity )) def __str__(self): return ('%s'%(self.item_description)) and I am stuck with the Shopping cart method and here are the requirements Parameterized constructor which takes the customer name and date as parameters Attributes customer_name (string) current_date (string) cart_items (list) Methods add_item() - Adds an item to cart_items list. Has parameter ItemToPurchase. Does not return anything. remove_item() - Removes item from cart_items list. Has a string (an item's name) parameter. Does not return anything. If item name cannot be found, output this message: Item not found in cart. Nothing removed. Using exception

http://stackoverflow.com/q/49084393
tagged with: list
has title: How are .pop and .index being used here?
type: Question
answer count: 2
has body: I have a piece of code that I don't understand, I would appreciate it if someone could help me out. list1 = [48, 33, 46, 46, 87, 11, 50, 99, 65, 87] list2 = [48, 33, 46] duplicates = [list1.pop(list1.index(i)) for i in list1 if i in list2]
has answer: http://stackoverflow.com/a/49084644
has answer: http://stackoverflow.com/a/49084469
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: indexing

http://stackoverflow.com/a/48968740
score: 1
type: AcceptedAnswer
downvote count: 0
has body: As per the docs, Query.update takes 1 mandatory positional argument, which should be a dict of the attributes to update. You should update your code as following: # ... schemaGroup.validate(raw_dict) group_query.update(raw_dict) return self.get(userid) # ...
answers question: http://stackoverflow.com/q/48968536
has comment: http://stackoverflow.com/comment/84991424
type: Answer
accepted answer of: http://stackoverflow.com/q/48968536
upvote count: 1

http://stackoverflow.com/comment/85163101
comment on: http://stackoverflow.com/q/49078484
has text: This has nothing to do with types. Assignment isn't an expression in Python.
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68234842
has body: Clobbering. for a[-1] in a sets a[-1] = a[1] because of the for loop. In the subsequent iterations, it does that again, so the contents of the list cycle. When it does the 6th iteration, you might be expecting the print to be "exam." However, remember what happened in the first iteration. a[-1] = a[1]. The exam string no longer exists, because it was clobbered by the integer 1. At that time, both a[1] AND a[-1] are the integer 1. After the for loop completes, you exit its scope. In the main program's scope, the contents of the list a never changed. So your print at the end is irrelevant to what happened in the loop. The for loop accepts all the same assignment targets a regular assignment does, no matter how silly. So it's assigning to the last position of the list repeatedly. You really shouldn't use any indexing between for ... in. You should just write a variable name there, and don't write the name of any existing variable. No one would write code like this in a real project because for loops are not supposed to be used like this.
answers question: http://stackoverflow.com/q/49010129
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/122665121

http://stackoverflow.com/comment/85092608
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49043479
has text: This warning indicates that you have not configured data source in Database Tool Window in Intellij Idea. It doesn't mean that your code is wrong, it just shows that you don't have code completion based on your database schema. Configuration of datasource in Intellij is described here https://www.jetbrains.com/help/idea/2016.3/database-tool-window.html

http://stackoverflow.com/comment/85287675
comment on: http://stackoverflow.com/q/49118477
score: 0
has text: Fair enough. You could install Django or Flask alongside Jupyter. Then you would be able to run them from Jupyter.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49106196
has comment: http://stackoverflow.com/comment/85226780
answers question: http://stackoverflow.com/q/49103096
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85225309
accepted answer of: http://stackoverflow.com/q/49103096
upvote count: 2
has body: All the cudnn convolution functions are defined here: https://github.com/pytorch/pytorch/blob/1848cad10802db9fa0aa066d9de195958120d863/aten/src/ATen/native/cudnn/Conv.cpp This function doesn't exist anymore in the latest versions of pytorch. The closest thing that there is there is cudnn_convolution_forward. In version 0.1.12, the function is in the same file: https://github.com/pytorch/pytorch/blob/v0.1.12/torch/csrc/cudnn/Conv.cpp I would recommend against using using an unpublic api (one starting with _) and use a public method instead, but you probably already know that. In otherwords you should be using torch.backends.cudnn.enabled = True and then conv2d or conv3d depending on your use.
has comment: http://stackoverflow.com/comment/85225171

http://stackoverflow.com/a/49086139
score: 2
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49086055
downvote count: 0
has body: As @jonrsharpe pointed out, the variable name isn't a property of those values, so you'll have to attach it differently. I think the easiest way is to go about it like this: my_array = [[12.74087388, 'A'], [12.48817861, 'B'], etc] my_sorted_array = sorted(my_array) my_sorted_named_array = [i[1] for i in my_sorted_array]

http://stackoverflow.com/comment/85039632
has text: Fantastic. Thank you a ton, worked perfectly. Now just so that I understand as to what I was doing wrong I was just forgetting to set up the row after opening the .csv? So the new line you added just creates a readable format of that column?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49017138

http://stackoverflow.com/comment/84990859
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48991071
has text: Hi Ramesh, I'm sorry but it doesn't work u_u. For this input: {"new":[],"removed":[{"start":"2018-02-24","end":"2018-03-02"},{"start":"2018-03-03","end":"2018-03-09"},{"start":"2018-03-10","end":"2018-03-16"},{"start":"2018-03-17","end":"2018-03-23"},{"start":"2018-03-24","end":"2018-03-30"}]} it only gets the first one, as far as i know, **filter** will get the rows with at least one entry, but reviewing the code you sent, only gets the first one... am i missing something? why is not working? thanks!

http://stackoverflow.com/comment/84962701
type: Comment
type: QuestionComment
has text: @shanmuga Im still getting that error. And I dont find anything unusual in lines 306425 - 306435
comment on: http://stackoverflow.com/q/48970805
score: 0

http://stackoverflow.com/comment/85077713
has text: [(Decimal('-75.14596502345678'),), (Decimal('-75.145678932567894'),), (Decimal('-75.14523567843256'),), (Decimal('-75.14567825609123'),)]
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49036155
type: AnswerComment

http://stackoverflow.com/a/49036562
has comment: http://stackoverflow.com/comment/85082830
downvote count: 0
has comment: http://stackoverflow.com/comment/85080273
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85079628
score: 1
answers question: http://stackoverflow.com/q/49036317
accepted answer of: http://stackoverflow.com/q/49036317
has comment: http://stackoverflow.com/comment/85084227
type: Answer
has comment: http://stackoverflow.com/comment/85083497
has body: So the key to doing this efficiently is ensuring we don't have to revisit nodes over and over again. We can do this by starting with the output and working our way back: crivers = rivers[:] # copy the rivers list, as this process is destructive ckeys = set(river.split(";")[0] for river in crivers) # make a set for O(1) lookup result = {} while crivers: for river in crivers[:]: key, value = river.split(";") if value in ckeys: continue # skip rivers that are flowing into unprocessed rivers result[int(key)] = [int(value)] + result.get(int(value), []) ckeys.remove(key) crivers.remove(river) If the rivers list is sorted properly, this is O(n), if it's not sorted (or, in the worst case, reverse sorted), it's O(n**2). "Sorted properly", in this case, means they are sorted from root to leaf in our upside down tree... as our processing order is: 4, 5, 3, 6, 7, 2, 9, 10, 8, 1 The final result is: {1: [2, 3, 4, -999], 2: [3, 4, -999], 3: [4, -999], 4: [-999], 5: [4, -999], 6: [5, 4, -999], 7: [5, 4, -999], 8: [7, 5, 4, -999], 9: [6, 5, 4, -999], 10: [7, 5, 4, -999]} Which can be converted to your final format via: fmt_lst = [] for key in result: for val in result[key]: fmt_lst.append("%s;%s" % (key, val)) ['1;2', '1;3', '1;4', '1;-999', '2;3', '2;4', '2;-999', '3;4', '3;-999', '4;-999', '5;4', '5;-999', '6;5', '6;4', '6;-999', '7;5', '7;4', '7;-999', '8;7', '8;5', '8;4', '8;-999', '9;6', '9;5', '9;4', '9;-999', '10;7', '10;5', '10;4', '10;-999']
upvote count: 1

http://stackoverflow.com/comment/85074809
score: 0
type: Comment
type: QuestionComment
has text: Right. You're trying to use the `INSERT` command syntax on `UPDATE`. Why not format the `UPDATE` statement [the way SQLite3 expects it](http://www.sqlitetutorial.net/sqlite-update/)? In the end, it's just a string that you can build with Python.
comment on: http://stackoverflow.com/q/49034403

http://stackoverflow.com/comment/105533618
comment on: http://stackoverflow.com/q/49028871
score: 0
type: Comment
type: QuestionComment
has text: Duplicate of this question: https://stackoverflow.com/questions/39643043/pip-installl-tsne-doesnt-work/39643572#39643572

http://stackoverflow.com/q/49119734
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49120694
has body: I am having trouble with executing UPDATE statements. In the code below when I write con.execute() it writes to the database, but if I write c.execute() it doesn't write to the database. Long comment is where the code in question lies. Most Relevant snippet def write_data(con, c): geolocator = Nominatim() table = c.execute('SELECT * FROM playerdata WHERE birth_place_long is null AND birth_place is not null').fetchall() for i in table: try: location = getgeo(i[4], geolocator) lat, long = location.latitude, location.longitude except: print(i[0]) ''' changing to c.execute doesnt work ''' con.execute('UPDATE playerdata SET birth_place_lat = ?, birth_place_long = ? WHERE id = ?', (1, 1, i[0])) print("failed" + i[1] + " " + i[2]) con.commit() else: c.execute('UPDATE playerdata SET birth_place_lat = ?, birth_place_long = ? WHERE id = ?', (lat, long, i[0])) print(i[1] + " " + i[2]) con.commit() con.close() Full code below: import csv from geopy.geocoders import Nominatim import sqlite3 import socket import geopy.exc import pandas as pd def connect_db(): con = sqlite3.connect('c:/s_db2.sqlite3') c = con.cursor() return con, c def getgeo(place, geolocator): try: location = geolocator.geocode(place) return location except (socket.timeout): return getgeo(place, geolocator) except geopy.exc.GeocoderTimedOut: return 0 def write_data(con, c): geolocator = Nominatim() table = c.execute('SELECT * FROM playerdata WHERE birth_place_long is null AND birth_place is not null').fetchall() for i in table: try: location = getgeo(i[4], geolocator) lat, long = location.latitude, location.longitude except: print(i[0]) ''' changing to c.execute doesnt work ''' con.execute('UPDATE playerdata SET birth_place_lat = ?, birth_place_long = ? WHERE id = ?', (1, 1, i[0])) print("failed" + i[1] + " " + i[2]) con.commit() else: c.execute('UPDATE playerdata SET birth_place_lat = ?, birth_place_long = ? WHERE id = ?', (lat, long, i[0])) print(i[1] + " " + i[2]) con.commit() con.close() while True: write_da…
accepted answer: http://stackoverflow.com/a/49123690
has answer: http://stackoverflow.com/a/49120694
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85270303
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49123690
has comment: http://stackoverflow.com/comment/85246088
tagged with: sqlite
tagged with: python
has title: python sqlite3 - cursor vs connections - executing UPDATE statements

http://stackoverflow.com/q/49115700
tagged with: signal-processing
linked to: http://stackoverflow.com/q/20626994
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20626994
has body: I am working on a few signal processing concepts. And I prefer to use Python over MATLAB. I require the complementary CDF of the Gaussian to model my system. I was able to write MATLAB's qfunc() as: from scipy import special as sp def qfunc(arg): return 0.5-0.5*sp.erf(arg/1.414) However, how would I write a similar function for qfuncinv()?
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has title: Python equivalent of MATLAB's qfuncinv()
has answer: http://stackoverflow.com/a/49115834
score: 0
has comment: http://stackoverflow.com/comment/85236811
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/84960441
has text: probably want to avoid using pandas as that's more overhead plus holding everything in memory
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48977607

http://stackoverflow.com/a/49061900
accepted answer of: http://stackoverflow.com/q/49061818
answers question: http://stackoverflow.com/q/49061818
has body: You would have to do it like this. It would only work for instance methods, not functions. class Something: self.lock = Lock( .. ) #decorator def _lock(func): def wrapper(self, *args, **kwargs): self.lock.acquire() r = func(self, *args, **kwargs) self.lock.release() return r return wrapper @_lock def some_func(self): #do something
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/49072608
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49071959
accepted answer of: http://stackoverflow.com/q/49071959
has body: Each packet header states how long it is. Once the parser has read that header, it can calculate the position of the next one. So as far as I know, you cannot open a pcap file and instantly locate packet 30; you'll need to parse the headers of the first 29. But you don't have to keep all packets in memory either, as long as you process them while receiving. i = 0 for pkt in sniff(offline=path, prn=action): if i == 30: print pkt break
upvote count: 1

http://stackoverflow.com/q/49071908
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49072392
has answer: http://stackoverflow.com/a/49072502
type: AnsweredQuestion
tagged with: django
possible better answer: http://stackoverflow.com/a/49072392
downvote count: 1
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/49072502
answer count: 2
upvote count: 0
has title: No Such Table: 'Auth User' Error with Django Sign Up Form
has body: Trying to register a user on my site, and getting this error when submitting. OperationalError: no such table: auth_user i've run makemigrations and migrate as suggested in other posts but it hasn't helped. if i go to the accounts/sign_up page (which calls the sign_in view), enter the username and password, i get the aforementioned error. Note that in my settings file, i am also bypassing auth_user model like so: AUTH_USER_MODEL = "accounts.User" this is the traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 323. return Database.Cursor.execute(self, query, params) The above exception (no such table: auth_user) was the direct cause of the following exception: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\accounts\views.py" in sign_up 46. if form.is_valid(): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\forms.py" in is_valid 161. return self.is_bound and not self.errors File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\forms.py" in errors 153. self.full_clean() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\forms.py" in full_clean 364. self._post_clean() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py" in _post_clean 402. self.validate_uni…

http://stackoverflow.com/q/48984319
type: Question
tagged with: function
linked to: http://stackoverflow.com/q/4979542
duplicate of: http://stackoverflow.com/q/4979542
score: 0
has body: I have a function like this. For *args I want to use a list of different Excel tables. def my_function(*args): for x in args: # some code I use this to get the full paths to the tables and make a list of them. There are only tables in the folder I want to use. cust_tables = os.listdir(r"my_folder") cust_path = [r"my_folder" + "\\" + x for x in cust_tables] This creates a list like this: ['C:\\some\\path\\to\\my\\table_1.xlsx', 'C:\\some\\path\\to\\my\\table_2.xlsx'] When I try to call the function my_function(cust_path), I get this error: File "C:\Users\my.name\AppData\Local\Continuum\anaconda3\lib\genericpath.py", line 30, in isfile st = os.stat(path) TypeError: stat: path should be string, bytes, os.PathLike or integer, not list I can call the function when using my_function(cust_path[0],cust_path[1]). Where did I make a mistake?
answer count: 1
has title: Cannot use list as a function parameter in Python
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48984363
tagged with: parameters
tagged with: list

http://stackoverflow.com/comment/85224099
type: QuestionComment
comment on: http://stackoverflow.com/q/49109150
type: Comment
has text: @AbdullahAhmedGhaznavi No, the problem is not of named entity recognition.
score: 0

http://stackoverflow.com/q/48973678
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84952274
upvote count: 1
downvote count: 1
has body: I'm currently working with Automate the boring stuff with Python and I'm dealing with project where I must display data from tableData in changed order and then justify each element to the right based on length of longest element in each list so it will display something like this: jabłka Alicja psy pomarańcze Bob koty and so on.. I know that I must get the first element of each nested list, then the second etc but I'm really struggling to to this and I'm hoping that you can help me with that. PS Don't worry about that strange letters in list items, it's my native language :) tableData = [ ['jabłka', 'pomarańcze', 'wiśnie', 'banany'], ['Alicja', 'Bob', 'Karol', 'Dawid'], ['psy', 'koty', 'łosie', 'gęsi'] ] def printTable(): colWidth = [0] * len(tableData) for i in range(len(tableData)): for j in range(len(tableData[i])): if colWidth[i] &lt; len(tableData[i][j]): colWidth[i] = len(tableData[i][j]) printTable()
has answer: http://stackoverflow.com/a/48973712
has title: How to get items from each inner list in order
has answer: http://stackoverflow.com/a/48973866
has answer: http://stackoverflow.com/a/48973890
type: Question
has comment: http://stackoverflow.com/comment/84952282
has comment: http://stackoverflow.com/comment/84952295
has answer: http://stackoverflow.com/a/48973735
tagged with: python
answer count: 4

http://stackoverflow.com/q/49004255
tagged with: pytorch
score: 0
has answer: http://stackoverflow.com/a/49029126
answer count: 1
has title: How to check the correct Training Class In PyTorch
tagged with: deep-learning
has body: I'm new with Pytorch, I tried to write my training class, but I had this error import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch.optim as optim import tqdm class MLPNet(nn.Module): def __init__(self): super(MLPNet, self).__init__() self.first_fully_connected = nn.Linear(8*8, 100) self.last_fully_connected = nn.Linear(100, 10) def forward(self, x): x = x.view(-1, 8*8) # reshape input tensor to the size (batch_size, 8*8) x = F.sigmoid(self.first_fully_connected(x)) x = F.sigmoid(self.last_fully_connected(x)) return x def training(mlp, X, y, epochs=1, lr=.2, batch_size=101): # solver # loss solver = torch.optim.SGD(mlp.parameters(), lr=lr, momentum=0.9) loss = nn.CrossEntropyLoss() # nn.NLLLoss() n_batches = (len(X) + batch_size - 1) // batch_size for epoch in tqdm.tqdm(range(epochs)): for i in range(n_batches): slice_ = np.s_[i::n_batches] X_batch = Variable(torch.from_numpy(X[slice_])).float() y_batch = Variable(torch.from_numpy(y[slice_, np.newaxis])).float() # X_batch = Variable(torch.from_numpy(X[slice_])).long() # y_batch = Variable(torch.from_numpy(y[slice_, np.newaxis])).long() print(type(X_batch.data)) print(type(y_batch.data)) ### BEGIN: your optim step here. do not forget to reset gradients # Clear gradients w.r.t. parameters solver.zero_grad() prediction = mlp(X_batch) # Forward pass to get output/logits #outputs = mlp(X_batch) # Calculate Loss: softmax --&gt; cross entropy loss #loss = criterion(outputs, y_batch) loss_f = loss(prediction, y_batch) # Getting gradients w.r.t. parameters loss_f.backward() # Updating parameters solver.step() ### END return mlp mlp = nn.Sequential( #### Your net here nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 2) ) model_mlp = training(mlp, X_std, y_std) But I got this error, I tried the change the type but still faced that error. I tried the changed the loss function too but still that error. RuntimeError Traceback (most recent call last) in ()…
tagged with: neural-network
type: UnansweredQuestion
type: Question
tagged with: python

http://stackoverflow.com/comment/85110226
score: 1
comment on: http://stackoverflow.com/q/49052756
type: QuestionComment
has text: You are correct, that makes it a function file, not a script. Read more info here: https://uk.mathworks.com/help/matlab/matlab_prog/scripts-and-functions.html
type: Comment

http://stackoverflow.com/comment/97766506
comment on: http://stackoverflow.com/a/49114348
score: 0
type: Comment
has text: Great answer. The only problem I have is understanding why occurs check is correct. In your example ``{Y=g(Y)}``, why is it a failure in general? If ``g`` is the identity function, would it not be viable? I guess my problem arises from the question, which kind of equality is applied here. (Value vs Instance equality?)
type: AnswerComment

http://stackoverflow.com/a/49087118
has body: You can add Labels inside your button: here i create a helper rule to avoid repeating stuff about how i want to size some labels &lt;AutoSizedLabel@Label&gt;: size_hint: None, None size: self.texture_size padding: 10 then, i add a floatlayout inside my button, to the size/position of the button, to make positionning of these labels easier, i also create dynamic properties to be able to easily pass text values for these labels, and i nest them in the FloatLayout, using the pos_hint system to position them. &lt;MyCrazyButton@Button&gt;: top_right_text: '' top_left_text: '' bottom_right_text: '' bottom_left_text: '' FloatLayout: size: root.size pos: root.pos AutoSizedLabel: text: root.top_right_text or '' pos_hint: {'top': 1, 'right': 1} AutoSizedLabel: text: root.bottom_right_text or '' pos_hint: {'y': 0, 'right': 1} AutoSizedLabel: text: root.top_left_text or '' pos_hint: {'top': 1, 'x': 0} AutoSizedLabel: text: root.bottom_left_text or '' pos_hint: {'y': 0, 'x': 0} and then i can use it like this: MyCrazyButton: text: 'boring text' bottom_left_text: 'bl' top_left_text: 'tl' bottom_right_text: 'br' top_right_text: 'tr' edit: of course, i did all the possibilities, if you don't need all of them, you can avoid creating a lot of unnecessary widgets by removing them from the rule!
score: 0
accepted answer of: http://stackoverflow.com/q/49051262
answers question: http://stackoverflow.com/q/49051262
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85212379

http://stackoverflow.com/comment/84948651
comment on: http://stackoverflow.com/q/48971720
has text: @VivekKalyanarangan. That's stated quite clearly in the question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48977023
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84959424
upvote count: 0
linked to: http://stackoverflow.com/q/17257631
tagged with: vigenere
type: Question
has title: Vigenere Cipher Incredibly Confused
score: -2
has comment: http://stackoverflow.com/comment/84959148
has answer: http://stackoverflow.com/a/48977380
accepted answer: http://stackoverflow.com/a/48977380
downvote count: 2
has comment: http://stackoverflow.com/comment/84959633
answer count: 1
has body: ive been stuck on this for hours now. I've been trying to encrypt a preset message with a preset vigenere key. so that the name lets say 'bob' shifts by the key 'abc' it shifts the word bob by the ascii values 'abc'. I have this code right now but it isn't printing anything whatsoever and i'm incredibly confused on how to do this. def vigenere(key, letter): keyVal = ord(key) letterVal = ord(letter) keyVal = keyVal - 97 letterVal = keyVal + letterVal if letterVal &gt;= ord("z"): letterVal = letterVal - 26 print letterVal
duplicate of: http://stackoverflow.com/q/17257631
favorite count: 0
tagged with: encryption
tagged with: python
duplicate of: http://stackoverflow.com/q/19130958
linked to: http://stackoverflow.com/q/33816697

loops
tags question: http://stackoverflow.com/q/49100254
tags question: http://stackoverflow.com/q/49107346
tags question: http://stackoverflow.com/q/49013649
tags question: http://stackoverflow.com/q/49074117
tags question: http://stackoverflow.com/q/49007740
tags question: http://stackoverflow.com/q/49108378
tags question: http://stackoverflow.com/q/49041693
tags question: http://stackoverflow.com/q/48963698
tags question: http://stackoverflow.com/q/49033899
tags question: http://stackoverflow.com/q/49041001
tags question: http://stackoverflow.com/q/49078472
tags question: http://stackoverflow.com/q/48968467
tags question: http://stackoverflow.com/q/49061027
tags question: http://stackoverflow.com/q/49042181
tags question: http://stackoverflow.com/q/49049374
tags question: http://stackoverflow.com/q/49026520
tags question: http://stackoverflow.com/q/49061754
tags question: http://stackoverflow.com/q/48971259
tags question: http://stackoverflow.com/q/49045203
tags question: http://stackoverflow.com/q/48966469
tags question: http://stackoverflow.com/q/48995089
tags question: http://stackoverflow.com/q/49102589
type: Tag
tags question: http://stackoverflow.com/q/49098605
tags question: http://stackoverflow.com/q/49113507
tags question: http://stackoverflow.com/q/49076857
tags question: http://stackoverflow.com/q/49072866
tags question: http://stackoverflow.com/q/49080744
tags question: http://stackoverflow.com/q/48972812
tags question: http://stackoverflow.com/q/48987179
tags question: http://stackoverflow.com/q/48968426
tags question: http://stackoverflow.com/q/49061180
tags question: http://stackoverflow.com/q/49014601
tags question: http://stackoverflow.com/q/49037570
tags question: http://stackoverflow.com/q/49114490
tags question: http://stackoverflow.com/q/49117163
tags question: http://stackoverflow.com/q/49000384
tags question: http://stackoverflow.com/q/49001710
tags question: http://stackoverflow.com/q/49060594
tag name: loops
tags question: http://stackoverflow.com/q/49059091
tags question: http://stackoverflow.com/q/48971338
tags question: http://stackoverflow.com/q/49082862
tags question: http://stackoverflow.com/q/48999368
tags question: http://stackoverflow.com/q/49046584
tags question: http://stackoverflow.com/q/48992398
tags question: http://stackoverflow.com/q/48982700
tags question: http://stackoverflow.com/q/48991665
tags question: http://stackoverflow.com/q/49083532
tags question: http://stackoverflow.com/q/49093373
tags question: http://stackoverflow.com/q/48969346
tags question: http://stackoverflow.com/q/49019238
tags question: http://stackoverflow.com/q/49091259
tags question: http://stackoverflow.com/q/49101016
tags question: http://stackoverflow.com/q/49007854
tags question: http://stackoverflow.com/q/49066523

http://stackoverflow.com/q/49093410
type: Question
linked to: http://stackoverflow.com/q/8608587
has comment: http://stackoverflow.com/comment/85191964
score: 0
has comment: http://stackoverflow.com/comment/85192657
has comment: http://stackoverflow.com/comment/85193923
tagged with: python-3.x
tagged with: python-internals
answer count: 0
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/8608587
has title: Python builtins.py
has body: When I download one module in PyCharm, I can glance over the code in the .py file. For example, I can find the code in re.py to know more about the method. But when I want to know something about the methods about list, I find the builtins.py. It's a pity that 'pass' instead of the details. def abs(*args, **kwargs): # real signature unknown """ Return the absolute value of the argument. """ pass I know some methods do with C. Can you tell me what should I do to find the code in the document?

http://stackoverflow.com/comment/85063602
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49026183
has text: food for thought. actually, i dont see any methods in lxml module that can give you xpath of an element but you can build xpath yourself, given that XML are usually very ordered. This can be done. I have a code to do that, but its not very efficient.
score: 0

http://stackoverflow.com/comment/84950749
has text: I am not sure if I understand your question completely. Could you please provide an example and output?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48969784
score: 0

http://stackoverflow.com/a/49067406
has comment: http://stackoverflow.com/comment/85140354
answers question: http://stackoverflow.com/q/49067258
downvote count: 0
has body: Try the following and ask any question you might have counter = 0 total = 0 number = int(raw_input("Enter any number: ")) while number != -1: counter += 1 total += number number = int(raw_input("Enter another number: ")) if counter == 0: counter = 1 # Prevent division by zero print total / counter
upvote count: 2
has comment: http://stackoverflow.com/comment/85140454
has comment: http://stackoverflow.com/comment/85140406
type: Answer
score: 2

http://stackoverflow.com/comment/85045168
comment on: http://stackoverflow.com/q/49019717
has text: That's fine. Can you post the code you have somewhere so I can test it locally without having to copy manually from the video?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85165673
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49079736
has text: I´m running in a BeagleBone Board. And I have successful connection for other server.

http://stackoverflow.com/a/49021668
score: 7
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49021589
accepted answer of: http://stackoverflow.com/q/49021589
upvote count: 7
has body: Given this is presumably Python 3 source code, the likely encoding is UTF-8 (it's the standard encoding for Python 3 source code). If that's the case, changing open("somefile.py") to open("somefile.py", encoding="utf-8") would specify the encoding explicitly, overriding the locale default, which should allow you to read it in correctly. For idiomatic code, you'd also want to use a with statement (to guarantee deterministic closing of the file), making it: with open("somefile.py", encoding="utf-8") as f: exec(f.read())

http://stackoverflow.com/comment/85233590
comment on: http://stackoverflow.com/q/49080548
score: 0
type: Comment
type: QuestionComment
has text: What user is Django running under?

http://stackoverflow.com/comment/85124911
score: 0
has text: There's not enough information here. Setting `DEBUG = False` should work, so you need to provide more information on how to reproduce the problem. Perhaps you have changed the wrong settings file, or you haven't saved your settings file or restarted the server after making the change.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49059772

http://stackoverflow.com/q/49075041
has comment: http://stackoverflow.com/comment/88708976
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85156158
has comment: http://stackoverflow.com/comment/88749913
score: 1
has answer: http://stackoverflow.com/a/61855090
has body: I have a Python project that runs in a docker container and I am trying to convert to a multistage docker build process. My project depends on the cryptography package. My Dockerfile consists of: # Base FROM python:3.6 AS base RUN pip install cryptography # Production FROM python:3.6-alpine COPY --from=base /root/.cache /root/.cache RUN pip install cryptography \ &amp;&amp; rm -rf /root/.cache CMD python Which I try to build with e.g: docker build -t my-python-app . This process works for a number of other Python requirements I have tested, such as pycrypto and psutil, but throws the following error for cryptography: Step 5/6 : RUN pip install cryptography &amp;&amp; rm -rf /root/.cache ---&gt; Running in ebc15bd61d43 Collecting cryptography Downloading cryptography-2.1.4.tar.gz (441kB) Collecting idna&gt;=2.1 (from cryptography) Using cached idna-2.6-py2.py3-none-any.whl Collecting asn1crypto&gt;=0.21.0 (from cryptography) Using cached asn1crypto-0.24.0-py2.py3-none-any.whl Collecting six&gt;=1.4.1 (from cryptography) Using cached six-1.11.0-py2.py3-none-any.whl Collecting cffi&gt;=1.7 (from cryptography) Downloading cffi-1.11.5.tar.gz (438kB) Complete output from command python setup.py egg_info: No working compiler found, or bogus compiler options passed to the compiler from Python's standard "distutils" module. See the error messages above. Likely, the problem is not related to CFFI but generic to the setup.py of any Python package that tries to compile C code. (Hints: on OS/X 10.8, for errors about -mno-fused-madd see http://stackoverflow.com/questions/22313407/ Otherwise, see https://wiki.python.org/moin/CompLangPython or the IRC channel #python on irc.freenode.net.) ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-uyh9_v63/cffi/ Obviously I was hoping not to have to install any compiler on my production image. Do I need to copy across another directory other than /root/.cache?
upvote count: 1
linked to: http://stackoverflow.com/q/22313407
type: Question
tagged with: docker-multi-stage-build
has comment: http://stackoverflow.com/comment/85218518
has answer: http://stackoverflow.com/a/49075645
tagged with: docker
has comment: http://stackoverflow.com/comment/85156083
answer count: 2
has title: Cryptography Python Docker multistage build
downvote count: 0

http://stackoverflow.com/q/49063730
has body: In Numerical Methods in Engineering with Python, 2nd Edition, Author: Jaan Kiusalaas, I wrote the same module found on page 146 that calculates the roots, f(x) = 0, using the bisection method: from math import log,ceil import error def bisection2(f,x1,x2,switch=0,tol=1.0e-9): f1 = f(x1) if f1 == 0.0: return x1 f2 = f(x2) if f2 == 0.0: return x2 if f1*f2 &gt; 0.0: error.err('Root is not bracketed') n = ceil(log(abs(x2 - x1)/epsilon)/log(2.0)) for i in range(n): x3 = 0.5*(x1 + x2); f3 = f(x3) if (switch == 1) and (abs(f3) &gt; abs(f1)) \ (abs(f3) &gt; abs(f2)): return None if f3 == 0.0:return x3 if f2*f3 &lt; 0.0: x1 = x3; f1 = f3 else: x2 = x3; f2 = f3 return (x1 + x2)/2.0 I am encountering the following error: ImportError Traceback (most recent call last) /usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where) 173 else: 174 filename = fname --> 175 builtin.execfile(filename, *where) /home/uwhpsc/Desktop/bisection2/bisection2.py in () 1 from math import log,ceil ----> 2 import error 3 4 def bisection2(f,x1,x2,switch=0,tol=1.0e-9): 5 f1 = f(x1) ImportError: No module named error Kindly could anyone please advise me how to solve this issue?
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85132545
tagged with: bisection
has title: ImportError: No module named error
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49063790
accepted answer: http://stackoverflow.com/a/49063790
type: Question
tagged with: python-2.7
tagged with: numerical-methods
answer count: 1

http://stackoverflow.com/a/76187947
has body: Go to the Cognito Service Then, select the app client Click Edit , And Select USER_PASSWORD_AUTH After That I have tried to login &amp; Got Successful Response :
type: Answer
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49000676
downvote count: 0

http://stackoverflow.com/comment/85111970
comment on: http://stackoverflow.com/a/49052124
has text: I'm sorry I did not make it clear. I have re-edit my question . Thank you very much for your help .
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85026659
type: Comment
type: QuestionComment
score: 0
has text: Thanks for advice, I will try next selenium,hopefully that will help to get the class needed.
comment on: http://stackoverflow.com/q/49010813

http://stackoverflow.com/a/49110088
answers question: http://stackoverflow.com/q/49109485
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85226157
upvote count: 1
score: 1
has body: For issue 1 I would go with the answer posted by @vlad : use a geometric distance. Assuming this suits you, you can look at issue 2 in geometric terms : let f1 be the X axis and f2 the Y axis. Frequency tuples at an equal distance of (f1, f2) will be on a circle around (f1, f2). It doesn't matter where the center point (f1, f2) lies, the closest points will always be at the same (x, y) offset from (f1, f2). This means you can calculate once and for all the ordering of these offsets, then add them to whatever (f1, f2) you are interested in. # do this once, and keep this variable around offsets = [(a, b) for a in range(-3, +4) for b in range(-3, +4)] offsets.sort(key=lambda x: x[0] ** 2 + x[1] ** 2) # for any f1, f2 get the closest tuples closest = [(f1 + o[0], f2 + o[1]) for o in offsets]
accepted answer of: http://stackoverflow.com/q/49109485

http://stackoverflow.com/q/49015736
has answer: http://stackoverflow.com/a/49016135
has body: msg = await self.bot.get_message(channel, req["message_id"]) channel and req["message_id"] are defined, the IDs are parsed as str (if int, then AttributeError would be raised) and the message is in the channel, yet the console output is this https://i.sstatic.net/Gp5vH.png. The bot has Administrator permission.
answer count: 1
tagged with: discord
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85037375
type: UnansweredQuestion
tagged with: python
has title: 404: Unknown Message (Discord.py v0.16.12)
downvote count: 0
score: 1
type: Question
tagged with: discord.py
upvote count: 1

http://stackoverflow.com/comment/85003401
type: AnswerComment
comment on: http://stackoverflow.com/a/48998978
type: Comment
score: 1
has text: The first one is correct. Since the second one has backslashes when it prints, it means it didn't escape the `"`. The first one prints it without backslashes, which means it is escaped.

http://stackoverflow.com/q/49052264
linked to: http://stackoverflow.com/q/24082784
has comment: http://stackoverflow.com/comment/85109020
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has title: pandas split dates into months
answer count: 0
score: 0
has body: I have a pandas dataframe that has the begin date and end date of each event (like the table below) Table Is there a datetime tool in pandas that can help me convert this into a dataframe like the table below Table If there is no pandas function, what is the best way to accomplish this result? Thanks!
type: Question
has comment: http://stackoverflow.com/comment/85109107
has comment: http://stackoverflow.com/comment/85158335
has comment: http://stackoverflow.com/comment/85110572
tagged with: pandas

http://stackoverflow.com/comment/85126896
comment on: http://stackoverflow.com/a/49060836
score: 2
has text: I agree on your design suggestion but the question is tagged `type-safety` and it explicitly asked "*...so that the test above will **generate an error***"
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/99676315
type: Comment
score: 7
has text: I know this is old but I am looking for the answer too - the screenshot shows images are disabled, but CSS is not, otherwise the layout would not be working, right? And the code block shown does not mention stylesheets ... does it mean it is not possible to disable CSS?
comment on: http://stackoverflow.com/a/53481064
type: AnswerComment

http://stackoverflow.com/q/48977945
tagged with: string
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48977987
tagged with: python
type: AnsweredQuestion
tagged with: list
has title: How to split strings in lists
possible better answer: http://stackoverflow.com/a/48978113
has body: I have a text in a file with multiple lines. I would like to create one big list, with each line as a seperate list inside. Within these lists each word should be a string. This is my code at the moment, I am failling to split the strings within the lists. f = open("test.txt","r") for line in f.readlines(): line2= line.split(",") print(line2) f.close() This is the output: ['Das ist 1e\n'] ['Textdatei', '\n'] ['bestehend aus mehreren WÃ¶rtern.']
has answer: http://stackoverflow.com/a/48978113
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/48977987
tagged with: split
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/85005933
score: 1
comment on: http://stackoverflow.com/q/49000112
type: Comment
type: QuestionComment
has text: If you just type /usr/bin/python3.6 in console, does it start Python 3.6 shell?

http://stackoverflow.com/comment/85158286
type: Comment
comment on: http://stackoverflow.com/a/49076129
has text: Hi Bernie, the column `expected` is my expected final result. I just manually create this column. What I want is use Python to create this column. My apologies for misunderstanding.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85223121
comment on: http://stackoverflow.com/q/49101560
has text: Which of the several [Python bindings for ffmpeg](https://pypi.python.org/pypi?%3Aaction=search&term=ffmpeg&submit=search) are you actually trying to use? If the answer is 'don't know', you have some reading up to do first.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85172795
type: QuestionComment
has text: Possible duplicate of [How to ignore hidden files using os.listdir()?](https://stackoverflow.com/questions/7099290/how-to-ignore-hidden-files-using-os-listdir)
comment on: http://stackoverflow.com/q/49083791
score: 0
type: Comment

http://stackoverflow.com/comment/85175418
type: Comment
has text: this is nlogn complexity...my solution is o of n
comment on: http://stackoverflow.com/a/49085040
score: 0
type: AnswerComment

http://stackoverflow.com/a/48971391
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48971247
answers question: http://stackoverflow.com/q/48971247
type: AcceptedAnswer
downvote count: 0
has body: Shift i = i + 1 out of the second loop, like this. a=[] i=0 for record in tablerows: a.append([]) rowcells=record.findAll('td') for data in rowcells[1:4]: a[i].append(data.text) print(a) i=i+1

http://stackoverflow.com/comment/85013902
has text: Please edit the question to include a sample from `list_stim.csv`
score: 0
comment on: http://stackoverflow.com/q/48978698
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48984512
type: UnansweredQuestion
tagged with: multithreading
has answer: http://stackoverflow.com/a/67934884
tagged with: python
has title: Making a timer: timeout inaccuracy of threading.Event.wait - Python 3.6
linked to: http://stackoverflow.com/q/12435211
tagged with: sleep
type: Question
upvote count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/63041290
has answer: http://stackoverflow.com/a/65889635
score: 4
linked to: http://stackoverflow.com/q/29082268
has body: First of all, I am new to Python and not familiar with its functionalities. I've been mainly using MATLAB. PC brief spec.: Windows 10, Intel i7 I am trying to make a timer class for periodic execution of a function such as MATLAB has, which is obviously borrowed from Java timer. The MATLAB timer has an about 1 ms resolution and I've never seen it exceeds 2 ms in any situation. In fact, it is accurate enough for my project. Recently, I planned to move to Python because of the poor parallel computing and web access features of MATLAB. However, unfortunately, the standard packages of Python offer somewhat low-level of timer (threading.Timer) compared to MATLAB that I had to make my own timer class. First, I referred to the QnA Executing periodic actions in Python [duplicate]. The solution suggested by Michael Anderson gives a simple idea of drift correction. He used time.sleep() to keep the period. The approach is highly accurate and sometimes showed better accuracy over the MATLAB timer. approx. 0.5 ms resolution. However, the timer cannot be interrupted (pause or resume) during being captured in time.sleep(). But I sometimes have to stop immediately regardless of whether it is in sleep() or not. A solution to the problem I found is to utilize the Event class in threading package. Refer to Python threading.timer - repeat function every 'n' seconds . Using the timeout feature of Event.wait(), I could make a time gap between executions and it is used to keep the period. That is, the event is usually cleared so that wait(timeout) can act like time.sleep(interval) and I could exit from wait() immediately, when needed, by setting event. Everything seemed fine then but there is a critical problem in Event.wait(). The time delay varies too largely from 1 ~ 15 ms. I think it comes from the overhead of Event.wait(). I made an example code that shows accuracy comparison between time.sleep() and Event.wait(). This sums total of 1000 iterations of 1 ms sleep() and wait() to see t…
answer count: 3
linked to: http://stackoverflow.com/q/8600161
tagged with: periodic-task
favorite count: 0
tagged with: timer

http://stackoverflow.com/q/49099798
has comment: http://stackoverflow.com/comment/85205333
accepted answer: http://stackoverflow.com/a/49100379
tagged with: python
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/49100105
has answer: http://stackoverflow.com/a/49100105
type: Question
has comment: http://stackoverflow.com/comment/85205013
has title: Add new variable and value to list from input
has body: Ok so I have looked around and seen similar questions and have tried a few different things. Here is what I am trying to accomplish. I have a list of variables with float values already assigned to them. I want to be able to ask the user to chose a variable from list and add float values to existing variable or create a new variable and assign it a value and add it to the list. (I'm using python 3) Here is what I have currently A = 0.00 B = 0.00 C = 0.00 List = [A,B,C] while True: Var = int(input("add to A(0), B(1), C(2) or add new varible (100)")) if Var != 100: amount = float(input("amount")) List[Var] = List[Var] + amount if Var == 100: newVar = input("Var name, amount").split(' ') newVar[0] = float(newVar[1]) List = List + newVar[0] So I am trying to get the user to name the variable and define the amount and then add it to this list. When I run it I get this message Traceback (most recent call last): File "/Users/jmc/Documents/test.py", line 14, in &lt;module&gt; newVar[0] = float(newVar[1]) IndexError: list index out of range The adding to existing function part is fine I believe. I would really appreciate if someone could tell where I am going wrong or if this is a ridiculous way of going about doing this. If it is, what is a more efficient way?
tagged with: variables
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49100379
has comment: http://stackoverflow.com/comment/85205182
has comment: http://stackoverflow.com/comment/85205269

bokeh
tags question: http://stackoverflow.com/q/49052688
tags question: http://stackoverflow.com/q/49041338
tags question: http://stackoverflow.com/q/49054952
type: Tag
tags question: http://stackoverflow.com/q/49062974
tags question: http://stackoverflow.com/q/49032296
tags question: http://stackoverflow.com/q/49059916
tags question: http://stackoverflow.com/q/48982260
tags question: http://stackoverflow.com/q/48994936
tags question: http://stackoverflow.com/q/48991892
tags question: http://stackoverflow.com/q/49112882
tags question: http://stackoverflow.com/q/49017042
tags question: http://stackoverflow.com/q/49055972
tags question: http://stackoverflow.com/q/49028057
tags question: http://stackoverflow.com/q/49100810
tag name: bokeh
tags question: http://stackoverflow.com/q/49117751

http://stackoverflow.com/a/49026034
score: 0
has body: It's possible to do this, but not recommended. You do not have any control over what the string contains if it comes from the user. There is probably a better way to achieve what you really want. If you really, absolutely, unavoidably have to, you can use eval: x = eval('dataframe["Column_name"].sum()') But it is probably easier to only take, for example, the column name from the user and use that in a function call: column_name = "Column_name" # or read it from the file x = dataframe[column_name].sum()
answers question: http://stackoverflow.com/q/49025999
type: Answer

http://stackoverflow.com/comment/85196727
type: Comment
has text: I needed to restructure the else statement to get everything to work and then run my command. In this order - latest_email_uid == data[0].split()[-1] > result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') > raw_email = data[0][1] It runs and waits yet when it seems to run again I get this error..... in next comment.....
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49086626

http://stackoverflow.com/q/49053783
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49054096
possible better answer: http://stackoverflow.com/a/49053921
upvote count: 7
type: Question
tagged with: dataframe
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49053968
score: 7
favorite count: 0
has body: The main problem I have right now is that DataFrame.quantile() doesn't work with Decimals. I can convert my Dataframe to floats by using df.convert_objects(convert_numeric=True), but this generates a deprecation warning and the suggested replacement infer_objects() doesn't work. As an alternative, I could use Dataframe.round on my input data instead of converting them to Decimals. I assume that this should be safe for direct comparisons (I am indexing on a column to subtract two dataframes from each other, e.g. df1.set_index('Time') - df2.set_index('Time')) but I can't be certain.
has title: How should I convert a Dataframe full of decimals to floats?
has answer: http://stackoverflow.com/a/49054096
tagged with: python
has answer: http://stackoverflow.com/a/49053921

http://stackoverflow.com/comment/85130654
comment on: http://stackoverflow.com/q/49062669
score: 0
type: Comment
type: QuestionComment
has text: @kitman0804 - This is a minimal code example of what I'm trying to accomplish. In my actual problem, the data (represented as `df1` and `df2`in my question) are imported from external sources so I don't have the option to create them differently. Unless I'm misunderstanding what you're suggesting.

http://stackoverflow.com/q/49103709
has body: I am trying to modify a python program to be able to communicate with a C++ program using shared memory. The main responsibility of the python program is to read some video frames from an input queue located in shared memory, do something on the video frame and write it back to the output queue in shared memory. I believe there are few things I need to achieve and it would be great if someone can shed some light on it: Shared memory: In C/C++, you can use functions like shmget and shmat to get the pointer to the shared memory. What is the equivalent way to handle this in python so both python and C++ program can use the same piece of shared memory? Synchronization: Because this involves multi-processing, we need some sort of locking mechanism for the shared memory in both C++ and python programs. How can I do this in python? Many thanks!
has answer: http://stackoverflow.com/a/49118076
accepted answer: http://stackoverflow.com/a/49118076
tagged with: python
has comment: http://stackoverflow.com/comment/85261934
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85214787
linked to: http://stackoverflow.com/q/2219604
has comment: http://stackoverflow.com/comment/85212852
has title: How to use shared memory in python and C/C++
has comment: http://stackoverflow.com/comment/85214700
downvote count: 1
upvote count: 23
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/85214219
has comment: http://stackoverflow.com/comment/85214431
has comment: http://stackoverflow.com/comment/85241506
score: 22
possible better answer: http://stackoverflow.com/a/65164890
answer count: 2
has comment: http://stackoverflow.com/comment/85220623
has answer: http://stackoverflow.com/a/65164890
favorite count: 0
tagged with: synchronization

http://stackoverflow.com/comment/85122191
type: Comment
has text: @DeliriousLettuce Thank you for the answer I'll give it a try, and if it doesn't work I'll manually do it as ividito suggested
type: QuestionComment
comment on: http://stackoverflow.com/q/49058313
score: 0

http://stackoverflow.com/q/49009656
has answer: http://stackoverflow.com/a/49009675
has comment: http://stackoverflow.com/comment/85023908
score: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85024893
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85024425
has answer: http://stackoverflow.com/a/49010149
has comment: http://stackoverflow.com/comment/85024663
tagged with: python-unicode
type: Question
answer count: 2
has body: I want to iterate through a text file and print the occurrence of unicode. In the place of range I want a suitable function. counter = {} x={'0x0985':1,'0x0986':2,'0x0987':3,'0x0988':4,'0x0989':5} for key,value in x.items(): x[key]=0 with open('bengali.txt', 'r', encoding='utf-8') as infile: for line in infile: for char in line: n = ord(char) if n in range{0x0985,0x0986,0x0987,0x0988,0x0989} counter[n] += 1 for key, value in counter.items(): print(chr(key), value)
has title: alternative function for range() in python
downvote count: 0
has comment: http://stackoverflow.com/comment/85024535

http://stackoverflow.com/a/48984363
upvote count: 3
downvote count: 0
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/84975193
has body: You need to unpack the list elements when passing as arguments. You can use the splat (*) operator: my_function(*cust_path) otherwise, when you do my_function(cust_path), it is passing the whole list as argument; so, args will be a one element tuple containing the list i.e. args will be ([&lt;cust_path_elements ...&gt;],).
answers question: http://stackoverflow.com/q/48984319

http://stackoverflow.com/comment/85214739
comment on: http://stackoverflow.com/q/49097306
has text: Seems like it might be related, but it only happens when I un-tar using Python, never when I do using the terminal
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49049136
has title: How do i implement code that changes the values in the GUI according to what the user clicks?
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
downvote count: 1
type: Question
has body: The below program is supposed to be a stock management system. from tkinter import* from tkinter import Tk, StringVar, ttk #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# import random import datetime import time; #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# start = Tk() start.geometry("100x600+0+0") start.title ("R.E.D Inventory Control System") #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# Heading = Frame(start, width = 1000, height = 100, bd = 10, relief = 'raise') Heading.pack(side = TOP) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# LowerHeading = Frame(start, width = 500, height = 100, bd = 20, relief = 'raise') LowerHeading.pack(side = BOTTOM) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# LMiddle = Frame(start, width = 500, height = 1000, bd = 12, relief = 'raise') LMiddle.pack(side = LEFT) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# RMiddle = Frame(start, width = 500, height = 1000, bd = 12, relief = 'raise') RMiddle.pack(side=RIGHT) #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# Title = Label(Heading, font=('arial',40,'bold…
score: -1
has answer: http://stackoverflow.com/a/49051395
upvote count: 0
accepted answer: http://stackoverflow.com/a/49051395
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84968902
has text: Yes. This would also work, but would call `np.vectorize` each time you call `f`. In my case the vectorzing is only done once at instantiation.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48981622
score: 1

http://stackoverflow.com/comment/84948229
score: 0
has text: @doyz - do you need remove all groups by `driverRef` if at least one non NaN in `clear lap?` column per group ? What is expected output?
type: QuestionComment
comment on: http://stackoverflow.com/q/48971488
type: Comment

http://stackoverflow.com/comment/86004760
has text: Well, that was a good guess anyway, I've had to do that before when using matplotlib. I gave it a whirl here but still no joy.
type: AnswerComment
comment on: http://stackoverflow.com/a/49043058
score: 0
type: Comment

http://stackoverflow.com/q/49010375
tagged with: python-3.x
answer count: 5
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49010830
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49010472
has answer: http://stackoverflow.com/a/49010495
downvote count: 1
has body: I got something like this: &gt; d1 = {'System tests': {'failed': 5, 'passed': 0, 'total': 5}, 'Func tests': {'failed': 5, 'passed': 0, 'total': 5}} &gt; d2 = {'System tests': {'failed': 1, 'passed': 1, 'total': 2}, 'Func tests': {'failed': 3, 'passed': 2, 'total': 5}} &gt; d3 = {'System tests': {'failed': 0, 'passed': 0, 'total': 0}, 'Func tests': {'failed': 1, 'passed': 0, 'total': 1}} I would like to sum values 'failed', passed and total into one dictionary so the output should be like this: d4 = {'System tests': {'failed': 6, 'passed': 1, 'total': 7}, 'Func tests': {'failed': 9, 'passed': 2, 'total': 11} What is the easiest solution to do such thing? I can use basic libraries, except collections. The solution must be generic, for example if some other dictionaries would appear in the future
has answer: http://stackoverflow.com/a/49011853
has title: Summing values in dictionary of dictionaries
type: Question
score: 3
tagged with: sum
possible better answer: http://stackoverflow.com/a/49010495
accepted answer: http://stackoverflow.com/a/49010830
upvote count: 4
has comment: http://stackoverflow.com/comment/85025262
has answer: http://stackoverflow.com/a/49010837
favorite count: 0

http://stackoverflow.com/q/49082424
score: 2
type: Question
upvote count: 2
tagged with: sql-server
has comment: http://stackoverflow.com/comment/85171571
tagged with: sqlite
tagged with: python
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I have a sql server data base and in memory sqlite table, how can I inner join between these DB using python?! The number of records is too much, and i don't want to keep this data in my codes
has title: how to inner join from different databases SQL server and Sqlite in python?
has comment: http://stackoverflow.com/comment/85170318

http://stackoverflow.com/comment/85161392
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49077658
has text: Is there always going to only be one cow with the highest yield?
score: 0

http://stackoverflow.com/comment/133521983
has text: Updated references for [`__setitem__`](https://github.com/pandas-dev/pandas/blob/main/pandas/core/frame.py#L3945) and [`_chec_setitem_copy`](https://github.com/pandas-dev/pandas/blob/main/pandas/core/generic.py#L4167)
comment on: http://stackoverflow.com/a/55818159
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49099216
answers question: http://stackoverflow.com/q/49099147
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49099147
has comment: http://stackoverflow.com/comment/85204308
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85204205
type: Answer
has body: Your instructor is right about a tuple being immutable but your "tuple" is actually a list (with square brackets). &gt;&gt;&gt; tuple1 = [3, 4, 5, 6] &gt;&gt;&gt; type(tuple1) &lt;class 'list'&gt; &gt;&gt;&gt; tuple1 = (3, 4, 5, 6) &gt;&gt;&gt; type(tuple1) &lt;class 'tuple'&gt; &gt;&gt;&gt; tuple1[1] = 44 Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment The other problem is that you are trying to get an item from the built-in list not an actual list. &gt;&gt;&gt; my_list = [1, 2, 3, 4] &gt;&gt;&gt; my_list[3] = 66 &gt;&gt;&gt; my_list [1, 2, 3, 66] &gt;&gt;&gt; type(list) &lt;class 'type'&gt; &gt;&gt;&gt; list[3] Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: 'type' object is not subscriptable

http://stackoverflow.com/q/49045372
tagged with: median
score: 0
has answer: http://stackoverflow.com/a/49045510
answer count: 1
has comment: http://stackoverflow.com/comment/85097509
has title: How to correctly calculate the MEDIAN of a probability function?
has comment: http://stackoverflow.com/comment/85097573
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85098007
has comment: http://stackoverflow.com/comment/85096203
type: Question
linked to: http://stackoverflow.com/q/20626994
tagged with: probability-distribution
has body: I am trying to calculate the exact median of a simple standard normal PDF in Python 36. The code looks like this: from scipy.stats import norm from pynverse import inversefunc mean = 'some_number' standard_deviation = 1 inverse_normal_pdf = inversefunc(lambda x: norm.pdf(x, mean, standard_deviation)) median = inverse_normal_pdf(norm.pdf(float('-inf'), mean, standard_deviation)+.5) I use the pynverse library to get the inverse of the normal PDF and use the solver for upper limit of integration from here to arrive to the solution for the median. But this method works for only means in the range [-8.6:11.2], and any other mean outside this range gives me exactly the number 2.6180339603380443 for some reason. I can't figure out what's happening here? What is this number?
tagged with: statistics

http://stackoverflow.com/comment/108143633
type: Comment
comment on: http://stackoverflow.com/a/52703195
score: 0
type: AnswerComment
has text: This worked for me when I had to reconnect, though, it's not clear to me why.

http://stackoverflow.com/a/48976915
score: 2
accepted answer of: http://stackoverflow.com/q/48976415
has body: I think you need s=df.set_index(['id','word_idx'])['word_count'].unstack(fill_value=0).reindex(columns=np.arange(2000),fill_value=0) Then we convert to tuple ot list s.apply(tuple,1) Out[342]: id 307 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... 15213 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... dtype: object
answers question: http://stackoverflow.com/q/48976415
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/49001663
has body: Use pandas. This is right up its alley import numpy as np import pandas as pd A = np.array([[1,2,3], [4,5,6], [7,8,9], [-1,-2,-3]]) M = np.array([[1], [1], [1], [0]]) dfa = pd.DataFrame(A) dfm = pd.DataFrame(M) seriesm = (pd.Series(dfm[dfm.columns[0]]) != 0) matrixYouWant = dfa[seriesm.values] If you want it back to a numpy array: yourNewArray = matrixYouWant.values
type: Answer
answers question: http://stackoverflow.com/q/49001497
has comment: http://stackoverflow.com/comment/85008376
has comment: http://stackoverflow.com/comment/85008366
score: 0

http://stackoverflow.com/comment/85095871
type: Comment
type: QuestionComment
has text: kitman0804 they are not in the source code of the main page, but whenever you load the page with the certain domain name, they should be in the source code.
comment on: http://stackoverflow.com/q/49040735
score: 0

http://stackoverflow.com/comment/86876412
type: AnswerComment
has text: Thank you. Are the loops with numba as fast as in C?
score: 0
comment on: http://stackoverflow.com/a/49050599
type: Comment

http://stackoverflow.com/comment/85167208
comment on: http://stackoverflow.com/q/49080744
type: Comment
score: 0
type: QuestionComment
has text: What do you mean `driver.refresh()`?

http://stackoverflow.com/q/49038190
type: UnansweredQuestion
has body: I am new, so excuse my ignorance if I ask something wrong please. I need to search a workbook to find a string, then I need to get my cell value from the cell directly below that string. When I have found the value, I want to take it and change the filename of the .xls to retain the first three letters of the filename and append the found value on to it. It could be anywhere in the sheet, there are no headers, it is more like a form. Any help is appreciated, I can't seem to find an answer to this. What I have tried is below for finding the cell value of the string I searched for. I just can't pull the data in the cell below. I have thousands of these files to look through and 2 possible strings, although I have not gotten that far along in my python code yet: import os from xlrd import open_workbook path = "a_path" for filename in os.listdir(path): book = open_workbook("some_workbook") for sheet in book.sheets(): for rowidx in range(sheet.nrows): row = sheet.row(rowidx) for colidx, cell in enumerate(row): if cell.value == "String" : print (sheet.name) print (colidx) print (rowidx) print (cell.value) New code. I am further along, but I cannot find a way to limit the columns now that I have gotten to the next row. import os import re import xlrd def rename_excel_files(): path = filename for filename in os.listdir(path): try: book = xlrd.open_workbook(path + filename) except: pass try: sheet = book.sheet_by_index(0) for rowidx in range(sheet.nrows): row = sheet.row(rowidx) for colidx, cell in enumerate(row): m = re.search(r' string ', str(cell.value)) if m: nextrow = sheet.row(rowidx + 1) for i, cell2 in enumerate(nextrow): newfileERnbr = (str(cell2.value).split('.')[0]) print (filename + newfileERnbr) except: pass rename_excel_files()
tagged with: python
tagged with: excel
type: Question
score: 0
tagged with: xlrd
answer count: 1
has title: read an excel sheet with xlrd and find a cell value below the string you search for
has answer: http://stackoverflow.com/a/49256584

app-engine-ndb
tags question: http://stackoverflow.com/q/49098476
tags question: http://stackoverflow.com/q/49015547
tag name: app-engine-ndb
tags question: http://stackoverflow.com/q/48985477
tags question: http://stackoverflow.com/q/49023913
type: Tag
tags question: http://stackoverflow.com/q/49062025

http://stackoverflow.com/q/48995936
type: UnansweredQuestion
has title: Writing points to influxDB using python client, throws error due to missing fields
tagged with: python
has answer: http://stackoverflow.com/a/49029762
tagged with: influxdb
type: Question
has body: I am trying to write points to an influxDB TSDB, but during the write it give an error: File "/home/lab/prometheus-clients-env/lib/python3.5/site-packages/influxdb/client.py", line 271, in request raise InfluxDBClientError(response.content, response.status_code) influxdb.exceptions.InfluxDBClientError: 400: {"error":"partial write: unable to parse 'Cisco-IOS-XR-cdp-oper-cdp,address-type=ipv4,capabilities=R,device-id=ASR9006-LER1,duplex=cdp-dplx-full,interface-name=TenGigE0/0/0/0,ipv4-address=100.8.44.1,node-name=0/0/CPU0,platform=cisco\\ ASR9K\\ Series,port-id=TenGigE0/1/0/7,receiving-interface-name=TenGigE0/0/0/0,system-name=ASR9006-LER1,version=Cisco\\ IOS\\ XR\\ Software\\,\\ Version\\ 6.2.3[Default]': missing fields\nunable to parse 'Cisco-IOS-XR-cdp-oper-cdp,address-type=ipv4,capabilities=R,device-id=ASR9006-LER1,duplex=cdp-dplx-full,interface-name=TenGigE0/0/0/2,ipv4-address=100.8.44.1,node-name=0/0/CPU0,platform=cisco\\ ASR9K\\ Series,port-id=TenGigE0/1/0/8,receiving-interface-name=TenGigE0/0/0/2,system-name=ASR9006-LER1,version=Cisco\\ IOS\\ XR\\ Software\\,\\ Version\\ 6.2.3[Default]': missing fields\nunable to parse 'Cisco-IOS-XR-cdp-oper-cdp,address-type=ipv4,capabilities=R,device-id=ASR9006-LER1,duplex=cdp-dplx-full,interface-name=TenGigE0/0/0/3,ipv4-address=100.8.44.1,node-name=0/0/CPU0,platform=cisco\\ ASR9K\\ Series,port-id=TenGigE0/1/0/9,receiving-interface-name=TenGigE0/0/0/3,system-name=ASR9006-LER1,version=Cisco\\ IOS\\ XR\\ Software\\,\\ Version\\ 6.2.3[Default]': missing fields\nunable to parse 'Cisco-IOS-XR-cdp-oper-cdp,address-type=ipv4,capabilities=R,device-id=ASR9006-LER1,duplex=cdp-dplx-full,interface-name=TenGigE0/0/0/4,ipv4-address=100.8.44.1,node-name=0/0/CPU0,platform=cisco\\ ASR9K\\ Series,port-id=TenGigE0/1/0/11,receiving-interface-name=TenGigE0/0/0/4,system-name=ASR9006-LER1,version=Cisco\\ IOS\\ XR\\ Software\\,\\ Version\\ 6.2.3[Default]': missing fields\nunable to parse 'Cisco-IOS-XR-cdp-oper-cdp,address-type=ipv4,capabilities=R,d…
score: 0
answer count: 1
tagged with: influxdb-python
tagged with: python-3.x

http://stackoverflow.com/q/49034111
has answer: http://stackoverflow.com/a/49041522
accepted answer: http://stackoverflow.com/a/49041522
has comment: http://stackoverflow.com/comment/85076892
tagged with: python
favorite count: 0
tagged with: python-3.x
has title: Using decorator in class method and populate variable
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/49034926
downvote count: 0
has answer: http://stackoverflow.com/a/49034926
linked to: http://stackoverflow.com/q/11058686
linked to: http://stackoverflow.com/q/37832228
has body: I'm writing some code and I have a dictionary where the key is any string, and the value is a function. I then loop through each key in the dictionary and call the functions, like so: class SomeClass: dictionary = {} # Not sure how to use this decorator function def decorator(key): def wrapper(funct): self.dictionary[key] = funct return funct return wrapper @decorator("some_val1") def function_1(self): ... @decorator("some_val2") def function_2(self): ... @decorator("some_val3") def function_3(self): ... def execute_all_functions(self): for key, _ in self.dictionary.items(): self.dictionary[key]() if __name__ == "__main__": sclass = SomeClass() sclass.execute_all_functions() So this should populate dictionary with: { "some_val1": function_1(), "some_val2": function_2(), "some_val3": function_3() } I'm getting this error though self.dictionary[key] = funct NameError: name 'self' is not defined How would I be able to do this. Help appreciated.
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/a/54356575
has comment: http://stackoverflow.com/comment/122322128
type: Answer
has body: I found that the default behaviour of Retries did not apply to POST. To do so required the addition of method_whitelist, e.g. below: def retry_session(retries=5): session = Session() retries = Retry(total=retries, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504], method_whitelist=frozenset(['GET', 'POST'])) session.mount('https://', HTTPAdapter(max_retries=retries)) session.mount('http://', HTTPAdapter(max_retries=retries)) return session
has comment: http://stackoverflow.com/comment/97865012
score: 14
upvote count: 14
answers question: http://stackoverflow.com/q/49121365
downvote count: 0

http://stackoverflow.com/q/48978803
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84963358
upvote count: 0
has comment: http://stackoverflow.com/comment/84963340
has comment: http://stackoverflow.com/comment/84963550
favorite count: 0
has comment: http://stackoverflow.com/comment/84962793
has comment: http://stackoverflow.com/comment/84963198
has comment: http://stackoverflow.com/comment/84964133
tagged with: datetime
answer count: 1
tagged with: python
has title: time series - calculating the daily average without 29.02 in python
downvote count: 1
has answer: http://stackoverflow.com/a/48979034
type: AnsweredQuestion
score: -1
has body: the problem is about the daily average. I have list of rainfall(mm) as below, Y = [ 22, 29, 4, 7, 10, 3, ...] and X is the time series , X= [datetime.date(1991, 1, 1), datetime.date(1991, 1, 2), datetime.date(1991, 1, 3), ... datetime.date(2017, 12, 13), datetime.date(2017, 12, 14), datetime.date(2017, 12, 15),] the length of X and Y is same. I could used it to plot it enter image description here I want to calculate the daily average in list but skip the day 29.02 in every leap year (so the length of average list is 365), and also consider incomplete year (for example in this question there are only 11 months and 15 days in 2017), so the new list (assume Z) would looks like this Z = [ 28, 19, ... 20] and len(Z) = 365 Is anyone have a clever way to solve this question? The ways I tried are always lengthy and stupid. Thank you from the bottom of my heart in advance.
accepted answer: http://stackoverflow.com/a/48979034

http://stackoverflow.com/q/48973632
tagged with: python
has comment: http://stackoverflow.com/comment/84953210
linked to: http://stackoverflow.com/q/45665217
has answer: http://stackoverflow.com/a/48973936
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/84952107
tagged with: time-series
answer count: 2
score: 4
tagged with: pandas
has body: I just started exploring time-series. I have such df Volume Year Month 718394219 2013 01 763723622 2014 01 762225057 2015 01 787479774 2016 01 845614054 2017 01 I want to predict the Volume for 2018. The accuracy of the forecast don't need to be high, as I just want to understand the basics. I made such method, that plots my moving average function along with actual data def plotMovingAverage(series, n): """ series - dataframe with timeseries n - rolling window size """ rolling_mean = series.rolling(window=n).mean() #rolling_std = series.rolling(window=n).std() #upper_bond = rolling_mean+1.96*rolling_std #lower_bond = rolling_mean-1.96*rolling_std plt.figure(figsize=(15,5)) plt.title("Moving average\n window size = {}".format(n)) plt.plot(rolling_mean, "g", label="Rolling mean trend") #plt.plot(upper_bond, "r--", label="Upper Bond / Lower Bond") #plt.plot(lower_bond, "r--") plt.plot(series[n:], label="Actual values") plt.legend(loc="upper left") plt.grid(True) But, I didn't get how can I predict value for the t+1 Same question for exponential smoothing def exponential_smoothing(series, alpha): result = [series[0]] # first value is same as series for n in range(1, len(series)): result.append(alpha * series[n] + (1 - alpha) * result[n-1]) return result
downvote count: 0
has answer: http://stackoverflow.com/a/48973958
favorite count: 0
has title: How can I predict next value using moving average/rolling mean
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84952727

http://stackoverflow.com/q/49012118
upvote count: 1
downvote count: 0
has body: In the following code I have written 2 methods that theoretically(in my mind) should do the same thing. Unfortunately they don't, I am unable to find out why they don't do the same thing per the numpy documentation. import numpy as np dW = np.zeros((20, 10)) y = [1 for _ in range(100)] X = np.ones((100, 20)) # =================== # Method 1 (works!) # =================== for i in range(len(y)): dW[:, y[i]] -= X[i] # =================== # Method 2 (does not work) # =================== dW[:, y] -= X.T
favorite count: 0
has answer: http://stackoverflow.com/a/49012415
has answer: http://stackoverflow.com/a/49012510
accepted answer: http://stackoverflow.com/a/49012510
tagged with: python
possible better answer: http://stackoverflow.com/a/49012623
has answer: http://stackoverflow.com/a/49029000
answer count: 4
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49012623
linked to: http://stackoverflow.com/q/49003798
type: Question
tagged with: numpy
has title: Numpy ":" operator broadcasting issues
tagged with: array-broadcasting

http://stackoverflow.com/comment/84983651
type: QuestionComment
comment on: http://stackoverflow.com/q/48984035
has text: Hey mate.i setup python on xampp as per the above steps and worked fine.could you tell me the correct way to write the exec () statement..and should I use exec () or shell_exec ()..which is suited for windows
score: 0
type: Comment

http://stackoverflow.com/comment/85071652
score: 0
type: Comment
has text: I have been trying to figure out isue for 3 day.. it is easy to judge people. tnx any way. @DeepSpace
type: QuestionComment
comment on: http://stackoverflow.com/q/49032610

http://stackoverflow.com/comment/85083014
has text: @PatrickArtner Why is it needed? I mentioned that in my comment above. It's not *needed* when the input CSV is simple, in the same way that specifying the file encoding is not *needed* when CSV matches your computer configuration's default encoding. But writing it anyway will not break anything, will make the implicit explicit ([PEP 20](https://www.python.org/dev/peps/pep-0020/)) and will generally allow the `csv` module to play out its potential. So I've made a habit out of not being picky and always write those attributes when working with CSV or text.
type: AnswerComment
comment on: http://stackoverflow.com/a/49038229
type: Comment
score: 1

http://stackoverflow.com/a/49059974
has comment: http://stackoverflow.com/comment/85125331
score: 1
has comment: http://stackoverflow.com/comment/85125214
has comment: http://stackoverflow.com/comment/85125255
upvote count: 1
answers question: http://stackoverflow.com/q/49059917
has body: Assigning to the variable doesn't update the list, it's just a temporary reference to the value that's in the array. Use enumerate to get the list index, then you can replace it with the result. for index, arr in enumerate(myList): myList[index] = np.column_stack([arr,5*arr[:,2]-arr[:,1])]) Also, avoid using the names of built-in classes and functions as your own variable names. list is a standard class.
has comment: http://stackoverflow.com/comment/85125173
has comment: http://stackoverflow.com/comment/85125308
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85125321

http://stackoverflow.com/comment/85065288
score: 0
comment on: http://stackoverflow.com/q/49030196
type: Comment
type: QuestionComment
has text: The data is definitely sent if I send it once. This is confirmed by reading the port and seeing the parts it controls move.

http://stackoverflow.com/comment/85190194
type: Comment
comment on: http://stackoverflow.com/a/49092183
score: 0
type: AnswerComment
has text: Okay, it'll only append `Customer`'s to `CustomerList` now.

http://stackoverflow.com/q/48997698
has answer: http://stackoverflow.com/a/48998049
tagged with: python
has comment: http://stackoverflow.com/comment/85001504
linked to: http://stackoverflow.com/q/37878946
answer count: 4
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48998872
has title: Index a NumPy array row-wise
has comment: http://stackoverflow.com/comment/85001630
has body: Say I have a NumPy array: &gt;&gt;&gt; X = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) &gt;&gt;&gt; X array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) and an array of indexes that I want to select for each row: &gt;&gt;&gt; ixs = np.array([[1, 3], [0, 1], [1, 2]]) &gt;&gt;&gt; ixs array([[1, 3], [0, 1], [1, 2]]) How do I index the array X so that for every row in X I select the two indices specified in ixs? So for this case, I want to select element 1 and 3 for the first row, element 0 and 1 for the second row, and so on. The output should be: array([[2, 4], [5, 6], [10, 11]]) A slow solution would be something like this: output = np.array([row[ix] for row, ix in zip(X, ixs)]) however this can get kinda slow for extremely long arrays. Is there a faster way to do this without a loop using NumPy? EDIT: Some very approximate speed tests on a 2.5K * 1M array with 2K wide ixs (10GB): np.array([row[ix] for row, ix in zip(X, ixs)]) 0.16s X[np.arange(len(ixs)), ixs.T].T 0.175s X.take(idx+np.arange(0, X.shape[0]*X.shape[1], X.shape[1])[:,None]) 33s np.fromiter((X[i, j] for i, row in enumerate(ixs) for j in row), dtype=X.dtype).reshape(ixs.shape) 2.4s
duplicate of: http://stackoverflow.com/q/37878946
type: Question
tagged with: numpy
score: 5
has answer: http://stackoverflow.com/a/48997870
upvote count: 5
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/85001169
tagged with: optimization
has comment: http://stackoverflow.com/comment/85002427
has comment: http://stackoverflow.com/comment/85001174
favorite count: 0
has answer: http://stackoverflow.com/a/48997926
accepted answer: http://stackoverflow.com/a/48997870
possible better answer: http://stackoverflow.com/a/48998049

http://stackoverflow.com/q/49107867
has comment: http://stackoverflow.com/comment/85220852
favorite count: 0
score: 0
linked to: http://stackoverflow.com/q/6681743
answer count: 3
has comment: http://stackoverflow.com/comment/85224137
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85224212
tagged with: floating-point
upvote count: 1
has comment: http://stackoverflow.com/comment/85224239
has answer: http://stackoverflow.com/a/49108108
downvote count: 1
type: Question
has body: So now I have a variable which is x = 1001.0010101 From this x, I wanna separate into two parts: x = 1001.0010101 val_int = int(x) #get val_int = 1001 val_fract = {0:.5f}".format(a - val_int) #get val_fract = 0.00101 Is it possible to use for loop to iterate the val_fract to be like: (ignore the int part and decimal point) 0 0 1 0 1 I have tried so many times and I couldn't get it done and the system told me Traceback (most recent call last): File "python", line 46, in &lt;module&gt; TypeError: 'float' object is not iterable Thanks for your help, much appreciated.
has title: How to iterate a float in Python 3?
has comment: http://stackoverflow.com/comment/85220653
tagged with: for-loop
has answer: http://stackoverflow.com/a/49108085
has answer: http://stackoverflow.com/a/49108088
has comment: http://stackoverflow.com/comment/85220921

http://stackoverflow.com/a/49079738
score: 0
answers question: http://stackoverflow.com/q/49079691
type: Answer
upvote count: 1
downvote count: 1
has body: You can use collections.defaultdict to create a better mapping of the occurrences of each each value item in intervals: from collections import defaultdict d = defaultdict(list) intervals = [[0,30], [20,55], [45,80], [75,100]] values = [25, 51, 53, 83, 91] for i in values: for c, h in enumerate(intervals): if i &gt;= h[0] and i &lt;= h[-1]: d[c].append(i) final_result = [b for a, b in d.items()] Output: [[25], [25, 51, 53], [51, 53], [83, 91]]

http://stackoverflow.com/comment/85415157
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49036565
has text: Got it. I haven't tested this in production yet, but to handle my .get() hanging problem, I put `.get(timeout=x)` in a `try` and on `except` I execv (i.e. restart the execution of the script that's adding tasks). This appears to work since, interestingly, when my program hangs on `.get()`, restarting the workers _doesn't_ get tasks executing again, but restarting the script that's adding tasks to the queue/calling `.get()` _does_. Does knowing this reveal anything to you about the underlying issue? I agree, it's a terrible hack and makes me feel icky.

http://stackoverflow.com/a/48975752
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84956658
type: Answer
has body: Your problem seems two-fold to me. There is one problem of selenium not being able to find the element and then there's the problem of Safari not being able to search even the most basic elements. For the first problem, I suggest you use the lower level elements of the '_uX kno-fb-ctx' element such as the '_XWk' element or '_Tfc _j0k'. They work succesfully. As for the problem with Safari, you can use Chrome or Firefox. You might have to download the geckodriver for Firefox. And I suggest you use Beautiful Soup if all you want it to do is scrape text from websites. It's faster and is less prone to such technical bugs and is much more precise.
answers question: http://stackoverflow.com/q/48975560
accepted answer of: http://stackoverflow.com/q/48975560
has comment: http://stackoverflow.com/comment/84979788

http://stackoverflow.com/comment/85048296
type: AnswerComment
type: Comment
score: 1
has text: @JulianKurz updated the answer. I totally did not read your question close enough. What SteveJ said about pycurl also looks interesting as a nicer alternative to executing curl without invoking an external process.
comment on: http://stackoverflow.com/a/49018924

http://stackoverflow.com/comment/85138843
type: Comment
comment on: http://stackoverflow.com/a/49065965
type: AnswerComment
score: 0
has text: I have updated the question. full_item() we are inserting the data into a table.

http://stackoverflow.com/comment/85052481
has text: Updated snippet to check None
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49023823
type: Comment

http://stackoverflow.com/q/49020555
has comment: http://stackoverflow.com/comment/85046380
has answer: http://stackoverflow.com/a/49020726
has title: Strange background appearance in tkk.Frame
score: 0
linked to: http://stackoverflow.com/q/54079715
answer count: 1
has comment: http://stackoverflow.com/comment/85046609
accepted answer: http://stackoverflow.com/a/49020726
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85046833
type: Question
has body: I discovered an anomaly in tkinter. I have attached my script below to show the anomaly. Running this script, I found on my system (Ubuntu 16.04.03) that the background of the ttk.Frame appears strange. If I move my mouse pointer in and out of the ttk.Frame, the background appearance can change and appear gibberish (e.g. backgrounds from other background windows may appear, strange color patterns may appear,....). After some investigations, I discovered that by replacing background='light purple' with background='white', the anomaly disappears and the ttk.Frame appearance behaves as was defined. That is, the fault was caused by using a background/colorname that tkinter did not recognised. Questions: Does this anomaly occur in a Mac, Windows or other Linux systems? What are the valid background names that tkinter accepts? I was not able to locate it in tkinter's __init__.py or ttk.py. Where can I find them? I think tkinter requires a more robust background name check routine to mitigate this anomaly. Who should I attention this to? Test Script: #!/usr/bin/python3 # -*- coding: utf-8 -*- import tkinter as tk import tkinter.ttk as ttk class App(ttk.Frame): def __init__(self, parent=None, *args, **kwargs): style=ttk.Style() style.configure('App.TFrame', background='light purple') ttk.Frame.__init__(self, parent, style='App.TFrame', borderwidth=10, relief='raised', width=200, height=200) self.parent = parent self.parent.geometry('300x300') if __name__ == '__main__': root = tk.Tk() app = App(root) app.grid(row=0, column=0, sticky='nsew') app.grid_propagate(0) root.mainloop()

http://stackoverflow.com/a/73247014
downvote count: 0
type: Answer
has body: If it's okay for you to use xlwt (seems to only work with old .xls files), you can try something like this: import io from xlwt import Workbook file_excel = io.BytesIO() workbook = Workbook(encoding='utf-8') sheet = workbook.add_sheet('sheet1') sheet.write(0, 0, 'column1') sheet.write(0, 1, 'column2') sheet.write(0, 2, 'column3') sheet.write(1, 0, 'Field11') sheet.write(1, 1, 'Field2') sheet.write(1, 2, 'Field3') workbook.save(file_excel) data = file_excel.getvalue() Source: https://www.programcreek.com/python/example/6932/xlwt.Workbook.
upvote count: 1
answers question: http://stackoverflow.com/q/49073545
score: 1

http://stackoverflow.com/comment/85106660
type: QuestionComment
comment on: http://stackoverflow.com/q/49050166
has text: I've tried to produce sample data frames, while encoutering the probable cause of this issue. Making the transformed X_model again a DataFrame just reindexed the DataFrame. Therefore, my call on some indices is misleading. I think the order of the rows is retained, the rows has simply another "name" now. I figure it out and post a solution afterwards.
score: 0
type: Comment

http://stackoverflow.com/a/49096304
type: Answer
answers question: http://stackoverflow.com/q/49095848
has comment: http://stackoverflow.com/comment/85197508
has body: It doesn't look like the whole page is being downloaded. You can check this with print(page_soup.prettify()). A way around this is to use Selenium to open up a web browser and then download the page: from selenium import webdriver from bs4 import BeautifulSoup as soup driver = webdriver.Firefox(profile) driver.get('http://smartgriddashboard.eirgrid.com/#all/generation') page_soup = soup(driver.page_source, 'html.parser') Note that Selenium needs geckodriver to be installed. I'm sure there's a better way, using Requests or something else. A super simple way is to get the page source by right clicking on your web browser and then getting Beautiful Soup to use that. On a side note, while it works, your findAll seems to be the old method. The new method or CSS selectors are probably better.
score: 0
has comment: http://stackoverflow.com/comment/85207706

http://stackoverflow.com/q/48988336
tagged with: selenium
has body: I try to script some test on an internal website in selenium in python. And this site contains a lot of iframes. I have no issue to switch iframe, but I try to set the url of the current iframe, and I do not find any method to attain this. iframe1 = WebDriverWait (driver, 10).until (EC.presence_of_element_located((By.ID, 'iframe1'))) driver.switch_to_frame (iframe1) iframe2 = WebDriverWait (driver, 10).until (EC.presence_of_element_located((By.ID, 'iframe2'))) driver.switch_to_frame (iframe2) # I was expecting something like this driver.get("/new_url_inside_my_frame.html") But it does not work, at first because get does not works with relative url, but even if I use a complete url, it sets the all the page and not just the iframe. I am pretty sure, this is possible, I just not find how anywhere.
type: Question
has comment: http://stackoverflow.com/comment/84981348
has comment: http://stackoverflow.com/comment/84983833
score: 0
has title: Selenium - python - how to update the url of the current iframe
tagged with: python
has comment: http://stackoverflow.com/comment/84981298
answer count: 0
type: UnansweredQuestion
tagged with: iframe

http://stackoverflow.com/comment/85006552
has text: [How to Create a Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve)
score: 4
comment on: http://stackoverflow.com/q/49000679
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85002015
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48997260
has text: @MegaFirm: I apologize. I've added information on how to update the image.
score: 0

http://stackoverflow.com/a/49115012
type: Answer
score: 6
answers question: http://stackoverflow.com/q/49108836
has body: In your abc() method you can create labels and add them to your layout. In order to do that, I made a few change to your code. I added an id to your GridLayout and changed your custom label class to MyLabel and added it to the py file, so that I could create them in Python. Here is the modified Python file: from kivy.uix.label import Label from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window Window.clearcolor = (0.5, 0.5, 0.5, 1) Window.size = (600, 600) class MyLabel(Label): pass class Invoice(Screen): def __init__(self, **kwargs): super(Invoice, self).__init__(**kwargs) def abc(self): #fetching from database arr = ({'Item1': 5000},{'Item2': 1000}) layout = self.ids['invoices'] for invoice in arr: for key,val in invoice.items(): lab1 = MyLabel(text=str(key),size_hint_x=.35, halign='left' ) lab2 = MyLabel(text=str(val),size_hint_x=.15, halign='right' ) layout.add_widget(lab1) layout.add_widget(lab2) class Test(App): def build(self): self.root = Builder.load_file('test.kv') return self.root And changes to the kv file included changing Label to MyLabel, moving as much as possible to the MyLabel class, and removing your example labels: &lt;Button@Button&gt;: font_size: 15 font_name: 'Verdana' size_hint_y:None height: 30 &lt;MyLabel&gt;: font_size: 15 font_name: 'Verdana' size_hint_y:None height: 30 text_size: self.size valign: 'middle' canvas.before: Color: rgb: .6, .6, .6 Rectangle: pos: self.pos size: self.size Invoice: BoxLayout: orientation: "vertical" padding : 15, 15 BoxLayout: orientation: "vertical" padding : 5, 5 size_hint: .6, None pos_hint: {'x': .18,} BoxLayout: orientation: "horizontal" padding : 5, 5 spacing: 10, 10 size: 800, 40 size_hint: 1, None Button: text: "Show" size_hint_x: .05 spacing_x: 30 on_press:root.abc() BoxLayout: orientation: "horizontal" size_hint: 1, 1 BoxLayout: orientation: "vertical" size_hint: .5, 1 padding : 0, 15 spacing: 10, 10 size: 500, 30 Button: t…
downvote count: 0
upvote count: 6

http://stackoverflow.com/q/48984978
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84975025
score: 2
answer count: 0
upvote count: 3
has title: Python Value Error: The truth value of an array with more than one element is ambiguous
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84974749
has comment: http://stackoverflow.com/comment/84974714
tagged with: mean
has comment: http://stackoverflow.com/comment/84975296
favorite count: 0
has body: I created a dictionary with my data years as keys and every key has a 3D array in the form (time,lat,lon). Now I tried to calculate the time mean with the following code: test_avg=numpy.mean(sorted(d.values())[0],axis=0) I am getting the Error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). When I used test_avg=numpy.mean(list(d.values())[0],axis=0) it worked fine, but then I can't be sure, if it really calculated the mean of the first dictionary key, right? Or is there a possibility to calculate the mean of the first axis in another way? So... can someone help my what this Error want to tell me? I can provide further informations if necessary! EDIT: So an simple example of my input: time lat lon 1 1,2,3 2,3,4 2 5,6,7 6,7,8 3 7,8,9 2,3,4 what I want: lat lon 8.3,5.3,6.3 3.3,4.3,5.3 I hope one can understand what I mean
type: UnansweredQuestion

http://stackoverflow.com/a/49032363
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49031491
accepted answer of: http://stackoverflow.com/q/49031491
has body: PyCharm sets the Python Path at the root of the project (by default). To mimic this in a quick'n'dirty fashion, you just need to do this once in your shell session before invoking python whatever: set PYTHONPATH=C:\Users\usr\PycharmProjects\project
upvote count: 5

http://stackoverflow.com/q/49034536
downvote count: 0
favorite count: 0
has body: I'm trying to following the instructions on https://docs.djangoproject.com/en/2.0/howto/static-files/, but I'm running into unexpected results. I have a Django project with an app dashboard like so: . ├── dashboard │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20180227_2103.py │ │ ├── 0003_auto_20180227_2304.py │ │ └── __init__.py │ ├── models.py │ ├── static │ │ └── dashboard │ │ └── dashboard.js │ ├── templates │ │ └── dashboard │ │ ├── checkin_detail.html │ │ ├── checkin_form.html │ │ └── checkin_list.html │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── manage.py └── my_project ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py In my project's settings.py, the STATIC_URL is as it was created by django-admin startproject: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' The dashboard.js file is a simple test script: alert("Hello, world!"); I'm trying to use the Javascript in the checkin_form.html template like so: {% load static %} &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src={% static "dashboard/dashboard.js" %}&gt;&lt;/script&gt; &lt;form action="" method="post"&gt;{% csrf_token %} {{ form.as_p }} &lt;input type="submit" value="Send message" /&gt; &lt;/form&gt; My views inherit from Django's generic view classes: from django.views import generic from .models import CheckIn class CheckInCreate(generic.CreateView): model = CheckIn fields = '__all__' class CheckInUpdate(generic.UpdateView): model = CheckIn fields = '__all__' However, when I navigate to the URL rendered by that view, I don't see an alert with "Hello, world!". Can someone point out to me what is wrong with this configuration/implementation?
tagged with: django
has title: Loading Javascript in Django using the static template tag
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/85074477
upvote count: 2
has answer: http://stackoverflow.com/a/49035219
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85073903
type: Question
has answer: http://stackoverflow.com/a/57633504
tagged with: javascript
has answer: http://stackoverflow.com/a/49034858
answer count: 3

http://stackoverflow.com/q/49016075
has title: Django WSGI: A server error occurred. How to use wsgi in webapp
type: Question
tagged with: wsgi
has comment: http://stackoverflow.com/comment/85042715
has comment: http://stackoverflow.com/comment/85041812
score: 0
answer count: 1
has body: I am new to Django, and trying to create a web app use Django and wsgi to generate a server. But I got some error and misunderstanding about Django. Here is the code of my wsgi.py : from django.shortcuts import render import urllib import urllib2 from urllib2 import urlopen import json from wsgiref.simple_server import make_server from django.http import HttpResponse def map(request): return render(request,'WebPage1.html') def searchMap(request): address =request.POST['city'] return render(request,'WebPage1.html',{'Address':address}) def routers(): urlpatterns = ( ('/map',map), ('/searchMap',searchMap) ) return urlpatterns def application(environ, start_response): print(environ['PATH_INFO']) path=environ['PATH_INFO'] status = '200 OK' response_headers = [('Content-Type', 'text/plain')] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == path: func = item[1] break if func: return func(environ) else: return ["Hello World".encode("utf-8")] httpd = make_server('', 8080, application) print('Serving HTTP on port 8080...') httpd.serve_forever() And my html: Simple Map {% csrf_token %} {{Address}} And the error message I get when I get to http://127.0.0.1:8080/map: Exception happened during processing of request from ('127.0.0.1', 54038) Traceback (most recent call last): File "C:\Python27\Lib\SocketServer.py", line 290, in _handle_request_noblock self.process_request(request, client_address) File "C:\Python27\Lib\SocketServer.py", line 318, in process_request self.finish_request(request, client_address) File "C:\Python27\Lib\SocketServer.py", line 331, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python27\Lib\SocketServer.py", line 652, in __init__ self.handle() File "C:\Python27\Lib\wsgiref\simple_server.py", line 131, in handle handler.run(self.server.get_app()) File "C:\Python27\Lib\wsgiref\handlers.py", line 92, in run self.close() File "C:\Python27\Lib\wsgiref\simple_server.py", line 33, in close self.status…
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49016363

http://stackoverflow.com/a/71036686
answers question: http://stackoverflow.com/q/49082093
score: 0
type: Answer
has body: Use regexp_match() from SQLAlchemy 1.4: It works on Integer type columns as well.

http://stackoverflow.com/comment/85021854
comment on: http://stackoverflow.com/q/49003440
type: QuestionComment
has text: i have called the dump function at the end of my code
score: 0
type: Comment

http://stackoverflow.com/a/48976135
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48976028
answers question: http://stackoverflow.com/q/48976028
has body: You can use np.random.choice to sample a vector import numpy as np n=100 vec=np.random.choice([-1,1],n) mat=np.diag(vec)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49007680
tagged with: python
linked to: http://stackoverflow.com/q/21415661
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85021199
accepted answer: http://stackoverflow.com/a/49007782
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85020010
possible better answer: http://stackoverflow.com/a/49007884
has answer: http://stackoverflow.com/a/49007884
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/85019886
has body: maybe someone could show me what i am doing wrong? import pandas as pd import operator def calculate(A, B): if (A &gt; 2 and B == True): Z = A * 10 else: Z = A * 10000 return Z df = pd.DataFrame() df['A'] = 1,2,3,4,5 df['B'] = True,True,False,False,True df['C'] = calculate(df.A, df.B) df **Error:** `ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().` Thanks a lot! I couldn't find a solution for my problem on stackoverflow. I am total beginner and started coding today. The Solutions provided by other Questions didn't helped me, sorry for double post.
has answer: http://stackoverflow.com/a/49007782
has title: Python Dataframe: Create New Column Using Logic ----> ValueError: The truth value of a Series is ambiguous
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/48997644
has answer: http://stackoverflow.com/a/48997741
accepted answer: http://stackoverflow.com/a/48997741
tagged with: python
has title: How to describe columns as categorical values?
upvote count: 13
has answer: http://stackoverflow.com/a/74751136
type: AnsweredQuestion
tagged with: describe
possible better answer: http://stackoverflow.com/a/53613242
score: 13
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/53613242
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/85000868
has body: I have a pandas dataframe that contains a mix of categorical and numeric columns. By default, df.describe() returns only a summary of the numerical data (describing those columns with count, mean, std, min, quantiles, max) when iterating through all the columns in the df and describing them individually as [df[c].describe() for c in df.columns] the description is returned based off of specific column dtype; i.e. numerical summary for int and float and categoric summary for object Does any one know of a succinct way of describing all columns as categorical with count, unique, top, freq?
downvote count: 0
has comment: http://stackoverflow.com/comment/85000770
favorite count: 0

http://stackoverflow.com/q/49006224
tagged with: python
tagged with: tls1.2
has title: Do Python 3.6 and Requests Module conform to RFC 6125 for wildcard reference identifiers?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49007756
tagged with: python-requests
has body: I am trying to ascertain whether Python's request module conforms to RFC 6125 or not. I created a Root CA Certificate and added it to my Linux's Trust Store. I then created a Server certificate and signed it with my Root CA Certificate and put the common name as "*.com". Then I started a server using OpenSSL's s_server using the Server Certificate. Now as per RFC 6125 and this question, my python client should not establish a TLS connection if i try to connect with "foo.com". However, the Python client does not fail here and establishes a connection. I am executing this command in the terminal: python -c "import requests; print(requests.get('https://foo.com', verify='/etc/ssl/certs/ca-certificates.crt'));" But, if i try to connect with "bar.foo.com", i get the expected error: requests.exceptions.SSLError: HTTPSConnectionPool(host='bar.foo.com', port=443): Max retries exceeded with url: / (Caused by SSLError(CertificateError("hostname 'bar.foo.com' doesn't match '*.com'",),)) In my opinion, this is a very trivial thing that should not happen. So is there something wrong in my approach or does the Requests Module actually not fail in this scenario? Looking forward to your help guys! Thanks!
type: Question
tagged with: ssl
score: 4
linked to: http://stackoverflow.com/q/33429453
upvote count: 4
answer count: 1
has answer: http://stackoverflow.com/a/49007756
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/49115430
score: 1
answers question: http://stackoverflow.com/q/49115192
has body: Unless you have a very specific reason for writing your own error handling, you should use the built-in raise_for_status() import requests import json response = requests.get('http://&lt;ip&gt;:5000/loads_list') response.raise_for_status() jData = json.loads(response.text) print(jData) This will hopefully raise an informative error message that you can deal with.
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/49045774
tagged with: unicode
has answer: http://stackoverflow.com/a/55623756
has comment: http://stackoverflow.com/comment/85096025
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49045830
upvote count: 1
type: AnsweredQuestion
has title: Why does Python3 get a UnicodeDecodeError reading a text file where Python2 does not?
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/49045830
answer count: 2
has body: I'm reading in a text file. I've been doing it just fine with python2, but I decided to run my code with python3 instead. My code for reading the text file is: neg_words = [] with open('negative-words.txt', 'r') as f: for word in f: neg_words.append(word) When I run this code on python 3 I get the following error: UnicodeDecodeError Traceback (most recent call last) &lt;ipython-input-14-1e2ff142b4c1&gt; in &lt;module&gt;() 3 pos_words = [] 4 with open('negative-words.txt', 'r') as f: ----&gt; 5 for word in f: 6 neg_words.append(word) 7 with open('positive-words.txt', 'r') as f: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py in decode(self, input, final) 319 # decode input (taking the buffer into account) 320 data = self.buffer + input --&gt; 321 (result, consumed) = self._buffer_decode(data, self.errors, final) 322 # keep undecoded input until the next call 323 self.buffer = data[consumed:] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 3988: invalid continuation byte It seems to me that there is a certain form of text that python2 decodes without any issue, which python3 can't. Could someone please explain what the difference is between python2 and python3 with respect to this error. Why does it occur in one version but not the other? How can I stop it?
downvote count: 0
possible better answer: http://stackoverflow.com/a/55623756

http://stackoverflow.com/comment/85154163
score: 0
has text: The amount of work you are doing for each triple is negligible, and 1007 items is a relatively small list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49074059

http://stackoverflow.com/a/49113818
score: 10
upvote count: 10
downvote count: 0
type: Answer
has body: You can use the urlretrieve to download the file EX: u = "https://publicwww.com/websites/%22google.com%22/?export=csv" import urllib urllib.request.urlretrieve (u, "Ktest.csv")
answers question: http://stackoverflow.com/q/49113616

http://stackoverflow.com/q/48988266
answer count: 4
upvote count: 14
possible better answer: http://stackoverflow.com/a/48989986
has answer: http://stackoverflow.com/a/48989986
has answer: http://stackoverflow.com/a/48988376
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48988342
has answer: http://stackoverflow.com/a/57346726
has comment: http://stackoverflow.com/comment/84984339
type: Question
downvote count: 0
favorite count: 0
has body: This is my first code in python and I have this issue: I'm reading a binary file as: def read_file(file): with open(file, "rb") as f: frame = f.read() print(type(frame)) #out = &lt;class 'bytes'&gt; return frame I need to convert all the vector to int values instead using them as bytes. After printing I get something like this: print(frame[0:10]) b'\xff\xff\xff\xffXabccc' However if I print passing one position only I get this:(the integer values are correct, but I just get them using the function print) print(frame[0]) 255 print(frame[1]) 255 print(frame[2]) 255 print(frame[3]) 255 print(frame[4]) 88 print(frame[5]) 97 print(frame[6]) 98 print(frame[7]) 99 print(frame[8]) 99 print(frame[9]) 99 print(frame[10]) 98 The question is: How can I convert all the positions of my array in one step? I would like to run the code print(frame[0:10]) and get something like [255, 255, 255, 255, 88, 97, 98, 99 ,99, 99, 98]
score: 14
has answer: http://stackoverflow.com/a/48988342
tagged with: python
has title: Convert python byte "array" to int "array

http://stackoverflow.com/q/48980602
type: UnansweredQuestion
tagged with: mqtt
has comment: http://stackoverflow.com/comment/85005297
tagged with: python
has body: I am new guy in use MQTT, when I publish message use qos=1 I could recevice message correct.but when I try to publish message use qos=2 I got nothing.this was my test code ,I try use rabbit mq (MQTT) Subscribe: def MQTT_CONNECTION(): print("IN mqtt connection") client = mqtt.Client() client.username_pw_set(user, pwd) client.connect("localhost", 1883, 60) client.on_connect = on_connect client.on_message = on_message client.subscribe([("TEST", 2)]) MQTT_CLIENT_CONNECTED=True print('in function'+str(stop)) client.loop_forever() except Exception as error: print("ERROR IN MQTT CONNECTION",error) MQTT_CLIENT_CONNECTED=False Publish code: client.publish("TEST",2111,qos=2,retain=True) when the qos set to 1 subscribe code could receive messsage, when I try to change the qos =2 I got nothing Please give me some help . Thanks
answer count: 0
has title: When I try to publish Message use MQTT (QOS=2) can't receive message
type: Question
has comment: http://stackoverflow.com/comment/84990104
score: 0
has comment: http://stackoverflow.com/comment/84979610
tagged with: qos

http://stackoverflow.com/a/49542826
upvote count: 7
has comment: http://stackoverflow.com/comment/86094222
answers question: http://stackoverflow.com/q/49081819
has body: So you can use properties with inheritance? Just an attempt at answering by giving an example: class Base(object): def __init__(self): self._value = 0 @property def value(self): return self._value @value.setter def value(self, val): self._value = val class Child(Base): def __init__(self): super().__init__() self._double = 0 @Base.value.setter def value(self, val): Base.value.fset(self, val) self._double = val * 2 If it was implemented the way you write it, then the Base.value.setter would also set the double, which is not wanted. We want a brand new setter, not to modify the base one. EDIT: as pointed out by @wim, in this particular case, not only it would modify the base setter, but we would also end up with a recursion error. Indeed the child setter would call the base one, which would be modified to call itself with Base.value.fset in an endless recursion.
downvote count: 0
type: Answer
score: 7

http://stackoverflow.com/a/51287002
score: 1
downvote count: 0
has body: Here is a guide on how to export Ethereum data to csv https://medium.com/@medvedev1088/exporting-and-analyzing-ethereum-blockchain-f5353414a94e It uses https://github.com/medvedev1088/ethereum-etl which outputs the data into blocks.csv, transactions.csv, erc20_transfers.csv. blocks.csv Column | Type | ------------------------|--------------------- block_number | bigint | block_hash | hex_string | block_parent_hash | hex_string | block_nonce | hex_string | block_sha3_uncles | hex_string | block_logs_bloom | hex_string | block_transactions_root | hex_string | block_state_root | hex_string | block_miner | hex_string | block_difficulty | bigint | block_total_difficulty | bigint | block_size | bigint | block_extra_data | hex_string | block_gas_limit | bigint | block_gas_used | bigint | block_timestamp | bigint | block_transaction_count | bigint | transactions.csv Column | Type | --------------------|-------------- tx_hash | hex_string | tx_nonce | bigint | tx_block_hash | hex_string | tx_block_number | bigint | tx_index | bigint | tx_from | hex_string | tx_to | hex_string | tx_value | bigint | tx_gas | bigint | tx_gas_price | bigint | tx_input | hex_string | erc20_transfers.csv Column | Type | --------------------|-------------- erc20_token | hex_string | erc20_from | hex_string | erc20_to | hex_string | erc20_value | bigint | erc20_tx_hash | hex_string | erc20_block_number | bigint |
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49080955

http://stackoverflow.com/comment/85153582
type: Comment
comment on: http://stackoverflow.com/a/49062624
score: 0
type: AnswerComment
has text: well done thank you very much. Why does python do it for us? What is the cause?

http://stackoverflow.com/comment/85413162
score: 0
type: AnswerComment
has text: Maybe a subset of the data? And what you would expect as output for that subset? Do you want to also "interpolate" to the edges of that plot? In that case, you aren't really interpolating at all since it isn't some combination of nearby points, it is a model based projection out to some unknown space (extrapolation)
comment on: http://stackoverflow.com/a/49087479
type: Comment

http://stackoverflow.com/q/49038977
answer count: 2
tagged with: function
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85083309
accepted answer: http://stackoverflow.com/a/49039174
tagged with: python
has comment: http://stackoverflow.com/comment/85083388
upvote count: 2
has answer: http://stackoverflow.com/a/49039166
tagged with: parameter-passing
downvote count: 1
has comment: http://stackoverflow.com/comment/85083519
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49039166
has answer: http://stackoverflow.com/a/49039174
score: 1
has body: I have create a function which has an optional argument y on it: def f(x, *y): print(x) if y in locals(): print(y) When passing these x and yarguments to the function it only ouputs x even though y is in the local variables: a = ['String', 'Optional String'] x = a[0] if len(a) == 2: y = a[1] f(x, *y) #Output: String I have a second issue that when giving only the x argument and not the y it ouputs a NameError: a = ['String', 'Optional String'] x = a[0] if len(a) == 2: y = a[1] f(x, *y) #Output: NameError: name 'y' is not defined How can I get this working? Thanks in advance. EDIT: Looks like I misunderstood what an optional argument was. Ended up changing the whole code and its Fixed. These answers helped me anyways, Thank you.
has title: Running a function with a non-existing optional argument
type: Question

import
type: Tag
tags question: http://stackoverflow.com/q/49033015
tags question: http://stackoverflow.com/q/49072154
tags question: http://stackoverflow.com/q/48983246
tags question: http://stackoverflow.com/q/49032045
tag name: import
tags question: http://stackoverflow.com/q/49022306
tags question: http://stackoverflow.com/q/49036628
tags question: http://stackoverflow.com/q/48971175
tags question: http://stackoverflow.com/q/49077128
tags question: http://stackoverflow.com/q/48971427
tags question: http://stackoverflow.com/q/49098039
tags question: http://stackoverflow.com/q/48987634
tags question: http://stackoverflow.com/q/49053434
tags question: http://stackoverflow.com/q/49101504
tags question: http://stackoverflow.com/q/49041602
tags question: http://stackoverflow.com/q/48978765
tags question: http://stackoverflow.com/q/48979233
tags question: http://stackoverflow.com/q/49090441
tags question: http://stackoverflow.com/q/49070016
tags question: http://stackoverflow.com/q/49005629
tags question: http://stackoverflow.com/q/49121286
tags question: http://stackoverflow.com/q/49117163

http://stackoverflow.com/comment/86753465
type: Comment
type: QuestionComment
score: 1
has text: Have you looked at Psychopy (http://www.psychopy.org/). It has support for some Tobii devices, although I am not sure if there is support for Tobii 4C.
comment on: http://stackoverflow.com/q/49011362

http://stackoverflow.com/q/49082862
type: Question
answer count: 2
tagged with: button
has body: i want to create multiple buttons in Tkinter, in a for loop. The problem is that I'm iterating through a dataframe (the values in the rows are the content of the Tkinter gadets I'm creating) with .iterrows which means, I have no "i", only rows and index. The problem is, that as I'm creating the buttons and give them different commands with lambda i:i=SomeFunction(somevariable), and here I have to use a variable other than "i". The result is that the commands are all referring at the end for to the last value of this "somevariable" and not to the value of it as it was at the creation of the button. import tkinter def printout(somevariable): print(somevariable) window = tkinter.Tk() i = 0 somevariable = 0 for index, rows in enumerate(["a","b","c","d"]): b = tkinter.Button(window, text=rows, command= lambda i=i: printout(somevariable)) b.pack() somevariable = somevariable + 1 window.mainloop() And all the buttons are containing as command the very last value of the "somevariable". Any idea how to make this work??
has answer: http://stackoverflow.com/a/49083209
favorite count: 0
tagged with: python-2.7
downvote count: 2
upvote count: 1
duplicate of: http://stackoverflow.com/q/10865116
has answer: http://stackoverflow.com/a/49082989
accepted answer: http://stackoverflow.com/a/49082989
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85170978
has title: Create multiple Tkinter button with different command but external variable
tagged with: python
possible better answer: http://stackoverflow.com/a/49083209
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85170983
linked to: http://stackoverflow.com/q/10865116
score: -1
tagged with: loops

http://stackoverflow.com/comment/85142091
has text: what programming language U use?
comment on: http://stackoverflow.com/q/49068539
score: 0
type: QuestionComment
type: Comment

wsgi
type: Tag
tags question: http://stackoverflow.com/q/49016075
tag name: wsgi

http://stackoverflow.com/a/48998049
has comment: http://stackoverflow.com/comment/85002406
has comment: http://stackoverflow.com/comment/85039812
has comment: http://stackoverflow.com/comment/85002004
has comment: http://stackoverflow.com/comment/85002324
downvote count: 0
has comment: http://stackoverflow.com/comment/85001927
has comment: http://stackoverflow.com/comment/85001967
has comment: http://stackoverflow.com/comment/85002075
has comment: http://stackoverflow.com/comment/85002350
score: 3
type: Answer
answers question: http://stackoverflow.com/q/48997698
has comment: http://stackoverflow.com/comment/85002313
has comment: http://stackoverflow.com/comment/85002052
upvote count: 3
has body: I believe you can use .take thusly: In [185]: X Out[185]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) In [186]: idx Out[186]: array([[1, 3], [0, 1], [1, 2]]) In [187]: X.take(idx + (np.arange(X.shape[0]) * X.shape[1]).reshape(-1, 1)) Out[187]: array([[ 2, 4], [ 5, 6], [10, 11]]) If your array dimensions are massive, it might be faster, albeit uglier, to do: idx+np.arange(0, X.shape[0]*X.shape[1], X.shape[1])[:,None] Just for fun, see how the following performs: np.fromiter((X[i, j] for i, row in enumerate(ixs) for j in row), dtype=X.dtype, count=ixs.size).reshape(ixs.shape) Edit to add timings In [15]: X = np.arange(1000*10000, dtype=np.int32).reshape(1000,-1) In [16]: ixs = np.random.randint(0, 10000, (1000, 2)) In [17]: ixs.sort(axis=1) In [18]: ixs Out[18]: array([[2738, 3511], [3600, 7414], [7426, 9851], ..., [1654, 8252], [2194, 8200], [5497, 8900]]) In [19]: %timeit np.array([row[ix] for row, ix in zip(X, ixs)]) 928 µs ± 23.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [20]: %timeit X[np.arange(len(ixs)), ixs.T].T 23.6 µs ± 491 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [21]: %timeit X.take(idx+np.arange(0, X.shape[0]*X.shape[1], X.shape[1])[:,None]) 20.6 µs ± 530 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [22]: %timeit np.fromiter((X[i, j] for i, row in enumerate(ixs) for j in row), dtype=X.dtype, count=ixs.size).reshape(ixs.shape) 1.42 ms ± 9.94 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) @mxbi I've added some timings and my results aren't really consistent with yours, you should check it out Here's a larger array: In [33]: X = np.arange(10000*100000, dtype=np.int32).reshape(10000,-1) In [34]: ixs = np.random.randint(0, 100000, (10000, 2)) In [35]: ixs.sort(axis=1) In [36]: X.shape Out[36]: (10000, 100000) In [37]: ixs.shape Out[37]: (10000, 2) With some results: In [42]: %timeit np.array([row[ix] for row, ix in zip(X, ixs)]) 11.4 ms ± 177 µs per loop (mean ± std. dev. of 7 runs…

http://stackoverflow.com/a/49049003
has comment: http://stackoverflow.com/comment/98167101
has comment: http://stackoverflow.com/comment/86831404
has comment: http://stackoverflow.com/comment/85299478
type: Answer
has comment: http://stackoverflow.com/comment/92972100
score: 10
has comment: http://stackoverflow.com/comment/87113803
has comment: http://stackoverflow.com/comment/86322901
accepted answer of: http://stackoverflow.com/q/49048734
has body: I have solved this,it seems that MKL 2018 has some serious problems conda uninstall mkl=2018 conda install mkl=2017
answers question: http://stackoverflow.com/q/49048734
upvote count: 10
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49079761
upvote count: 0
type: UnansweredQuestion
has title: How to create a rank matrix with column names instead of values?
tagged with: pandas
has answer: http://stackoverflow.com/a/49079811
tagged with: python
has answer: http://stackoverflow.com/a/49081606
has answer: http://stackoverflow.com/a/49079945
favorite count: 0
score: -1
type: Question
downvote count: 1
has comment: http://stackoverflow.com/comment/85165466
tagged with: dataframe
has answer: http://stackoverflow.com/a/49080087
has body: I am quite new to Python. I have a data frame like the following book 1 book 2 book 3 user 1 0.05 0.47 0.09 user 2 0.3 0.01 0.35 I want it to be ranked based on the values(descending order) and the output to be the following: Rank 1 Rank 2 Rank 3 user1 book 2 book 3 book 1 user2 book 3 book 1 book 2 this is how the matrix looks in real task I would appreciate your help. Thank you.
answer count: 4

http://stackoverflow.com/q/48979352
tagged with: plotly
type: Question
has answer: http://stackoverflow.com/a/50165264
answer count: 2
has answer: http://stackoverflow.com/a/78892771
score: 0
tagged with: choropleth
has title: Choropleth Map in python using plotly without State Codes.
type: UnansweredQuestion
has body: I have the following code to plot a choropleth Map in python. data = [dict( type="choropleth", autocolorscale= True, locations = df[statename], z = df[z].astype(float), locationmode = 'USA-states', text = df[state], marker = dict( line = dict ( color = 'rgb(255,255,255)', width = 2 )), colorbar = dict(title = title) )] layout = dict(title = title, geo=dict(scope="usa",showlakes = True,lakecolor = 'rgb(255, 255, 255)')) iplot(go.Figure(data=data,layout=layout),validate=False) Is it possible to plot the map using just the State Names as input to locations or is it necessary to have the two Letter State Codes. When i use the state codes it works but when i use the state names it just gives me an empty map.
tagged with: python

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/49026578
tags question: http://stackoverflow.com/q/48997100
tags question: http://stackoverflow.com/q/49103066
type: Tag
tags question: http://stackoverflow.com/q/49116579
tags question: http://stackoverflow.com/q/48998371
tags question: http://stackoverflow.com/q/48972115
tags question: http://stackoverflow.com/q/48970768
tags question: http://stackoverflow.com/q/49016494

http://stackoverflow.com/q/48974839
downvote count: 0
tagged with: wxpython
has answer: http://stackoverflow.com/a/48975364
answer count: 3
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48987548
has answer: http://stackoverflow.com/a/48990057
score: 1
tagged with: boa-constructor
has title: Get column number or value in wx.ListControl wxPython
type: Question
has body: How to get column number or value in wx.ListControl wxPython? I want to sort the item by column when I click it. I'm using BoaConstructor IDE. Please help me :)

http://stackoverflow.com/comment/85246465
comment on: http://stackoverflow.com/a/49120201
score: 0
type: Comment
type: AnswerComment
has text: I tried `df_duplicates = df.drop_duplicates(['testtime','responsetime'],keep='first').groupby([''studentid','subj','topic','lesson])`.... but my question is this? Does the `drop_duplicates(['testtime','responsetime'],keep='first')` check to see if testtime had the same value between the row index 1 and 2 & if responsetime had the same value between the row index 1 and 2? I want to only keep one of the values only when both column values are the same between multiple rows.

http://stackoverflow.com/a/49074910
has body: I do not understand the "labels" at all. But a cantor plot is rather easily produced by recursively walking the levels. import numpy as np import matplotlib.pyplot as plt line = [0,1] depth = 5 def divide(line, level=0): plt.plot(line,[level,level], color="k", lw=5, solid_capstyle="butt") if level &lt; depth: s = np.linspace(line[0],line[1],4) divide(s[:2], level+1) divide(s[2:], level+1) divide(line) plt.gca().invert_yaxis() plt.show() Labeling the lines is in this far not straight forward here because the recursive placement of the lines is in a different order than the desired labeling. One solve this by placing a label for each line and later on sort the labels; then giving each the number from the sorted list. import numpy as np import matplotlib.pyplot as plt line = [0,1] depth = 5 labels=[] def divide(line, level=0): plt.plot(line,[level,level], color="k", lw=5, solid_capstyle="butt") label = plt.annotate("",xy=(np.mean(line),level), xytext=(0,5), textcoords="offset points", ha="center", color="crimson") labels.append(label) if level &lt; depth: s = np.linspace(line[0],line[1],4) divide(s[:2], level+1) divide(s[2:], level+1) divide(line) labels.sort(key=lambda x: x.xy[::-1]) for i, label in enumerate(labels): label.set_text(i+1) plt.gca().invert_yaxis() plt.show() Note that the smaller the lines, the less readable the text is. So labeling the lower, small lines makes only sense when zooming in I guess.
type: Answer
has comment: http://stackoverflow.com/comment/85162217
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85157060
has comment: http://stackoverflow.com/comment/85159796
has comment: http://stackoverflow.com/comment/85157018
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49071229
answers question: http://stackoverflow.com/q/49071229

http://stackoverflow.com/comment/84955308
score: 0
type: Comment
has text: What output you want
type: QuestionComment
comment on: http://stackoverflow.com/q/48975202

http://stackoverflow.com/comment/84937860
has text: @Georgy, I already fixed myself. Thanks for your tip.
comment on: http://stackoverflow.com/q/48963935
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/67075361
type: Answer
has body: In this example snippet, I demonstrate a scenario of integrating Twisted logging into another (custom) logging system (the code for which I've omitted). In this case, the other logger is managing a file object, stdout/err redirects, file rotations etc. I just wanted to to have Twisted supplement that other system and send it's messages over that effectively. I additionally show here how to using log level filtering in Twisted, and how to correctly start and stop their logger as needed. As shown in some other answers, you need to create a new "Observer" bound to a log file object, with a "Filter" to restrict the logging level. If you want to start/stop/restart - then note you once Twisted logging has previously been "started", one needs to redirect that output to a new file (via a new observer), rather than "start" their logging again. That prevents warnings which otherwise appear in the log if you attempt to "start" Twisted logging more than once. I also point out that a call to theLogPublisher.removeObserver, is harmless to call if that observer was already removed (or never added). So, holding on to an observer reference after stopping, is in fact desired here for a simple logic flow, despite perhaps wanting to set such to None - even if that might equate to a tiny "waste" of memory in certain contexts. from twisted.python import log as twistedlog from twisted.logger import( FilteringLogObserver, textFileLogObserver, LogLevelFilterPredicate, LogLevel ) twistedLogObserver = None def startTwistedLogging( logFile, level, isStdMsgHdlr=False ): global twistedLogObserver observer = FilteringLogObserver( textFileLogObserver( logFile ), predicates=[ LogLevelFilterPredicate( level ) ] ) if twistedLogObserver: twistedlog.theLogPublisher.addObserver( observer ) else: twistedlog.startLoggingWithObserver( observer, setStdout=isStdMsgHdlr ) twistedLogObserver = observer def stopTwistedLogging(): if twistedLogObserver: twistedlog.theLogPublisher.removeObserver( twistedLogObserve…
answers question: http://stackoverflow.com/q/49063649
score: 0

http://stackoverflow.com/comment/85112117
type: QuestionComment
has text: @eyllanesc, good point. I tried saving it in a few different locations on my PC but getting the same error.
score: 0
comment on: http://stackoverflow.com/q/49053370
type: Comment

http://stackoverflow.com/comment/85039165
type: Comment
type: AnswerComment
has text: Well... I did get all the numbers in one line. If you really need that feature then go ahead and use @glibdud answer. Be aware that what (s)he's doing there uses a **really** deprecated aspect of python which does not work with python 3. So please stop thinking that using `any` is justified
score: 0
comment on: http://stackoverflow.com/a/49016951

http://stackoverflow.com/q/49040717
score: -1
has answer: http://stackoverflow.com/a/49041899
accepted answer: http://stackoverflow.com/a/49041899
answer count: 1
downvote count: 1
favorite count: 0
has title: Django temporary view
tagged with: python
has body: In my Django Project user is redirect to specific template with content: "Thanks for your registration" def success_signup(request): """Account created with success.""" return render(request, "account/success.html") when he register new account with success. I want to make this template/view temporary. I.E When the user/somebody go to "account/success.html" again should be redirected to the homepage instead of the success.html template. Unfortunately, I can not find this in the documentation. Thanks in advance!
type: AnsweredQuestion
upvote count: 0
tagged with: django
type: Question

http://stackoverflow.com/q/49089127
type: Question
has answer: http://stackoverflow.com/a/49089344
has body: I know that Jupyter is using it's own CSS style which limits what you can do with HTML unless you edit it. I try to display some info with more sophisticated way than Python print and for that I use: from IPython.core.display import display, HTML display(HTML(' some header text '))) Everything is left aligned though - both text and tables. Is there any simple workaround for this? Or is there any other way to have centered tables in Jupyter Notebook?
answer count: 1
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49089344
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
has title: Centering HTML tables and text in Jupyter Notebook
upvote count: 1

http://stackoverflow.com/a/48984560
answers question: http://stackoverflow.com/q/48984071
type: Answer
score: 2
has body: Referring to the answer for the question: "CountVectorizer raising error on short words": words= ['A', 'A', 'A'] vect = TfidfVectorizer(token_pattern='(?u)\\b\\w+\\b') dtm = vect.fit_transform(words) vect.get_feature_names() gives the output: ['a']
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/49024341
downvote count: 0
answer count: 1
favorite count: 0
has title: How to handle multiple results from a coroutine function?
upvote count: 8
tagged with: asynchronous
score: 8
tagged with: python-3.x
has body: I have some generators doing some searching stuff, and I use another generator wrapping them up: def searching_stuff_1(): # searching yield 1 # and searching yield 2 yield 3 def searching_stuff_2(): yield 4 yield 5 def gen(): yield from searching_stuff_1() yield from searching_stuff_2() for result in gen(): print(result) So now I am wondering how I can rewrite it into async version, that can yield multiple values in searching_stuff_1 and searching_stuff_2. I was trying: import asyncio async def searching_stuff_1(): f = asyncio.Future() result = [] await asyncio.sleep(1) #searching result.append(1) #searching result.append(2) result.append(3) f.set_result(result) return f async def searching_stuff_2(): f = asyncio.Future() result = [] await asyncio.sleep(1) result.append(4) result.append(5) f.set_result(result) return f async def producer(): coros = [searching_stuff_1(), searching_stuff_2()] for future in asyncio.as_completed(coros): yield await future async def consumer(xs): async for future in xs: for r in future.result(): print(r) loop = asyncio.get_event_loop() loop.run_until_complete(consumer(producer())) loop.close() However, in this version, I have to append all results into a list and wrap it in a Future instance. I am wondering if there is better way to handle multiple results from coroutine function. Is it possible that I can still yield those numbers?
accepted answer: http://stackoverflow.com/a/49093162
tagged with: python
tagged with: generator
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49093162
tagged with: coroutine
type: Question

http://stackoverflow.com/a/49075376
has body: The problem is that python interprets (4) as 4 and the parameter needs to be an iterable. Try to update to this: cursor.execute( select_categories, (4, ) ) The comma after the 4 will force python to interpret this as a tuple.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49075238
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49075238
type: Answer

http://stackoverflow.com/q/49103070
type: AnsweredQuestion
has title: Why is method in class manipulating a __init__ variable
type: Question
has answer: http://stackoverflow.com/a/49103141
tagged with: class
has body: I have this class Record class Record(): def __init__(self, record): self.state_abbreviations = {'AL': 'Alabama'} self.raw_record = record self.is_valid = self.validate_record(self.raw_record) self.formatted_record = self.format_record(self.raw_record) def validate_record(self, record): if (record.get('provider_first_name') is None and record.get('provider_last_name_legal_name') is None): return False return True def format_record(self, record): # swap state abbreviation for full state name record_state = record.get('provider_business_practice_location_address_state_name') full_state_name = self.state_abbreviations.get(record_state) record['provider_business_practice_location_address_state_name'] = full_state_name return record when I instantiate it: r = Record({'provider_first_name': 'is', 'provider_last_name_legal_name': 'fake', 'provider_business_practice_location_address_state_name': 'AL'}) I would expect r.raw_record to give me {'provider_business_practice_location_address_state_name': 'AL', 'provider_first_name': 'is', 'provider_last_name_legal_name': 'fake'} but the output i am getting is: {'provider_business_practice_location_address_state_name': 'Alabama', 'provider_first_name': 'is', 'provider_last_name_legal_name': 'fake'} I'm confused on why the raw record is being manipulated by the format_record function.
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49103141
tagged with: python

http://stackoverflow.com/q/49032953
has comment: http://stackoverflow.com/comment/85070630
type: AnsweredQuestion
favorite count: 0
has body: I have: beta = 0.95 alpha = 0.3 delta = 0.1 def k_bar(alpha, beta, delta): return ((1 / beta - 1 + delta) / alpha) ** (1 / (alpha - 1)) def c_bar(alpha, delta, k_bar): return k_bar ** alpha - delta * k_bar When i call k_bar(alpha, beta, delta) I get "2.63". But but when i call c_bar(alpha, delta, k_bar) I get "TypeError: unsupported operand type(s) for ** or pow(): 'function' and 'float'" However I would like to get the result instead and make the function as argument work in this specific case. I hope sb. can help me! Cheers, Tobias
type: Question
tagged with: arguments
tagged with: python
has comment: http://stackoverflow.com/comment/85070691
has answer: http://stackoverflow.com/a/49033188
score: -1
tagged with: call
upvote count: 3
has answer: http://stackoverflow.com/a/49033110
answer count: 3
has title: Python: How can I call a function that has another function as argument?
has comment: http://stackoverflow.com/comment/85070694
has answer: http://stackoverflow.com/a/49033041
possible better answer: http://stackoverflow.com/a/49033110
has comment: http://stackoverflow.com/comment/85070518
tagged with: function
accepted answer: http://stackoverflow.com/a/49033041
has comment: http://stackoverflow.com/comment/85070897
downvote count: 4
has comment: http://stackoverflow.com/comment/85070523

http://stackoverflow.com/comment/85089595
type: Comment
type: QuestionComment
has text: @JimWright So it doesn't increment to the dictionary `time` (e.g. `time[i]`)? How would I assign the values then. There are 5 forms, I just need the first and last times.
score: 0
comment on: http://stackoverflow.com/q/49042180

http://stackoverflow.com/comment/85229360
type: QuestionComment
score: 0
has text: Now I got you. No, I wasn't randomly picking it. When ever I changed directory, I changed files location too in the same directory. I was trying it with the thought that there must be problem with directory.
comment on: http://stackoverflow.com/q/49111774
type: Comment

http://stackoverflow.com/comment/85212001
has text: So I ran this code in Notepad++ and it ran fine. What is strange is I can run other code just fine in Sublime but for some reason when I use this user input command it simple fails. Any ideas on how to fix my sublime IDE or what could be causing this would be appreciated.
comment on: http://stackoverflow.com/q/49101915
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85178036
has text: I'd recommend not overwriting the internal `list` type. It would be better to call your `list` something else like `words` or `sentences` or something.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49086222

http://stackoverflow.com/a/49101494
has comment: http://stackoverflow.com/comment/85208561
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49101409
has body: np.random.shuffle is an in-place operation, so you need to either use copies, as explained by @liliscent; or, my preference, just use a function which does not operate in place. np.random.permutation is sufficient for your task: import numpy as np a = np.array([[0.11101831,0.444,0.555,0.6666], [.1,.2,.3,.4], [.10,.20,.30,.40], [.9,.8,.7,.6], [.4,.5,.6,.7]]) saved = [] for i in range(2): x = np.random.permutation(np.random.permutation(a).T) saved.append(x) Even better, you can convert this into a list comprehension: saved = [np.random.permutation(np.random.permutation(a).T) for _ in range(2)] Example result: # [array([[ 0.8 , 0.444 , 0.5 , 0.2 , 0.2 ], # [ 0.9 , 0.11101831, 0.4 , 0.1 , 0.1 ], # [ 0.7 , 0.555 , 0.6 , 0.3 , 0.3 ], # [ 0.6 , 0.6666 , 0.7 , 0.4 , 0.4 ]]), # array([[ 0.4 , 0.11101831, 0.1 , 0.9 , 0.1 ], # [ 0.6 , 0.555 , 0.3 , 0.7 , 0.3 ], # [ 0.7 , 0.6666 , 0.4 , 0.6 , 0.4 ], # [ 0.5 , 0.444 , 0.2 , 0.8 , 0.2 ]])]
upvote count: 1

http://stackoverflow.com/comment/85128867
type: Comment
has text: This seems to work, never used the lambda before. Is there anyway to add this into the formula? just want to keep things clean and inclusive: g['profit'] = g.credit - g.debit
comment on: http://stackoverflow.com/a/49061446
type: AnswerComment
score: 0

http://stackoverflow.com/q/49072355
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/95330032
type: Question
has body: I’m trying to convert a mathematical expression into a binary tree structure using the “Node” type in zss library. I’m using this particular “Node” type because I want to compute the tree edit distance using a function in the same library. Mathematical expressions can be in different formats e.g. (28 + 32), (((75 + 2) - 21) + (94 - 90)), ((53 + 67) / 2), ((40 * 51) / (86 - 52)) etc Trees are binary trees. Root node is always an operator and the leaves are always numbers. “Node” tree structure is always Node(root_node, [leftChild,rightChild]). Following are few examples of how an expression is represented in a tree. Following is what my code currently does (complete code): Read in the string expression and split it into tokens Store the indexes of operators in op_index Case 1: when the expression is like (2 + 3) – has one operator (Set the operator as top_operator, Sort the leaf nodes and assign the lowest to the left tree (because of this (2 + 3) and (3 + 2) expressions will always be built into the same manner)) Case 2: when the expression is like ((2 + 3) * 5) – has two operators (Set the operator as top_operator and sort the leaf nodes) Return the tree def generateTree(bs): item = bs.split() op_index = [] top_operator = [] left_tree = [] right_tree = [] # stores the index of each operator in item list for i in range(0, len(item)): if item[i] in ['+', '-', '*', '/']: op_index.append(i) for n in op_index: #case 1 if (len(op_index) == 1): top_operator.append(item[n]) #a = Node(item[n - 1], []) #b = Node(item[n + 1], []) if(isLeftChildNodeSmaller(item[n-1], item[n+1]) == True): left_tree.append(Node(item[n - 1], [])) right_tree.append(Node(item[n + 1], [])) else: left_tree.append(Node(item[n + 1], [])) right_tree.append(Node(item[n - 1], [])) #case 2 elif (len(op_index) == 2): if(isInt(item[n-1]) == True and isInt(item[n+1]) == True): if (isLeftChildNodeSmaller(item[n - 1], item[n + 1]) == True): c = Node(item[n],[Node(item[n - 1], []), Node(item[n + 1], [])]) else: …
has comment: http://stackoverflow.com/comment/95354756
has comment: http://stackoverflow.com/comment/85150487
has comment: http://stackoverflow.com/comment/85170840
downvote count: 0
has title: Dynamically constructing a binary tree using "Node" structure in python
favorite count: 0
tagged with: binary-tree
tagged with: python
score: 2

http://stackoverflow.com/comment/84940053
comment on: http://stackoverflow.com/q/48967112
type: QuestionComment
type: Comment
has text: Index 218 is an example. There will be another entry in the 'DOCNO' that will be MP00059189. It is also possible that there will be MP0059189B, MP0059189C, etc. in the dataframe.
score: 0

http://stackoverflow.com/comment/85046251
score: 0
type: AnswerComment
has text: That shouldn't matter here. `\d` isn't a recognized escape character, so Python "helpfully" pretends it's not an escape (I put sarcasm quotes around "helpfully", because when `'c:\data'` works, it gives the mistaken impression that raw strings aren't needed, leading to confusion when `'c:\bin'` fails, because `\b` becomes the ASCII backspace character). If I enter `'c:\data'` in the interactive interpreter, it echoes `'c:\\data'` as expected.
type: Comment
comment on: http://stackoverflow.com/a/49020268

http://stackoverflow.com/comment/85061681
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49028561
has text: Hi there! I am not sure I 100% understand. So you basically want to be able to run pip command from every folder without having errors?
score: 1

http://stackoverflow.com/comment/85084479
type: Comment
type: QuestionComment
score: 0
has text: maybe s_t_ = = np.zeros([T,1]) instead of s_t ?
comment on: http://stackoverflow.com/q/49039491

http://stackoverflow.com/a/49063151
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49062816
downvote count: 0
has body: According to cv2 documentation: Python: cv.CvtColor(src, dst, code) → None Parameters: src – input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point. That means images in your code is not the required kind of thing. And from PIL: PIL.Image.open(fp, mode='r') Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new(). Apparently you have opened the file, but loaded the image. And cv2 can't load it for you. Note that I'm working from documentation that I can find on line; I don't have first hand experience with these modules. Do you have documentation or examples that indicate that this code should work?

http://stackoverflow.com/comment/108004981
comment on: http://stackoverflow.com/a/51116910
type: AnswerComment
has text: @Lore I simplified it a bit, look at the example again. Yield from basically enters into another generator, until that generator is finished.
type: Comment
score: 2

http://stackoverflow.com/comment/85128827
score: 0
type: Comment
type: QuestionComment
has text: Could you show an example or two of the expected input/output? What would be the desired `Direction` if `flowDir` was `100`? `210`?
comment on: http://stackoverflow.com/q/49061780

http://stackoverflow.com/q/49091553
favorite count: 0
upvote count: 9
tagged with: python
has answer: http://stackoverflow.com/a/49096518
accepted answer: http://stackoverflow.com/a/49096518
type: AnsweredQuestion
has title: UserWarning: Discrepancy between trainable weights and collected trainable weights error
has body: Hi I'm training VGG16 network for my own dataset. Following has given the code I used. from keras.models import Sequential from scipy.misc import imread #get_ipython().magic('matplotlib inline') import matplotlib.pyplot as plt import numpy as np import keras from keras.layers import Dense import pandas as pd from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input import numpy as np from keras.applications.vgg16 import decode_predictions from keras.utils.np_utils import to_categorical from sklearn.preprocessing import LabelEncoder from keras.models import Sequential from keras.optimizers import SGD from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, AveragePooling2D, ZeroPadding2D, Dropout, Flatten, merge, Reshape, Activation import os from sklearn.metrics import log_loss import cv2 from keras.models import Model from sklearn import cross_validation from imagenet_utils import preprocess_input from imagenet_utils import preprocess_input,decode_predictions import tensorflow as tf from keras.backend.tensorflow_backend import set_session from skimage import measure, morphology from mpl_toolkits.mplot3d.art3d import Poly3DCollection from os import walk from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import confusion_matrix os.environ['CUDA_VISIBLE_DEVICES'] = '-1' def load_images(): def train_test_separation(): df = pd.read_csv('C:/CT_SCAN_IMAGE_SET/resnet_50/dbs2017/data/stage1_labels.csv') print(df.head()) #print (filenames,' ',pathname,' ',BASE_PATH ) #images=load_images() labeling = df['cancer'].as_matrix() names=['Not_Cancer','Cancer'] Y_category=keras.utils.to_categorical(labeling, num_classes=2) x = np.array([np.mean(np.load('E:/224x224/%s.npy' % str(id)), axis=0) for id in df['id'].tolist()]) print ('.......................................',Y_category.shape) img_rows, img…
type: Question
score: 9
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras

http://stackoverflow.com/a/48998958
score: 0
type: Answer
has body: It seems that you're already writing everything to the "output.xml" file. Feel free to post a snippet of your output file, as well as for the input ones. If the only problem is that you want it be structured across multiple lines, compared to be a one-liner, you could just set the pretty print flag to true. newdom.write("output.xml", pretty_print=True) Output example: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> My CD Collection Title Artist . . </xsl:template> </xsl:stylesheet>
has comment: http://stackoverflow.com/comment/85003880
answers question: http://stackoverflow.com/q/48998062

http://stackoverflow.com/comment/85099463
has text: @TAMIMHAIDER initialize the value of `a` before evaluating it. updated the code. mark as accepted & upvote if it helped you.
type: AnswerComment
comment on: http://stackoverflow.com/a/49043343
score: 0
type: Comment

http://stackoverflow.com/q/49037669
has title: How can I catch any output to the console from a Python Tkinter application?
linked to: http://stackoverflow.com/q/1218933
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I have a large, multifile, Tkinter app with innumerable functions, that is then being packaged with Pyinstaller as an executable. It contains error handling for expected events. However, it does not have any error handling for unexpected events. When running the application before packaging it as an executable, unexpected errors are printed to the console. Once it is packaged as an executable, these errors are hidden (I do not want a terminal window to display to the user). The problem with this is that unexpected errors are not displayed anywhere, and therefore I cannot capture and debug them. How can I have a "catch-all" that grabs any output that would go to the console, or catch or log any error? I know many ways to do this with extra code throughout, but adding code to each function of the application seems overly burdensome for what I'm trying to achieve.
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49037979
tagged with: tkinter
score: 1
has comment: http://stackoverflow.com/comment/85081608
tagged with: error-handling
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85120024

http://stackoverflow.com/comment/89291004
type: QuestionComment
has text: Note that *only* ``async def``, ``async for``, ``async with`` and ``await`` are part of the Python spec. These are basically classical generator based coroutines (``def ...: yield``) and their temporary delegation (``yield from ...``), extending the later to ``with`` and ``for``. In contrast ``asyncio`` is an I/O library built using those primitives. There are other libraries, such as ``curio`` and ``trio`` - mainly built to be easier to reason about. You may want to check them out after reading @Bharel 's answer.
comment on: http://stackoverflow.com/q/49005651
score: 1
type: Comment

http://stackoverflow.com/comment/85221612
score: 0
type: Comment
has text: @DylanWyatt please take a look at the answers.
type: QuestionComment
comment on: http://stackoverflow.com/q/49108301

http://stackoverflow.com/q/49067168
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49100506
tagged with: kivy
has title: Is there any way to add a widget above the parent(Layout)?
score: 0
answer count: 1
tagged with: layout
type: AnsweredQuestion
has body: Hey i recently started with python / kivy programming. I have a basic question which can not be solved with the documentation i found. I wanna add a self defined function (InitiateGraph) above my root (ScreenLayout). Within this function i am plotting a graph with matplotlib, which is generated with the call of the app. It should look like this: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |here should be the plotted graph from InitiateGraph| _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | here should follow the GridLayout (ScreenLayout) | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Currently the two blocks are reversed. Please see following minimalistic example. Python-code: class ScreenLayout(GridLayout): def __init__(self, *args, **kwargs): super(ScreenLayout, self).__init__(*args, **kwargs) self.add_widget(self.InitiateGraph()) def InitiateGraph(self): ... class TestApp(App): def build(self): return ScreenLayout() Test = TestApp() Test.run() Kivy-code: &lt;ScreenLayout&gt;: rows: 3 BoxLayout: BoxLayout: Is there a way to do this?
has answer: http://stackoverflow.com/a/49100506
tagged with: kivy-language

http://stackoverflow.com/comment/85262047
type: Comment
comment on: http://stackoverflow.com/a/49110204
has text: it is almost the same as yesterday
type: AnswerComment
score: 0

http://stackoverflow.com/a/48999443
upvote count: 4
answers question: http://stackoverflow.com/q/48999392
type: AcceptedAnswer
downvote count: 0
has body: You can use try-except statement. It's not a really good idea to use a general except handler though. term = ["fug,fuge", "duc,duce,duct", "ortho", "morph", "mot,mob,mov,cine,kine", "ible, able", "flect, flex", "flu", "cide,sec,seg", "miso", "mort", "ology", "port", "ject,jet", "miss,mitt", "viv", "vert, volv, rota", "naut", "act", "klept", "frac,frag,rupt", "simil", "struct", "tens", "therm", "luc,lum,photo", "foli,phyll", "tox", "bene,bon", "agr"] definition = ["drive away,flee", "to lead", "right,straight,correct", "change", "to move", "able to be", "to bend", "to flow", "to kill,cut", "hate", "to die", "science,study of", "carry", "to throw", "to send", "to live", "to turn", "to sail", "to do, make", "to steal", "to break", "to resemble", "to build", "to stretch", "heat", "light", "poison", "good", "field"] x = 0 while x &lt; 30: try: t = driver.find_element_by_xpath("//div[contains(text(), '"+term[x]+"')]") t.click() d = driver.find_element_by_xpath("//div[contains(text(), '" + definition[x] + "')]") d.click() except selenium.common.exceptions.NoSuchElementException: pass x=x+1
accepted answer of: http://stackoverflow.com/q/48999392
type: Answer
has comment: http://stackoverflow.com/comment/85004155
has comment: http://stackoverflow.com/comment/85004265
has comment: http://stackoverflow.com/comment/85004143
score: 4

http://stackoverflow.com/a/49091540
downvote count: 0
has comment: http://stackoverflow.com/comment/85199594
answers question: http://stackoverflow.com/q/49091423
has comment: http://stackoverflow.com/comment/85191549
has body: Cast your date column to DateTime if you haven't yet: df['date'] = pd.to_datetime(df['date']) If the data isn't already sorted by date, make sure to do that (thanks @PiRSquared): df.sort_values(by='date', inplace=True) Create the desired column values: df['pos'] = df['date'].dt.month.diff().ne(0).cumsum()*100 df date open high low close pos 0 2007-11-02 22757 22855 22564 22620 100 1 2007-11-05 22922 22964 22349 22475 100 2 2007-11-06 22540 22755 22404 22734 100 3 2007-11-07 23058 23251 22811 22929 100 4 2007-11-08 22740 22936 22683 22783 100 5 2007-11-28 21841 22040 21703 21776 100 6 2007-11-29 22000 22055 21586 21827 100 7 2007-11-30 21750 22169 21694 21935 100 8 2007-12-03 21782 21935 21469 21527 200 9 2007-12-04 21453 21760 21378 21648 200 10 2007-12-05 21725 21836 21526 21627 200 11 2007-12-06 21460 21787 21454 21632 200 12 2007-12-07 21836 21909 21699 21865 200 13 2007-12-26 23352 23556 23298 23456 200 14 2007-12-27 23523 23744 23276 23333 200 15 2007-12-28 23338 23449 23112 23225 200 16 2008-01-02 23225 23388 23174 23183 300 17 2008-01-03 23259 23379 23197 23287 300 18 2008-01-04 23450 24164 23406 24152 300 19 2008-01-24 23079 23386 22969 23292 300 20 2008-01-25 23502 23754 23369 23678 300 21 2008-01-28 23617 23627 23229 23371 300
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/q/49100090
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/85205542
has answer: http://stackoverflow.com/a/49106799
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49100178
possible better answer: http://stackoverflow.com/a/49106799
answer count: 2
score: 3
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49100178
tagged with: python
has body: I'm parsing a file that has chronologically timestamped data for multiple time series that I would like to parse in python and then use matplotlib to create a single line plot with independent lines for each set of time series data. The data I'm parsing looks something like this: time label value 1.05 seriesA 3.925 1.09 seriesC 0.245 2.13 seriesB 12.32 2.73 seriesC 4.921 I've parsed the file into a dictionary of lists that contain (time,value) tuples keyed on the series label. I'm struggling with how to get from this to a single line plot with all this data. I want independent lines for seriesA, seriesB, seriesC, etc. on a single plot. Any pointers? Edit: As requested the dictionary is below. I had a hard time figuring out the best way to store this data so maybe the data structure I'm using is also a problem. The keys below are the different time series labels and the values are a list of (time,value) tuples. In any case, here it is: {'client1': [(861.991698574, 298189000.0), (862.000768158, 0.0)], 'client2': [(861.781502324, 0.0), (861.78903722, 153600000.0), (862.281483262, 0.0), (862.289038158, 153600000.0)], 'client3': [(862.004470762, 3295674368.0), (862.004563939, 3295674368.0), (862.03981821, 799014912.0), (862.040403314, 1599078400.0), (862.540269616, 3295674368.0), (862.55133097, 1599078400.0)]}
type: AnsweredQuestion
has title: Python line plot multiple time series on same plot

http://stackoverflow.com/comment/84993496
has text: This solved my problem and saved me a lot of time! The link is instructive too.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48993354

http://stackoverflow.com/comment/85161659
type: Comment
has text: Sorry for bothering you again. At the moment I have {A:C}, but is there a way to generate {A:{B:C}}?
comment on: http://stackoverflow.com/a/49077045
type: AnswerComment
score: 0

http://stackoverflow.com/q/49053252
has title: Pandas alternative to apply - to create new column based on multiple columns
tagged with: pandas
upvote count: 7
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85111219
has comment: http://stackoverflow.com/comment/85111610
tagged with: python
has comment: http://stackoverflow.com/comment/91561086
score: 7
has answer: http://stackoverflow.com/a/49057014
linked to: http://stackoverflow.com/q/16476924
has comment: http://stackoverflow.com/comment/85115305
type: Question
tagged with: numpy
tagged with: dataframe
has body: I have a Pandas dataframe and I would like to add a new column based on the values of the other columns. A minimal example illustrating my usecase is below. df = pd.DataFrame([[4,5,19],[1,2,0],[2,5,9],[8,2,5]], columns=['a','b','c']) df a b c --------------- 0 4 5 19 1 1 2 0 2 2 5 9 3 8 2 5 x = df.sample(n=2) x a b c --------------- 3 8 2 5 1 1 2 0 def get_new(row): a, b, c = row return random.choice(df[(df['a'] != a) &amp; (df['b'] == b) &amp; (df['c'] != c)]['c'].values) y = x.apply(lambda row: get_new(row), axis=1) x['new'] = y x a b c new -------------------- 3 8 2 5 0 1 1 2 0 5 Note: The original dataframe has ~4 million rows and ~6 columns. The number of rows in the sample might vary between 50 and 500. I am running on a 64-bit machine with 8 GB RAM. The above works, except that it is quite slow (takes about 15 seconds for me). I also tried using x.itertuples() instead of apply and there is not much of an improvement in this case. It seems that apply(with axis=1) is slow since it does not make use of the vectorized operations. Is there some way I could achieve this in a faster way? Can the filtering(in the get_new function) be modified or made more efficient compared to using conditional boolean variables, as I currently have? Can I in some way use numpy here for some speedup? Edit: df.sample() is also quite slow and I cannot use .iloc or .loc since I am further modifying the sample and do not wish for this to affect the original dataframe.
tagged with: apply

http://stackoverflow.com/a/49069756
upvote count: 2
answers question: http://stackoverflow.com/q/49060506
has body: One way to solve this is to use another class as a controller for all of the windows you want to show. In each window you will send a signal when you want to switch windows and it is up to this controller class to decide how to handle the signal when received and decide which window to show. Any arguments that you need passed can be passed through the signals. Here is a simplified complete working example.
type: AcceptedAnswer
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/85184734
score: 2
accepted answer of: http://stackoverflow.com/q/49060506

http://stackoverflow.com/comment/117757750
type: Comment
type: QuestionComment
has text: Any solution to this yet? I'm experiencing almost the same thing though.
comment on: http://stackoverflow.com/q/49094245
score: 0

user-interface
tags question: http://stackoverflow.com/q/49036021
tags question: http://stackoverflow.com/q/49091372
tags question: http://stackoverflow.com/q/48972683
type: Tag
tags question: http://stackoverflow.com/q/48977473
tags question: http://stackoverflow.com/q/48983638
tags question: http://stackoverflow.com/q/48964879
tags question: http://stackoverflow.com/q/49103120
tags question: http://stackoverflow.com/q/49010193
tags question: http://stackoverflow.com/q/49037051
tags question: http://stackoverflow.com/q/49029780
tags question: http://stackoverflow.com/q/49037104
tags question: http://stackoverflow.com/q/49101704
tag name: user-interface
tags question: http://stackoverflow.com/q/49029457

http://stackoverflow.com/q/49093444
has title: Python program to sort and count repeated no in list
has comment: http://stackoverflow.com/comment/85192276
favorite count: 0
has body: Write a Python function histogram(l) that takes as input a list of integers with repetitions and returns a list of pairs as follows: for each number n that appears in l, there should be exactly one pair (n,r) in the list returned by the function, where r is is the number of repetitions of n in l. the final list should be sorted in ascending order by r, the number of repetitions. For numbers that occur with the same number of repetitions, arrange the pairs in ascending order of the value of the number. For instance: &gt;&gt;&gt; histogram([13,12,11,13,14,13,7,7,13,14,12]) [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)] &gt;&gt;&gt; histogram([7,12,11,13,7,11,13,14,12]) [(14, 1), (7, 2), (11, 2), (12, 2), (13, 2)] &gt;&gt;&gt; histogram([13,7,12,7,11,13,14,13,7,11,13,14,12,14,14,7]) [(11, 2), (12, 2), (7, 4), (13, 4), (14, 4)]
has answer: http://stackoverflow.com/a/49093494
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49093497
tagged with: list
downvote count: 3
type: Question
answer count: 2
upvote count: 0
tagged with: function
tagged with: sorting

http://stackoverflow.com/comment/85038291
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49016530
type: Comment
has text: There are two reasons for this. First, you need to specify to the gradient calculation function that whether you are in training phase or test phase. Second, when you add dropout, some of the activations are dropped(becomes zero), so even if you get it running, it would not make much sense, if the dropout is active, you don't know whether the activation worked or lost due to dropout

http://stackoverflow.com/q/49038781
has body: I am trying to connect to my Neo4j graph database server from a new machine. I can successfully connect from an older machine but do not wish to use the older one anymore. I have reduced the problem to a simple script that returns an exception: from neo4j.v1 import GraphDatabase, basic_auth auth = basic_auth("username","password") session = GraphDatabase.driver("bolt://remote.server:7687",auth=auth).session() statement = """MATCH (a:Protein) WHERE a.name={name} RETURN a.Accession""" tx = session.begin_transaction() record = tx.run(statement,{'name':"ARCH_HUMAN"}).single() print record['a.Accession'] session.close() And the error message is: File "Test.py", line 10, in &lt;module&gt; tx = session.begin_transaction() File "/home/username/anaconda2/lib/python2.7/site-packages/neo4j/v1/api.py", line 432, in begin_transaction self._connect() File "/home/username/anaconda2/lib/python2.7/site-packages/neo4j/v1/api.py", line 269, in _connect self._connection = self._acquirer(access_mode) File "/home/username/anaconda2/lib/python2.7/site-packages/neo4j/v1/direct.py", line 52, in acquire raise ServiceUnavailable("Cannot acquire connection to {!r}".format(self.address)) neo4j.exceptions.ServiceUnavailable: Cannot acquire connection to Address(host='remote.server', port=7687) Port 7687 is open (confirmed via netstat -tulpn and iptables -L), and neo4j is configured to listen to 0.0.0.0:7687. In addition, .neo4j/known_hosts contains an entry for host 0.0.0.0 What's strange is that I get a different error message (neo4j.exceptions.AuthError) if I break the authentication by using an incorrect password. So the connection is being made to check the password, but still I cannot connect with the correct auth. What's going on?
tagged with: neo4j
has answer: http://stackoverflow.com/a/49182824
favorite count: 0
has comment: http://stackoverflow.com/comment/85086579
has title: Cannot acquire connection to Neo4j database
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/85083351
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49182824
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49048342
has answer: http://stackoverflow.com/a/49048342

http://stackoverflow.com/a/48967501
score: 4
answers question: http://stackoverflow.com/q/48967169
upvote count: 4
has body: Idea is to generate reindexing matrix A = np.array([ 37.17, 36.99, 36.84, 37.57, 37.49, 37.45, 37.82, 37.95, 37.36, 37.84, 37.85, 37.12]) w = 4 g = 2 Time delay embedding with w and g A[(np.arange(w)*(g+1))+ np.arange(np.max(a.shape[0] - (w-1)*(g+1), 0)).reshape(-1,1)] Output: array([[ 37.17, 37.57, 37.82, 37.84], [ 36.99, 37.49, 37.95, 37.85], [ 36.84, 37.45, 37.36, 37.12]]) if A is a matrix [index, value] then add value column index A[n...) ,1] Update 1 # incorrect step count calculation was replaced by a.shape[0]-(w-1)*(g+1) Update 2 # added max to avoid errors on impossible values of g and w Check documentation on used functions np.arange, np.reshape, broadcasting rules and indexing.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84942246
type: Answer
has comment: http://stackoverflow.com/comment/84942677
has comment: http://stackoverflow.com/comment/84942120
has comment: http://stackoverflow.com/comment/84945987
has comment: http://stackoverflow.com/comment/84942121
has comment: http://stackoverflow.com/comment/84944458
has comment: http://stackoverflow.com/comment/84942294
accepted answer of: http://stackoverflow.com/q/48967169

http://stackoverflow.com/q/49076558
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49076708
tagged with: tflearn
has title: Getting the following error, "ImportError: cannot import name 'rnn_cell_impl' " on tensorfow V 1.4.0
type: Question
has body: ~/anaconda3/lib/python3.6/site-packages/tflearn/layers/recurrent.py in &lt;module&gt;() 12 # Fix for TF 1.1.0 and under 13 from tensorflow.contrib.rnn.python.ops.core_rnn import static_rnn as _rnn, static_bidirectional_rnn as _brnn ---&gt; 14 from tensorflow.python.ops.rnn import rnn_cell_impl as _rnn_cell, dynamic_rnn as _drnn 15 from tensorflow.contrib.rnn.python.ops import core_rnn_cell 16 ImportError: cannot import name 'rnn_cell_impl' Getting the following error. TF version 1.4 .
tagged with: python
score: 0
answer count: 1
tagged with: tensorflow

psycopg2
tags question: http://stackoverflow.com/q/49010166
tags question: http://stackoverflow.com/q/49022470
tags question: http://stackoverflow.com/q/49097346
tags question: http://stackoverflow.com/q/49038635
tags question: http://stackoverflow.com/q/49062045
tags question: http://stackoverflow.com/q/49113126
type: Tag
tags question: http://stackoverflow.com/q/49020718
tags question: http://stackoverflow.com/q/49006388
tags question: http://stackoverflow.com/q/49027003
tags question: http://stackoverflow.com/q/49073662
tags question: http://stackoverflow.com/q/49091105
tags question: http://stackoverflow.com/q/49096763
tag name: psycopg2

http://stackoverflow.com/comment/85393692
score: 0
type: AnswerComment
type: Comment
has text: Everything between the `()` of the print function builds a string. You can simply assign that to a variable. like: `mystring = "\n".joi....`
comment on: http://stackoverflow.com/a/49099105

http://stackoverflow.com/q/49105138
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/49105192
accepted answer: http://stackoverflow.com/a/49105192
has title: Multiple and or conditions for flagging in python
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: I have the below data in a pd dataframe : There are cutoffs for Sliver and OThers(Like all Multi's - Multi_A etc) as below: d_id Sliver Multi_A Multi_B Multi_C Multi_D no_of_prem Flag_Sliver 5 4.80 53.05 19.07 13.59 0 3 No 18 5.17 27.63 26.83 12.15 0 3 No 25 1.28 0.14 0.12 0 0 2 Yes 32 0.90 0.43 0.94 0 0 2 No 33 3.69 3.24 0.77 1.36 0 3 No 34 0.15 11.62 5.92 1.42 0 3 No 55 0.31 11.29 5.95 1.02 0 3 No 64 0.25 0.82 2.77 0 0 2 No 86 0.02 9.65 1.82 0.10 0 3 No 89 0.13 3.19 1.55 1.77 0 3 No Sliver 5 Multis 0.15 IF any d_id has value in Sliver which is less than 5 and any two of the multi's(there are 4 Multi's in total) for that d_id has values less than 0.15 then the Flag variable is given a Yes or else a No. IN the above example only 25 satisfies the condition and hence flagged as yes. Can someone please help me with these conditions?

http://stackoverflow.com/q/48980285
downvote count: 0
has answer: http://stackoverflow.com/a/48980316
has comment: http://stackoverflow.com/comment/84965672
has comment: http://stackoverflow.com/comment/84965694
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/70219968
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/526125
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84965683
tagged with: list
has comment: http://stackoverflow.com/comment/84965712
has body: I'm messing around with dictionaries for the first time and something's coming up that's confusing me. Using two lists to create a new dictionary, the order of the list terms for the key part seems to be wrong. Here's my code: list1 = ["a", "b", "c", "d"] list2 = [5,3,7,3] newDict = {list1[c]: number for c, number in enumerate(list2)} print(newDict) This gives me the following: {'a': 5, 'd': 3, 'c': 7, 'b': 3} Why is this happening? Surely the 'c' value getting terms from the list is going from 0 and upwards, so why isn't it creating the dictionary with the letters in the same order? Thanks.
has comment: http://stackoverflow.com/comment/84965797
linked to: http://stackoverflow.com/q/39980323
answer count: 4
tagged with: for-loop
has answer: http://stackoverflow.com/a/48980325
has answer: http://stackoverflow.com/a/48980314
has title: Python Dictionary Key Order With Comprehensions
has comment: http://stackoverflow.com/comment/84965753
accepted answer: http://stackoverflow.com/a/48980314
score: 2
possible better answer: http://stackoverflow.com/a/48980316
type: AnsweredQuestion

http://stackoverflow.com/q/48981749
tagged with: multidimensional-array
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84968617
has answer: http://stackoverflow.com/a/48981824
type: Question
tagged with: numpy
has title: Two denominational array slicing
score: 0
accepted answer: http://stackoverflow.com/a/48981824
answer count: 1
linked to: http://stackoverflow.com/q/509211
has body: I have a portion of Viterbi algorithm that I want to manipulate. I need to understand the slicing part in this code: import numpy as np A = np.array([[0.6, 0.2, 0.2], [0.5, 0.3, 0.2], [0.4, 0.1, 0.5]]) pi = np.array([0.5, 0.2, 0.3]) O = np.array([[0.7, 0.1, 0.2], [0.1, 0.6, 0.3], [0.3, 0.3, 0.4]]) states = UP, DOWN, UNCHANGED = 0, 1, 2 observations = [UP, UP, DOWN] alpha = np.zeros((len(observations), len(states))) # time steps x states alpha[:,:] = float('-inf') backpointers = np.zeros((len(observations), len(states)), 'int') ***alpha[0, :] = pi * O[:,UP]*** in the last line print out the O[:,UP] what is should give me: [0.7, 0.1, 0.2] I believe instead, it gives me: O[:,UP] Out[15]: array([ 0.7, 0.1, 0.3]) I tried to look into this Understanding Python&#39;s slice notation I couldn't understand why it changes the last element of the array. Also, I run this: O[:,UNCHANGED] Out[17]: array([ 0.2, 0.3, 0.4]) I'm still newbie in python, I need some help

http://stackoverflow.com/a/48998421
accepted answer of: http://stackoverflow.com/q/48998383
has comment: http://stackoverflow.com/comment/85002942
has body: Change your method references within main() from tile_chart to self.tile_chart. You have defined the variable at class rather than method level. Therefore, to call the variable you have to refer to self.
has comment: http://stackoverflow.com/comment/85002458
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48998383

http://stackoverflow.com/comment/85084712
score: 0
comment on: http://stackoverflow.com/q/49039491
type: Comment
type: QuestionComment
has text: I got `def v_t(var_v, T): # Getting draws of the shock realizations v_t_ = np.zeros([T,1]) # Specification for stochastic realizations: v_t_[1:T] = (var_v ** 0.5) * np.random.randn(len(v_t_) - 1, 1) return v_t_ def s_t(rho, T): # Generating the sequence of autocorrelated productivity states v_t_2 = v_t(var_v, T) s_t_ = np.zeros([T,1]) s_t_[0] = 0 for t in range(1,T): s_t_[t] = rho *s_t_[t-1] + v_t_2[t] return s_t_ ` But it does not work either....

http://stackoverflow.com/comment/85312486
type: QuestionComment
comment on: http://stackoverflow.com/q/49100088
has text: Okay, will consider that.
score: 0
type: Comment

http://stackoverflow.com/comment/84940159
comment on: http://stackoverflow.com/a/48967221
score: 0
type: Comment
has text: @KindStranger Duly noted. Updated the answer as well.
type: AnswerComment

http://stackoverflow.com/q/48967040
tagged with: python
tagged with: nlp
tagged with: text-analysis
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/84942143
has body: Is there any way to determine different kind of noises present in the data or we just assume all standard noises to be present and do a pre-processing considering them. From noises here, I mean, html, mentions, etc
type: Question
has title: How to determine the presence of different noises in text data while performing Text Pre-processing with millions of rows?
score: 0
has comment: http://stackoverflow.com/comment/84939844
has comment: http://stackoverflow.com/comment/84941007

http://stackoverflow.com/q/49015475
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/49016397
tagged with: python
has body: I would like to apply custom percentages to my dataframe rows and last row per each company id should always be zero. I tried with df.apply method but not able to pass multiple parameters. Appreciate if you could let me know in how many ways this problem can be solved? Thank you in advance for your attention and efforts!! df = pd.DataFrame({'CompanyId' : ['A','A','A','B','B'], 'stand_alone' : [10,12,-5,20,1]}) def get_change(current,previous): if current==previous: return 0 if current&gt;=0 and previous&lt;0: chg=1.0 if current&gt;=0 and previous==0: chg=1.0 if current&lt;0 and previous&gt;0: chg=-1.0 if current&gt;0 and previous&gt;0: chg=abs(current)/abs(previous)-1 if current&lt;0 and previous&lt;0: chg=abs(current)/abs(previous)-1 chg=-chg return round(chg*100,2) Output should be as follows: CompanyId change stand_alone 0 A -16.67 10 1 A 100.00 12 2 A 0.00 -5 3 B 1900.00 20 4 B 0.00 1
has comment: http://stackoverflow.com/comment/85036350
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: dataframe
has title: How to apply custom percent change to pandas dataframe?
tagged with: apply
has comment: http://stackoverflow.com/comment/85036298
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49016175
answer count: 2
possible better answer: http://stackoverflow.com/a/49016397
has answer: http://stackoverflow.com/a/49016175

http://stackoverflow.com/comment/85001695
type: QuestionComment
score: 1
has text: Interesting, perhaps I wasn't looking deep enough. It seems classes will create `__annotations__` to the mapping when there's annotated class attributes, but not for instance attributes which is what you're looking for.
comment on: http://stackoverflow.com/q/48997386
type: Comment

http://stackoverflow.com/a/49043748
answers question: http://stackoverflow.com/q/49043682
score: 0
has body: To expand the row from the numpy data use * like: Code: writer.writerow(*line) Whole Listing: def write_to_csv(file_name, header, numpy_data): with open(file_name, "w", newline='') as csv_file: writer = csv.writer(csv_file, delimiter=',') writer.writerow(header) for line in numpy_data: if line is None: writer.writerow(line) else: writer.writerow(*line)
type: Answer
has comment: http://stackoverflow.com/comment/85092643

http://stackoverflow.com/q/49015697
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85036739
tagged with: python
has comment: http://stackoverflow.com/comment/85036613
has comment: http://stackoverflow.com/comment/85036379
has comment: http://stackoverflow.com/comment/85037310
score: 1
has answer: http://stackoverflow.com/a/49016146
upvote count: 1
has comment: http://stackoverflow.com/comment/85036507
type: Question
has comment: http://stackoverflow.com/comment/85036565
has comment: http://stackoverflow.com/comment/85036330
has comment: http://stackoverflow.com/comment/85036704
has title: Adding arrays at run-time in 4d numpy array python
has comment: http://stackoverflow.com/comment/85036497
tagged with: numpy
has comment: http://stackoverflow.com/comment/85038780
has comment: http://stackoverflow.com/comment/85036302
linked to: http://stackoverflow.com/q/49014541
answer count: 1
has comment: http://stackoverflow.com/comment/85036420
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/85036393
has body: I am trying to make a list of 3d numpy arrays for which I need to make a 4d numpy array and then later append the sub-arrays to it.I saw this method to create empty arrays: numpy.empty(shape, dtype=float, order='C') The problem is,the size of the 3d arrays in each dimension is not fixed.But while making the 4d numpy array,I have to define the shape and dimensions. Can anyone please provide some information on how this functionality can be achieved. Thank you for your time.
favorite count: 0
linked to: http://stackoverflow.com/q/49017619
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85036437
has comment: http://stackoverflow.com/comment/85036349
has comment: http://stackoverflow.com/comment/85036525

http://stackoverflow.com/q/48964787
possible better answer: http://stackoverflow.com/a/48964894
upvote count: 4
score: 0
downvote count: 4
answer count: 3
favorite count: 0
has title: Merging lines in Notepad++ or by using Python
has answer: http://stackoverflow.com/a/48964972
tagged with: python
has answer: http://stackoverflow.com/a/48964894
tagged with: regex
has answer: http://stackoverflow.com/a/48964895
accepted answer: http://stackoverflow.com/a/48964895
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84936013
has comment: http://stackoverflow.com/comment/84939993
type: Question
tagged with: notepad++
has body: I have a long file which is structured like below: every line should start with 500 there are lines not starting with 500 (Line 2, Line 4, basically every even line) What I want to do: The lines not starting with 500 should be merged with not even line above (so Line 2 with Line 1, Line 4 with Line 3, etc). Once merging additional semicolon should be added (i.e. &lt;Line 1&gt;;&lt;Line 2&gt;). How I can easily do it in python (2.7)? Regex in Notepad++ may also work. I've heard that I should use a multi-line mode but I don't know how to do it. Probably it's not even hard but I have a hard time dealing with it. Thanks. Here the input (simplified): ;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU” ;” 6,291.00”;; ;500;6900;;”YPNV”;”KE”;”53213072”;”YOU” ;” 6,991.00”;; Expected output: ;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”;;” 6,291.00”;; ;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”;;” 6,991.00”;;

http://stackoverflow.com/a/49061904
has body: &gt;&gt;&gt; test = """\ ... ENSG1 1:24 2:56 3:47 4:68 5:89 ... ENSG2 1:25 2:57 3:48 4:69 5:90 ... ENSG3 1:26 2:58 3:49 4:70 5:91""" &gt;&gt;&gt; result = {} &gt;&gt;&gt; for row in test.splitlines(): ... key, *values = row.split() ... result[key] = values ... &gt;&gt;&gt; result {'ENSG1': ['1:24', '2:56', '3:47', '4:68', '5:89'], 'ENSG2': ['1:25', '2:57', '3:48', '4:69', '5:90'], 'ENSG3': ['1:26', '2:58', '3:49', '4:70', '5:91']}
type: Answer
has comment: http://stackoverflow.com/comment/85168023
upvote count: 2
has comment: http://stackoverflow.com/comment/85168125
has comment: http://stackoverflow.com/comment/85344922
downvote count: 1
has comment: http://stackoverflow.com/comment/85168038
score: 1
answers question: http://stackoverflow.com/q/49061865
has comment: http://stackoverflow.com/comment/85167775

http://stackoverflow.com/comment/85018352
type: AnswerComment
type: Comment
has text: I posted the text data in comment section, however it is coming in proper format. `playerID, yearID, gameNum, gameName, teamName, lgID, GP, startingPos gomezle01 1933, 1, Cricket, Team1, NYA, AL, 1 ferreri01, 1933 2, Hockey, "This is Team2", BOS, AL, 1 gehrilo01, 1933, 3 "Game name is Cricket" , Team3, NYA, AL, 1 gehrich01, 1933, 4, Hockey "Here it is Team4", DET, AL, 1 dykesji01, 1933, 5, "Game name is Hockey" , "Team name Team5" CHA, AL, 1`
score: 0
comment on: http://stackoverflow.com/a/48971522

http://stackoverflow.com/comment/84989736
type: QuestionComment
comment on: http://stackoverflow.com/q/48991994
has text: The linked docs don't talk about most of the items you're setting in the dict you're passing as a transport. What gave you the idea you could set things like `max_retries` there?
score: 0
type: Comment

http://stackoverflow.com/comment/85182005
comment on: http://stackoverflow.com/q/49086827
score: 0
type: Comment
type: QuestionComment
has text: You could also write to 2 files and `tail -f` them.

http://stackoverflow.com/q/49113616
type: Question
has title: How to download file using Python?
score: 7
duplicate of: http://stackoverflow.com/q/22676
has comment: http://stackoverflow.com/comment/92715867
tagged with: get
has answer: http://stackoverflow.com/a/49113818
answer count: 3
linked to: http://stackoverflow.com/q/22676
downvote count: 0
favorite count: 0
tagged with: download
type: UnansweredQuestion
tagged with: python
has body: I'm completely new to Python, I want to download a file by sending a request to the server. When I type it into my browser, I see the CSV file is downloaded, but when I try sending a get request it does not return anything. for example: import urllib2 response = urllib2.urlopen('https://publicwww.com/websites/%22google.com%22/?export=csv') data = response.read() print 'data: ', data It does not show anything, how can I handle that? When I search on the web, all the questions are about how to send a get request. I can send the get request, but I have no idea of how the file can be downloaded as it is not in the response of the request. I do not have any idea of how to find a solution for that.
has comment: http://stackoverflow.com/comment/85232731
has answer: http://stackoverflow.com/a/49113904
has answer: http://stackoverflow.com/a/49113799
upvote count: 7
linked to: http://stackoverflow.com/q/16694907

http://stackoverflow.com/q/49007938
accepted answer: http://stackoverflow.com/a/49007977
downvote count: 0
answer count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/49008018
has answer: http://stackoverflow.com/a/49007966
has answer: http://stackoverflow.com/a/49008018
has answer: http://stackoverflow.com/a/49007977
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
has body: I have the following python dictionary of integers: {1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2: [3, 6, 13], 3: [1, 2, 3], 4: [13, 14, 15], 5: [3, 6], 6: [6, 13]} I would like to remove the number 6 from both the 5th and 6th entries to the dictionary. I know this is quite simple but I am new to python so all help appreciated. Thank you.
has answer: http://stackoverflow.com/a/49008153
type: Question
has title: Python removing specific values from a dictionary

http://stackoverflow.com/q/48985874
tagged with: python
has answer: http://stackoverflow.com/a/48991460
tagged with: seaborn
possible better answer: http://stackoverflow.com/a/48991460
type: AnsweredQuestion
has body: I am trying to plot a logarithmic plot using seaborn factorplot on a dataframe as follows import pandas as pd import matplotlib.pyplot as plt import seaborn as sns l1 = [0.476, 0.4427, 0.378, 0.2448, 0.13, 0.004, 0.012, 0.0933, 3.704e-05, 1.4762e-06, 4.046e-08, 2.99e-10, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] df = pd.DataFrame(l1, columns=["y"]) df.reset_index(inplace=True) g = sns.factorplot(x='index',y='y', data=df, aspect=2, size=8) g.fig.get_axes()[0].set_yscale('log') plt.grid(True,which="both",ls="--",c='gray') plt.show() I get the following figure. Even though I changed the Y-axis scale to log and used both the gridlines, the final figure doesnt have the log scale ticks. However, the same code when used with another set of values gives me the following figure. In this case, the minimum value is limited to 10^-7 l2 = [0.29, 0.111, 0.0285, 0.0091, 0.00045, 5.49759e-05, 1.88819e-06, 0.0, 0.0, 0.0] df = pd.DataFrame(l2, columns=["y"]) # same code as above Any idea where I am being wrong? Update 1 I follwed Diziet's answer and forced the major and minor ticks as follows g.ax.yaxis.set_minor_locator(tkr.LogLocator(base=10, subs='all')) g.ax.yaxis.set_minor_formatter(tkr.NullFormatter()) g.ax.set_yscale('log') g.ax.grid(True,which="both",ls="--",c='gray') But it still doesnt solve the problem
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84992288
has answer: http://stackoverflow.com/a/48994101
has title: Logarithmic Gridlines for Seaborn Factorplot
type: Question
upvote count: 4
answer count: 2
downvote count: 0
score: 4
favorite count: 0
linked to: http://stackoverflow.com/q/44078409
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48994101

http://stackoverflow.com/comment/85019151
comment on: http://stackoverflow.com/q/49007341
has text: what does 'not everything' mean? please be more precise. (did you try to `f.flush()` your out file from time to time?).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85077566
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49014843
score: 0
has text: Thanks for all the replies. I added the --password to the command line and it worked. I ventured in to the pexpect territory without much luck.

http://stackoverflow.com/q/49006368
has body: I am trying to store the output of the STOCH indicator in the dataframe, so that I can plot it later. Here is what I tried and what I got: stock['slowk'],stock['slowd']=STOCH(stock, 5, 3, 0, 3, 0, timeperiod=5,prices=[ 'high', 'low', 'close']) stock I got the following output: As you can see the values are not appearing or getting stored in the dataframe. Without storing the values I am getting the numbers respectively as: Kindly, let me know what way I can store the output in the dataframe. Editing Note: I am using the Abstract API and not the Function API
favorite count: 0
tagged with: python-2.7
tagged with: ta-lib
tagged with: pandas
has title: Ta-lib python STOCH indicator not storing data in dataframe
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
downvote count: 0

http://stackoverflow.com/q/48999145
tagged with: resampling
tagged with: python
linked to: http://stackoverflow.com/q/28136663
has body: I have a dataframe that looks like this: A B 2010-01-01 6.5 3.2 2010-02-01 7.2 np.Nan 2010-03-01 8.1 np.Nan 2010-04-01 4.3 5.6 2010-05-01 3.7 6.1 I want to upsample to days and forward fill values. But in the case of df['B'] I want the forward fill to stop where np.Nan values start. I'm looking for the following: A B 2010-01-01 6.5 3.2 2010-01-02 6.5 3.2 .... 2010-01-31 6.5 3.2 2010-02-01 7.2 np.Nan 2010-02-02 7.2 np.Nan .... 2010-02-28 7.2 np.Nan 2010-03-01 8.1 np.Nan 2010-03-02 8.1 np.Nan .... 2010-03-31 8.1 np.Nan 2010-04-01 4.3 5.6 2010-04-02 4.3 5.6 .... 2010-04-30 4.3 5.6 2010-05-01 3.7 6.1 2010-05-02 3.7 6.1 .... 2010-05-31 3.7 6.1 If I apply the following code: df['A'] = df['A'].resample('D').ffill() df['B'] = df['B'].resample('D').ffill() My results look like this: A B 2010-01-01 6.5 3.2 2010-01-02 6.5 3.2 .... 2010-01-31 6.5 3.2 2010-02-01 7.2 3.2 2010-02-02 7.2 3.2 .... 2010-02-28 7.2 3.2 2010-03-01 8.1 3.2 2010-03-02 8.1 3.2 .... 2010-03-31 8.1 3.2 2010-04-01 4.3 5.6 2010-04-02 4.3 5.6 .... 2010-04-30 4.3 5.6 2010-05-01 3.7 6.1 2010-05-02 3.7 6.1 .... 2010-05-31 3.7 6.1 df['B'] is filled with the 3.2 value from 2010-01-01 up through 2010-03-31 instead of "stopping' at 2010-01-31 and preserving the np.Nan from 2010-02-01 through 2010-03-31. I know I can do this using a very messy iterative process. But is there an easier way to do this i'm not seeing? Thanks.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49000183
tagged with: time-series
type: Question
score: 0
tagged with: pandas
answer count: 1
has title: Python Pandas Upsampling - Complex Issue Preserving Some np.Nans
has comment: http://stackoverflow.com/comment/85004484

http://stackoverflow.com/a/49078840
has comment: http://stackoverflow.com/comment/85164858
has body: As described in here, do not append to a dataframe inside a loop, as it is very inefficent. Rather do something like this: files = GetFiles('hand_texts') database = [] for hand_text in files: # as a sidenote, with contexts are helpful for these: with open('hand_texts/' + hand_text) as text: b=text.read() hands=b.split("\n\n\n\n\n") for i in range(1,len(hands)): try: hh = PokerStarsHandHistory(unicode(hands[i])) hh.parse() fold = FindFold(hh) if fold == 'showdown': for shower in GetShowers(hh): database.append(DataGenerator(hh,shower,hand_text,i)) print('Success in parsing iteration ' + str(i) + ' from file' + hand_text) except: print('PARSER ERROR ON ITERATION ' + str(i) + ' FROM FILE ' + hand_text + '') database.append(EmptyLine(hand_text,i)) pd.DataFrame(database).to_csv('database2.csv'))
accepted answer of: http://stackoverflow.com/q/49078705
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49078705
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/49033223
has comment: http://stackoverflow.com/comment/85071372
downvote count: 2
has body: Today I've chosen to learn a new language, Python. I have some knowledge in C. I started with Pythonista 3 on my iPad (was on the go), now I'm home, copied my code, and I have the following problem: #!/use/bin/python startNumber = 3 #1000329977989 endNumber = startNumber + 100 #int(input('Enter the ending number:')) numberToTest = startNumber string = '1 is prime!' print(string) string = '2 is prime!' print(string) string = '3 is prime!' print(string) while numberToTest &lt; endNumber -1: for numberToTest in range(startNumber, endNumber): testerRangeEnd = int(numberToTest**(1/2)) for tester in range(2, testerRangeEnd): if numberToTest % tester == 0: string = str(numberToTest) + ' is not prime!' print(string) numberToTest += 1 break if tester == testerRangeEnd - 1: string = str(numberToTest) + ' is prime!' print(string) print("Done!") Outputs: 1 is prime! 2 is prime! 3 is prime! Done! Why do the prints in the while loop not print? I don't get it at all... Miss my parenthesis, semicolons and brackets... :( Cheers /Leic
has comment: http://stackoverflow.com/comment/85071472
has answer: http://stackoverflow.com/a/49033424
answer count: 1
has comment: http://stackoverflow.com/comment/85071388
favorite count: 0
has comment: http://stackoverflow.com/comment/85071128
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85071193
has comment: http://stackoverflow.com/comment/85071436
has title: Python problems with print
upvote count: 0
has comment: http://stackoverflow.com/comment/85071443
type: Question
has comment: http://stackoverflow.com/comment/85071504
score: -2
has comment: http://stackoverflow.com/comment/85071203

http://stackoverflow.com/q/49091310
tagged with: sockets
tagged with: python
answer count: 0
score: 1
upvote count: 1
has body: Assuming you have 2 routers and each uses an IP address of the form 192.168.0.1/24 which means their respective broadcast are of the form 192.168.0.255 and you are connected to both using either Ethernet and Wi-Fi or two Wi-Fi adapters. Then my question is, using python inbuilt socket module how would you broadcast to both adapters either by looping or silmutaneously given when I broadcast it's going through only one interface. Even better would be to choose to which adapter to broadcast to since all have same broadcast I'd. Thanks
type: Question
has comment: http://stackoverflow.com/comment/86111269
has title: Python socket broadcast with similar broadcast address
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85162973
type: Comment
has text: I think it looks nicer too, and it's ever so slightly more efficient. And it helps you learn something new
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49078377

http://stackoverflow.com/a/49105761
has body: It seems that your local network status can not resolve the host name. Maybe be you can try to install that from source, below is my step: 1:Download the source code: https://pypi.python.org/pypi/openpyxl 2:Build and install: python3.6 setup.py install 3:Output: ......... creating dist creating 'dist/openpyxl-2.5.0-py3.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing openpyxl-2.5.0-py3.6.egg creating /usr/local/lib/python3.6/dist-packages/openpyxl-2.5.0-py3.6.egg Extracting openpyxl-2.5.0-py3.6.egg to /usr/local/lib/python3.6/dist-packages Adding openpyxl 2.5.0 to easy-install.pth file Installed /usr/local/lib/python3.6/dist-packages/openpyxl-2.5.0-py3.6.egg Processing dependencies for openpyxl==2.5.0 Searching for et-xmlfile==1.0.1 Best match: et-xmlfile 1.0.1 Adding et-xmlfile 1.0.1 to easy-install.pth file Using /usr/local/lib/python3.6/dist-packages Searching for jdcal==1.3 Best match: jdcal 1.3 Adding jdcal 1.3 to easy-install.pth file Using /usr/local/lib/python3.6/dist-packages Finished processing dependencies for openpyxl==2.5.0 4:Import and using: Python 3.6.3 (default, Oct 6 2017, 08:44:35) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from openpyxl import Workbook &gt;&gt;&gt;
upvote count: 5
has comment: http://stackoverflow.com/comment/92629457
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49105344
downvote count: 0
answers question: http://stackoverflow.com/q/49105344
type: Answer
has comment: http://stackoverflow.com/comment/114233335
score: 5
has comment: http://stackoverflow.com/comment/85338028

http://stackoverflow.com/comment/85060717
has text: @asongtoruin - good idea, thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49028130
type: AnswerComment

http://stackoverflow.com/comment/85167956
comment on: http://stackoverflow.com/q/49081114
has text: @johnashu What are you talking about? You can't name something yield, it would be syntax error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48990989
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48988114
answers question: http://stackoverflow.com/q/48988114
type: AcceptedAnswer
downvote count: 0
has body: You can concatenate videos horizontally or vertically or in a grid to a single video file using ffmpeg or manually in python. You can use ffmpeg outside python to concatenate videos into single video and show as a single video: Vertically stack several videos using ffmpeg? Or you can make a single video by concatenating those videos horizontally or vertically in python itself. e.g. use scikit-video or opencv to load videos into different arrays and concatenate horizontally or vertically or in grid and save as a single video.
type: Answer

http://stackoverflow.com/comment/85128572
has text: What's wrong using `d = data[0]` ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49061655
type: QuestionComment

http://stackoverflow.com/a/49012243
answers question: http://stackoverflow.com/q/49012051
type: Answer
has comment: http://stackoverflow.com/comment/85042106
has comment: http://stackoverflow.com/comment/85041107
has comment: http://stackoverflow.com/comment/85041195
has comment: http://stackoverflow.com/comment/85042053
score: 0
has body: Here is one solution: import pandas as pd df = pd.DataFrame({'Acc':[1,2,4,2,1,3],'Event':list('ABCACA'),'exit':[0,1,1,1,0,0]}) df2 = df.groupby(['Acc', 'exit'])['Event'].apply(list).reset_index() df2 = df2.join(pd.get_dummies(df2['Event'].apply(pd.Series).stack()).sum(level=0))\ .drop('Event', 1) # Acc exit A B C # 0 1 0 1 0 1 # 1 2 1 1 1 0 # 2 3 0 1 0 0 # 3 4 1 0 0 1
has comment: http://stackoverflow.com/comment/85041940

http://stackoverflow.com/q/49014725
has comment: http://stackoverflow.com/comment/85035293
has comment: http://stackoverflow.com/comment/85034371
tagged with: python
has body: I am seeing this error from python code inside 6.8centos container request = &lt;SubRequest 'test_dir_resource_creation' for &lt;Function 'test_instance_creation'&gt;&gt; @pytest.fixture(scope="session", autouse=True) def test_dir_resource_creation(request): """Create the test environment based on local or br env.""" &gt; user = os.getlogin() E OSError: [Errno 25] Inappropriate ioctl for device tests/conftest.py:16: OSError I read something online that it may be due to missing of mod_wsgi rpm so I've installed it but still no luck. Is it possible for docker to have tty to for the above python code to work?
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/85035453
has comment: http://stackoverflow.com/comment/85035236
has title: docker python app failure: OSError: [Errno 25] Inappropriate ioctl for device
tagged with: docker
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/49068673
type: Answer
has body: use QListWidget.clear() and it Removes all items and selections in the view. for am more selective approuch you can use QListWidget.takeItem( index ), it Removes and returns the item from the given row in the list widget Official Docs: clear() Official Docs: takeItem()
has comment: http://stackoverflow.com/comment/130741107
upvote count: 26
accepted answer of: http://stackoverflow.com/q/49068100
score: 26
answers question: http://stackoverflow.com/q/49068100
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49007816
tagged with: tensorflow
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49010525
type: Question
tagged with: deep-learning
answer count: 1
downvote count: 0
has title: image data go beyond 0-1 range after processing
favorite count: 0
tagged with: python
has body: I am randomly adjusting brightness, saturation etc. of an image. But after adjustment, img_data has value beyond 0-1, such that imshow will not work. tf.InteractiveSession() image_raw_data=tf.read_file('C:/Users/User/PycharmProjects/Neural_Network\\cat.jpg') sess=tf.Session() img_data=tf.image.decode_jpeg(image_raw_data,channels=3) img_data=tf.image.convert_image_dtype(img_data,dtype=tf.float32) img_data=tf.image.resize_images(img_data,[300,300],method=0) img_data=tf.image.random_brightness(img_data,max_delta=32/255) plt.imshow(img_data.eval()) The error is: ValueError: Floating point image RGB values must be in the 0..1 range. May I know how should I properly transform the image so that it can be shown?
has answer: http://stackoverflow.com/a/49010525
score: 2
upvote count: 2
tagged with: image-processing

http://stackoverflow.com/q/49088365
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/49088468
upvote count: 1
tagged with: svm
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49088468
has title: SVM Algorithm: Without using sklearn package (Coded From the Scratch)
has comment: http://stackoverflow.com/comment/85188836
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: classification
has body: I'm trying to code SVM algorithm from the scratch without using sklearn package, now I want to test the accuracy score of my X_test and Y_predict. The sklearn had already function for this: clf.score(X_test,Y_predict) Now, I traced the code from the sklearn package, I cannot find how the 'score' function has coded from the scratch. And how the model generated from the sklearn SVC: SVM classifier :: SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma=2, kernel='poly', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) After I fitted and trained the dataset, I want that the model will be generated so that I can Save and Load it using Pickle.

http://stackoverflow.com/a/59607117
score: 18
type: Answer
downvote count: 1
upvote count: 19
has body: This is the easiest solution. You can load the data without even downloading the file locally using S3FileSystem from s3fs.core import S3FileSystem s3_file = S3FileSystem() data = pickle.load(s3_file.open('{}/{}'.format(bucket_name, file_path)))
answers question: http://stackoverflow.com/q/48964181
has comment: http://stackoverflow.com/comment/134050270

http://stackoverflow.com/comment/85439109
comment on: http://stackoverflow.com/a/49093993
score: 0
has text: Yes exactly. Maybe I've done it wrong, but it is supposed to be a key value dictionary.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49061687
has body: I always like to present the defaultdict solution from collections import defaultdict d = defaultdict(list) for k, v in zip(s1, s2): d[k].append(v) dict(d) {'A': ['1', '2'], 'B': ['2']}
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49061542
upvote count: 1

http://stackoverflow.com/a/49001628
type: Answer
has body: You can try this. # Step 1 df_m = df2.merge(df1, on="Group", how="outer") # Step 2 df_m["diff"] = df_m["randomnumbers"] - df_m["ProbabilityBrackets"] # Step 3 df_m_filtered = df_m[df_m["diff"] &lt; 0].set_index( ["Destination", "ProbabilityBrackets"]) # Step 4 df_desired = df_m_filtered.groupby( ["Group", "randomnumbers"])["diff"].nlargest(1).reset_index() index Group randomnumbers Destination ProbabilityBrackets diff 0 0 test 0.20 A 0.50 -0.30 1 1 test 0.78 C 1.00 -0.22 2 2 train 0.15 AA 0.75 -0.60 3 3 train 0.35 AA 0.75 -0.40 Explanation: Begin with an outer merge Calculate differences between randomnumbers and ProbabilityBrackets Filter the results with condition df_merged["diff"] &lt; 0 as we are interested in finding those whose randomnumbers is smaller than ProbabilityBrackets Groupby ["Group" and "randomnumbers"] and find the one with the largest diff within each group.
score: 1
has comment: http://stackoverflow.com/comment/85037479
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48999007
has comment: http://stackoverflow.com/comment/85039442
answers question: http://stackoverflow.com/q/48999007
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49010952
tagged with: multithreading
type: Question
score: 0
tagged with: kubernetes
answer count: 1
has title: Distribute ssh connections made by Django App (multi-threaded python function) among n number of Kubernetes Replicas
has answer: http://stackoverflow.com/a/49011385
type: UnansweredQuestion
tagged with: ssh
tagged with: django
tagged with: python
has body: My Django App makes SSH connections to n number of machines (using a multithreaded python function). When replica=n is set in kubernetes deployment.yaml file then I want my app to distribute the connections among the n replicas. I mean 1 replica should connect to k number machines, another to next k number of machines and so on. When all the replicas are done then it should take the connections in cyclic fashion i.e. next k connections to first machine and another next k to other machine. I tried with 2 replicas but all the connections are getting established by both the pods (replicas). I want those connections to be distributed among the pods. How can I achieve this?

http://stackoverflow.com/a/48982173
answers question: http://stackoverflow.com/q/48981651
type: AcceptedAnswer
downvote count: 0
has body: What you really need is to group your data by the common keys. itertools.groupby is made for this, and you can use operator.itemgetter to group by the key elements of each sublist. Once iterating over the groups, tracking the respective sum and maximum you need is not hard. This does assume that you intend on keeping the maximum and not removing the minimum, as having more than 2 elements in a group would make this impossible to do while summing the second elements. from itertools import groupby from operator import itemgetter def merge(data): out_data = [] for _, group in groupby(data, key=itemgetter(0, 2)): key_num, to_sum, key_name, to_max = next(group) for _, sum_val, _, max_val in group: to_sum += sum_val to_max = max(to_max, max_val) out_data.append([key_num, to_sum, key_name, to_max]) return out_data Demo &gt;&gt;&gt; a = [[1234,32.5,'John',1114], [1234,16.3,'John',1115], [1235,25.3,'John',1116], [1239,16.3,'Lisa',1117]] &gt;&gt;&gt; merge(a) [[1234, 48.8, 'John', 1115], [1235, 25.3, 'John', 1116], [1239, 16.3, 'Lisa', 1117]] It is also worth noting that if you have many operations to apply to tabular data like this, you may want to look into the Pandas library. Using Pandas, a succinct solution to your problem could be import pandas as pd def pd_merge(data): df = pd.DataFrame(data) return (df.groupby((0, 2), as_index=False) .agg({1: 'sum', 3: 'max'}) .sort_index(1))
accepted answer of: http://stackoverflow.com/q/48981651
type: Answer
has comment: http://stackoverflow.com/comment/84969471
score: 1
upvote count: 1

http://stackoverflow.com/a/49129877
accepted answer of: http://stackoverflow.com/q/49106336
has comment: http://stackoverflow.com/comment/120875688
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: Perhaps you're using an outdated miniconda on one of the build machine, try doing docker build --pull --no-cache. Docker doesn't necessarily pull the latest image from the repository, so unless you do a --pull, it is possible that some of your machines may be starting the build with outdated base image.
upvote count: 2
answers question: http://stackoverflow.com/q/49106336

http://stackoverflow.com/comment/85223321
type: QuestionComment
score: 0
has text: Your DF says that delimiter is `\001` whereas your sample data's delimiter appears to be `\t`. Which one is the correct delimiter?
comment on: http://stackoverflow.com/q/49108541
type: Comment

http://stackoverflow.com/a/49048095
accepted answer of: http://stackoverflow.com/q/49036162
upvote count: 1
has body: driver.window_handles returns a list of all opened windows. Just tried switch_to.window() and it raised error because it needs only one name and not a list. If jquery generates actual browser window you can switch to the popup window by its name/title if it has one: driver.switch_to.window("Alert popup!") In the situation when the current and popup windows have equal titles I use something like this: current_window = driver.current_window_handle _handles = driver.window_handles &lt;popup opening button&gt;.click() WebDriverWait(driver, timeout).until( expected_conditions.new_window_is_opened(_handles)) try: #find new window handle popup_window = (h for h in driver.window_handles if h != current_window).next() except StopIteration: raise Exception("No popup!") If jquery generates some popup-styled &lt;div&gt; (not browser window), so you just locate it like any other element on the page with driver.find_element_by_&lt;...>
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49036162
type: Answer
score: 1

http://stackoverflow.com/q/49071772
tagged with: stdout
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49108061
tagged with: stdin
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85156885
has comment: http://stackoverflow.com/comment/85158020
tagged with: python
tagged with: subprocess
downvote count: 0
score: 1
type: Question
tagged with: nonblocking
has title: Non-blocking read on subprocess output without flush() and new line
has body: I have a program that I can't modify. This program print data to stdout WITHOUT flushing it or put \n inside and wait for input and so on. My question is how can I, from a Python script, print in real-time stdout and write into his stdin? I found some ways to write into his stdin without closing the programs but the problem remains for printing his stdout too. In fact, there are some issues with thread, Popen and fcntl to print in real time his output but they all assumes that the program flush stdout after each print and include \n in their output. To be clear, let's say I have a program test.c: #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main (void) { char name[100], age[100], location[100]; fprintf (stdout, "\nWhat is your name : "); fgets (name, sizeof (name), stdin); name[strcspn (name, "\n")] = '\0'; fprintf (stdout, "How old are you : "); fgets (age, sizeof (age), stdin); age[strcspn (age, "\n")] = '\0'; fprintf (stdout, "Where do you live : "); fgets (location, sizeof (location), stdin); location[strcspn (location, "\n")] = '\0'; fprintf (stdout, "\nHello %s, you have %s years old and live in %s\n\n", name, age, location); return 0; } How can I, from a Python script, output the first fprintf() then writing answer into his stdin and so on in the same way I could simply launch test.c? The purpose is to control data sent to this program from a script and still having return on what happens.

http://stackoverflow.com/comment/85080684
comment on: http://stackoverflow.com/q/49036453
type: Comment
type: QuestionComment
has text: Why do you need each of the floats to be in its own `ndarray`? It doesn't make much sense. `data.tolist()` will convert that array into a list of lists. You could then iterate through the list and turn the sublists into tuples.
score: 0

http://stackoverflow.com/q/49092122
has answer: http://stackoverflow.com/a/49092214
possible better answer: http://stackoverflow.com/a/49092193
accepted answer: http://stackoverflow.com/a/49092214
has answer: http://stackoverflow.com/a/49092193
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has body: I have 3 lists : Names=["Jack","Jeni","Monsa","Mehus","Kuis","Tim","Tony","Yestgf","Pere"] Years=[17,20,26,40,67,88,96,99,37] Order=[1,2,3,4,5,6,7,8,9] I'm trying to extract names from Names list using the order in Order list, it starts from Jack Jack and the 2nd set starts from Jeni Jeni (its not duplicate entry here , just to show that the entry starts from its own) Jack Jack Jack Jeni Jack Monsa Jack Mehus Jack Kuis Jack Tim Jack Tony Jack Yestgf Jack Pere Jeni Jeni Jeni Monsa Jeni Mehus Jeni Kuis Jeni Tim Jeni Tony Jeni Yestgf Jeni Pere Jeni Jack I have written code as: Names=["Jack","Jeni","Monsa","Mehus","Kuis","Tim","Tony","Yestgf","Pere"] Years=[17,20,26,40,67,88,96,99,37] Order=[1,2,3,4,5,6,7,8,9] for names,years,orders in zip(Names,Years,Order): for i in range(1,(len(Order)+1)): for j in range(i,i+len(Order)): jdisplay = Names[j % len(Order)] if (j % len(Order)) else Names[j] print(names,Names[j]) I am getting the following error: Traceback (most recent call last): Jack Jeni File "C:/Users/Administrator/PycharmProjects/Tesrt/forumsquestion.py", line 7, in &lt;module&gt; Jack Monsa Jack Mehus Jack Kuis Jack Tim Jack Tony Jack Yestgf Jack Pere jdisplay = Names[j % len(Order)] if (j % len(Order)) else Names[j] IndexError: list index out of range Process finished with exit code 1 I'm lost somewhere, is this right way of extracting the data from zipped lists? Update: The code given by William Feirie is working fine, however the 4th level entry seems to be going weird Names=["Jack","Jeni","Monsa","Mehus","Kuis","Tim","Tony","Yestgf","Pere"] Years=[17,20,26,40,67,88,96,99,37] Order=[1,2,3,4,5,6,7,8,9] print(len(Names),len(Years),len(Order)) for idx,name in enumerate(Names): for idx in range(idx,idx+len(Names)): for idy in range(idx,idx+len(Names)): for idz in range(idx,idx+len(Names)): print(name,Names[idx%len(Names)],Names[idy%len(Names)],Names[idz%len(Names)]) Output: Jack Jack Jack Jack Jack Jack Jack Jeni Jack Jack Jack Monsa Jack Jack Jack Mehus Jack Jack Ja…
tagged with: python
has title: Accessing data in zip - Index out of range - Python
answer count: 2
upvote count: 1

http://stackoverflow.com/q/49045444
tagged with: list
has body: I am trying to find tuples in a list with a certain symbol at the 2nd position. The list looks something like this: list = [ (0, "a", 1), (1, "b", 2), (2, "c", 3)] I can obviously find all the tuples with e.g. a "c" by running the following code: for item in list: if item[1] == "c": return item I was just wondering if I could combine line1 and line2 of the above given code to do something like for (numb1, symbol=="c", numb2) in list: return (numb1, symbol, numb2) Does anyone know if there is a shortcut for this? Thank you!
has comment: http://stackoverflow.com/comment/85097220
upvote count: 1
downvote count: 1
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/49045691
has comment: http://stackoverflow.com/comment/85095463
score: 0
has answer: http://stackoverflow.com/a/49045491
has comment: http://stackoverflow.com/comment/85095798
has answer: http://stackoverflow.com/a/49045613
has answer: http://stackoverflow.com/a/49046813
has title: check element of tuple at certain position - shortcut?
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/49045685
has comment: http://stackoverflow.com/comment/85097716
answer count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85096073

http://stackoverflow.com/a/49075333
type: Answer
answers question: http://stackoverflow.com/q/49075226
accepted answer of: http://stackoverflow.com/q/49075226
score: 5
upvote count: 5
downvote count: 0
has body: From the looks of that output, that's probably not the code you really ran. You probably wrote Foo.__dict__ in an IPython interactive session. IPython automatically sorts the keys of dicts and mappingproxy objects when displaying them. (This was eventually changed in IPython 5.6 so IPython no longer sorts dict keys on Python 3.6+.)
type: AcceptedAnswer

http://stackoverflow.com/q/48972115
tagged with: sha256
tagged with: rsa-sha256
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/84959544
tagged with: pycrypto
has body: I installed Crypto module and SHA256 but showing ModuleNotFoundError :- Traceback (most recent call last): File "Digitalsig.py", line 1, in from Crypto.Hash import SHA256 ModuleNotFoundError: No module named 'Crypto' Here is the refrence code from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto import Random random_generator = Random.new().read #used to generate a keypair which contain a public and private key keyPair = RSA.generate(1024,random_generator) pubKey = keyPair.publicKey() plainText = 'Hello World' hashA = SHA256.new(plainText).digest() digitalSignature = keyPair.sign(hashA,'') print("Hash A: "+repr(hashA) + "\n"); print("Digital Signature: " + repr(digitalSignature) + "\n") #Bob receives the plainText and digitalSignature from Alice #plainTextChanged ='Hello World' hashB =SHA256.new(plainText).digest() print("Hash B: " + repr(hashB) + "\n") if(pubKey.verify(hashB, digitalSignature)): print("Match") else: print("No Match")
type: Question
has answer: http://stackoverflow.com/a/48972144
score: 5
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84949435
upvote count: 8
tagged with: python
tagged with: cryptography
has title: ModuleNotFoundError: No module named 'Crypto'

http://stackoverflow.com/a/49060316
answers question: http://stackoverflow.com/q/49060262
upvote count: 2
has body: You need to iterate through the array, looking to see whether the target word, school is in that array element. Then drop the index into your list. final_array = [i for i in range(len(array)) if "school" in array[i]] Output: [0, 1] Your original attempt didn't do that: index could find the location of school in a sentence, not the location of the sentence containing school in the array. Improvement with more Pythonic technology: [i for i, phrase in enumerate(array) if "school" in phrase]
type: Answer
has comment: http://stackoverflow.com/comment/85125831
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85125796

http://stackoverflow.com/comment/84954886
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48975017
has text: note that `tuple1 += tuple2` also creates a new reference.

http://stackoverflow.com/comment/85164381
type: Comment
has text: @Jota I updated my answer to include more information
comment on: http://stackoverflow.com/a/49078835
score: 0
type: AnswerComment

http://stackoverflow.com/q/48981557
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/48981785
has title: How to add and Rename (No Header) Column in dataframe
accepted answer: http://stackoverflow.com/a/48981580
type: Question
has answer: http://stackoverflow.com/a/48981580
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/48981785
favorite count: 0
tagged with: pandas
has body: I have a pandas.DataFrame without a header like this: 0 1 2 3 4 5 MAC ID1 1 1 2 3 3 4 ID2 6 6 7 7 8 9 ID3 1 2 3 3 4 5 I want to add column header with following "data" names. My expected results look like this: Data_1 Data_2 Data_3 Data_4 Data_5 Data_6 MAC ID1 1 1 2 3 3 4 ID2 6 6 7 7 8 9 ID3 1 2 3 3 4 5 I have hundred thousand columns and I want to edit all of the columns, please give a better way to edit this data.

http://stackoverflow.com/q/49040100
has title: Python print lines after context
has body: How can I print two lines after the context i am interest in using python. Example.fastq @read1 AAAGGCTGTACTTCGTTCCAGTTG + '(''%$'))%**)2+'.(&amp;&amp;'/5- @read2 CTGAGTTGAGTTAGTGTTGACTC + )(+-0-2145=588..,(1-,12 I can find the context of interest using... fastq = open(Example.fastq, "r") IDs = [read1] with fastq as fq: for line in fq: if any(string in line for string in IDs): Now that I have found read1 I want to print out the the following lines for read1. In bash i might use something like grep -A to do this. The desired output lines look like the following. + '(''%$'))%**)2+'.(&amp;&amp;'/5- But in python i cant seem to find an equivalent tool. Perhaps "islice" might work but I don't see how I can get islice to start at the position of the match. with fastq as fq: for line in fq: if any(string in line for string in IDs): print(list(islice(fq,3,4)))
possible better answer: http://stackoverflow.com/a/49068138
has answer: http://stackoverflow.com/a/49068138
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49040228
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85085704
tagged with: grep
tagged with: python
score: 1
tagged with: fasta
has comment: http://stackoverflow.com/comment/85086248
tagged with: bioinformatics
upvote count: 1
has answer: http://stackoverflow.com/a/49040228
tagged with: fastq
type: AnsweredQuestion

http://stackoverflow.com/comment/84942639
type: Comment
type: QuestionComment
has text: Can you add some sample data for the business names (or make some up if you don't want to name any real companies, just as long as the format of the data matches what you are seeing)
comment on: http://stackoverflow.com/q/48968376
score: 0

http://stackoverflow.com/comment/85266070
has text: Thanks modelmat, I got confused between key,value,k and v 's! feeling slightly 'stoopid' now
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49121613

http://stackoverflow.com/q/49101545
has comment: http://stackoverflow.com/comment/85228631
type: Question
has title: How to normalize dataframe by standard deviation using scikit-learn?
score: 5
has answer: http://stackoverflow.com/a/49101596
has body: Given the following dataframe and left-x column: | | left-x | left-y | right-x | right-y | |-------|--------|--------|---------|---------| | frame | | | | | | 0 | 149 | 181 | 170 | 175 | | 1 | 149 | 181 | 170 | 175 | | 2 | 149 | 181 | 170 | 175 | | 3 | 149 | 181 | 170 | 175 | how may I normalize left-x by standard deviation using scikit-learn library?
upvote count: 5
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49111835
has comment: http://stackoverflow.com/comment/85208832
has comment: http://stackoverflow.com/comment/85227666
tagged with: python
tagged with: sklearn-pandas

http://stackoverflow.com/comment/84976976
type: QuestionComment
has text: *but it didnt work*... What does it mean? Exception?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48986204

http://stackoverflow.com/comment/112953493
type: AnswerComment
has text: +1 for a beautiful generic and scalable solution, which is exactly what makes this solution applicable to my own coding project. Thank you, @OlivierMelançon!
type: Comment
comment on: http://stackoverflow.com/a/49039168
score: 0

http://stackoverflow.com/comment/85375090
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49097295
has text: I actually could make it show only the right hand size setting `lon_minmax` to (-90,90), but that did not work well for (90,270) for instance. Do you know if this some limitation? Also, how could I add parasitic X and Y axes with real rectangular X and Y ticks?

http://stackoverflow.com/comment/85102672
comment on: http://stackoverflow.com/a/49048501
type: AnswerComment
score: 0
type: Comment
has text: @Lundin Corrected ... I was going by the OP's question

http://stackoverflow.com/comment/85056230
score: 0
has text: I can install google.cloud.datastore to my pipeline.but another error occured.(add error messaget to my question)
comment on: http://stackoverflow.com/q/48990784
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84998046
type: Comment
type: QuestionComment
score: 2
has text: This is connected component analysis. There are a million and one algorithms for it out there. [YACCLAB](http://imagelab.ing.unimore.it/yacclab) collects and compares the most prominent algorithms. That is probably a good resource to read about the concepts.
comment on: http://stackoverflow.com/q/48996148

http://stackoverflow.com/a/49029637
has comment: http://stackoverflow.com/comment/85067617
upvote count: 1
type: Answer
has body: You can define a function for creating the Label and Entry with the given parameters: def make_entry(frame, text, variable, row, col1, col2): font = ('arial',16,'bold') label = Label(frame, font=font, text=text, bg='powder blue', bd=19, anchor='w') label.grid(row=row, column=col1) entry = Entry(frame, font=font, textvariable=variable, bg='powder blue', bd=10, insertwidth=4, justify='right') entry.grid(row=row, column=col2) Then, just call that function for your different candies. make_entry(f1, "Twix", Twix, 2, 0, 1) make_entry(f1, "Snickers", Snickers, 4, 0, 1) ... You might also have the function return label, entry if you need those later on, but it seems like the variables are enough. The parameters in the second group are a bit different: Larger font size, thicker borders, different shades of blue. You could either make those additional parameters to the function, or create a second function for those buttons similar to the first. Alternatively, you could also just create two loops instead of defining a function. Particularly if the differences between the first and the second group of entries are more significant this may be simpler than using two very similar functions, or one function with very many parameters. candies = [("Twix", Twix), ("Snickers", Snickers), ("Mars Bar", MarsBar), ("Godiva", Godiva)] font = ('arial',16,'bold') for i, (name, var) in enumerate(candies, start=1): label = Label(f1, font=font, text=name, bg='powder blue', bd=19, anchor='w') label.grid(row=2*i, column=0) entry = Entry(f1, font=font, textvariable=var, bg='powder blue', bd=10, insertwidth=4, justify='right') entry.grid(row=2*i, column=1) Also, unrelated to the actual problem, DoubleVar does not seem to be a sensible choice for a countable quantity like chocolate bars. Are your users supposed to be able to buy 3.14 Mars bars? Instead, I'd suggest using IntVar. About your "revised code": There are two problems: First, the use of the function make_entry(f1, ...) should not be inside…
has comment: http://stackoverflow.com/comment/85104911
has comment: http://stackoverflow.com/comment/85068958
has comment: http://stackoverflow.com/comment/85105308
answers question: http://stackoverflow.com/q/49029457
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85103358
has comment: http://stackoverflow.com/comment/85064777
accepted answer of: http://stackoverflow.com/q/49029457
has comment: http://stackoverflow.com/comment/85068935
has comment: http://stackoverflow.com/comment/85071681
has comment: http://stackoverflow.com/comment/85066782
has comment: http://stackoverflow.com/comment/85063666
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85104059
has comment: http://stackoverflow.com/comment/85069307
has comment: http://stackoverflow.com/comment/85103843
has comment: http://stackoverflow.com/comment/85102938

http://stackoverflow.com/comment/126732674
type: Comment
comment on: http://stackoverflow.com/a/57180795
has text: `A_gpu = csr_gpu(A)` give me `ValueError: Only bool, float32, float64, complex64 and complex128 are supported`.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85171284
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49083021
score: 0
has text: Well, as far as I know a dict has EXACTLY one entry per key. And here I have several (one for each DateFrom/DateTo pairs)

http://stackoverflow.com/a/49058750
has comment: http://stackoverflow.com/comment/85123000
has comment: http://stackoverflow.com/comment/85124576
accepted answer of: http://stackoverflow.com/q/49057890
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85125406
downvote count: 0
answers question: http://stackoverflow.com/q/49057890
has comment: http://stackoverflow.com/comment/98142737
has comment: http://stackoverflow.com/comment/85126055
type: Answer
score: 2
has body: release_pan or release_zoom are callbacks. Those are the functions which are called once the conditions of the user releasing the mouse in pan or zoom mode are satisfied. You cannot connect them, but you may connect to them and of course you may call them if needed. The possible events to connect are listed in the documentation. They are events = ['resize_event', 'draw_event', 'key_press_event', 'key_release_event', 'button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event', 'pick_event', 'idle_event', 'figure_enter_event', 'figure_leave_event', 'axes_enter_event', 'axes_leave_event', 'close_event'] Since there is no such thing as a "release_zoom_event", this can also not be connected. But.. you may create this "release_zoom_event" yourself, if needed. This is essentially described in matplotlib hooking in to home/back/forward button events for the "home" button. Adapting that example to the "release_zoom_event" would look like this: import matplotlib.pyplot as plt from matplotlib.backend_bases import NavigationToolbar2 release_zoom = NavigationToolbar2.release_zoom def new_release_zoom(self, *args, **kwargs): s = 'release_zoom_event' self.canvas.callbacks.process(s, args[0]) release_zoom(self, *args, **kwargs) NavigationToolbar2.release_zoom = new_release_zoom def handle_release_zoom(evt): print('release_zoom_event') print(evt.xdata,evt.ydata) fig = plt.figure() fig.canvas.mpl_connect('release_zoom_event', handle_release_zoom) plt.plot([1,3,1]) plt.show()
upvote count: 2

http://stackoverflow.com/comment/85078957
comment on: http://stackoverflow.com/a/49034672
type: AnswerComment
score: 0
type: Comment
has text: Yup, this does it! I was looking into the stream editing IO Tools, but your method worked in the exact way I wanted. Thanks Mike.

http://stackoverflow.com/a/48986390
has body: Not at all sure that I understood it right, I tried to base my answer on the equation. Even if it is still a bit of from the result you expect, it might help you to solve your issue. I create a result list to store each value of L[t], i.e. 50 values. Then I compute the start / stop of the sum for every couple (t,i) and compute it. import numpy as np years = np.arange(50) m_ = [50, 30, 15] a = [25, 15, 7.5] ARC_ = [38, 255, 837] r = 0.03 result = [] for t in years: s = 0 for i in range(3): t0 = t tf = t + m_[i]-a[i] for k in range(int(t0), int(tf+1)): s += ARC_[i] / (1+r) ** t result.append(s) If what you wanted to do is to compute the difference element-wise between m and a, a simple solution is: [m_[i] - a[i] for i in range(len(m_))] Hope it helps.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48985751
answers question: http://stackoverflow.com/q/48985751
type: Answer
score: 0

http://stackoverflow.com/a/48995228
has body: Unwrap the outer list from each entry, then use the vectorized .values.tolist(), then pass into a DataFrame constructor and rename: pd.DataFrame(df['col1'].apply(lambda x: x[0]).values.tolist()).rename(columns=lambda x: 'col{}'.format(x+1))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48995018

http://stackoverflow.com/q/49003983
favorite count: 0
has answer: http://stackoverflow.com/a/49004020
has body: Very popular answer but my one differs from others. I have a list: s = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] I need without another lists combine my lists inside and make one big list. I need them to be string so I do [map(str, x) for x in s] But in this way I get [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] So I need ['1', '2', '3', '4', '5', '6', '7', '8', '9']
has answer: http://stackoverflow.com/a/49004045
has title: How to reformat variables in lists in list to make one list
tagged with: python
has answer: http://stackoverflow.com/a/49004598
has answer: http://stackoverflow.com/a/49004002
downvote count: 1
linked to: http://stackoverflow.com/q/5436503
accepted answer: http://stackoverflow.com/a/49004002
linked to: http://stackoverflow.com/q/952914
tagged with: combinations
type: AnsweredQuestion
tagged with: list
upvote count: 5
has answer: http://stackoverflow.com/a/49004030
has comment: http://stackoverflow.com/comment/85012334
type: Question
has answer: http://stackoverflow.com/a/49011320
possible better answer: http://stackoverflow.com/a/49004045
answer count: 6
score: 4

http://stackoverflow.com/comment/85243129
type: QuestionComment
has text: I tried that. Every item in the list is a string, and if i set the deliminter flag to \t it splits every character in every item for the list.
comment on: http://stackoverflow.com/q/49118619
score: 0
type: Comment

http://stackoverflow.com/a/49117225
has body: If you just want it to wait 5 seconds just sleep for 5 seconds after the loop has run. Adding REDRESET is as simple as having another elif from time import sleep while RedScore &lt;= 5 and BlueScore &lt;= 5: if RedScore == 5: print('RED WINS') sleep(5) RedScore = BlueScore = 0 elif BlueScore == 5: print('BLUE WINS') sleep(5) BlueScore = RedScore = 0 else: x = input("Who Scored? ") if x == 'Red': RedScore += 1 print(RedScore) elif x == 'Blue': BlueScore += 1 print(BlueScore) elif x == 'REDRESET': RedScore = 3 else: print('Bad Input')
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49117104
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49117104

http://stackoverflow.com/comment/85246989
type: QuestionComment
comment on: http://stackoverflow.com/q/49120065
score: 1
has text: If the content you are interested in extracting is not loaded dynamically, then I would be very surprised if the size of the content (quantity of information) is actually slowing you down...
type: Comment

http://stackoverflow.com/comment/84970914
has text: Ok, so what is `print (df1.to_dict())` ? Problem is correct DataFrame is incorrect written to file?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48982484
type: Comment

http://stackoverflow.com/a/52312661
has body: Unfortunately, it is not possible in Chrome. ChromeDriver disable rendering and CSS Chrome/chromedriver cannot run headless without some virtual screen like Xserver, and it can't not-render the html and css. Exhaustive list of all options that are allowed: profile.default_content_setting_values: cookies, images, javascript, plugins, popups, geolocation, notifications, auto_select_certificate, fullscreen, mouselock, mixed_script, media_stream, media_stream_mic, media_stream_camera, protocol_handlers, ppapi_broker, automatic_downloads, midi_sysex, push_messaging, ssl_cert_decisions, metro_switch_to_desktop, protected_media_identifier, app_banner, site_engagement, durable_storage
downvote count: 1
score: 3
answers question: http://stackoverflow.com/q/49031428
upvote count: 4
type: Answer

http://stackoverflow.com/a/49105279
score: 3
accepted answer of: http://stackoverflow.com/q/49105196
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Try data['class_size']['padded_csd'] = data["class_size"]["CSD"].apply(lambda x: str(x).zfill(2) if len(str(x)) == 1 else str(x) ) #Update else str(x)
answers question: http://stackoverflow.com/q/49105196
upvote count: 3
has comment: http://stackoverflow.com/comment/85215546

http://stackoverflow.com/q/49015210
score: 0
answer count: 2
tagged with: shell-exec
has comment: http://stackoverflow.com/comment/85035697
has body: i have a php file which have some variables para1 and para2 , i want to send them to a python file . this is my php file: &lt;?php $para1 = "one"; $para2 = "two"; echo "shell_exec(" /C:/xampp/htdocs/Ai_Edutech_trial_project/eclipse_workspace/Project /check.py '$para1' '$para2'")"; ?&gt; and this is my py file: import sys x=sys.argv[1] y=sys.argv[2] print(x) print(y) but this does not work for me. Can someone please help me with this or suggest some other way?
tagged with: sys
tagged with: python
tagged with: php
has answer: http://stackoverflow.com/a/49015302
has comment: http://stackoverflow.com/comment/85035947
has answer: http://stackoverflow.com/a/60622093
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12197815
possible better answer: http://stackoverflow.com/a/60622093
has comment: http://stackoverflow.com/comment/85035363
has comment: http://stackoverflow.com/comment/85036140
has title: passing php variable to python file
type: Question
has comment: http://stackoverflow.com/comment/85035290
linked to: http://stackoverflow.com/q/18451272
accepted answer: http://stackoverflow.com/a/49015302
linked to: http://stackoverflow.com/q/18721066
has comment: http://stackoverflow.com/comment/85036238

http://stackoverflow.com/q/49114267
has body: I need to calculate just first five prime numbers. I want to check the length of list while building it in list comprehension. The following code doesn't work. def checkPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True primes = [] primes = [x for x in range(2,30) if(checkPrime(x) and len(primes)&lt;6) ] print primes Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] Why len(primes)&lt;6 is not working here. How can I achieve that?
tagged with: list
downvote count: 0
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/76599059
tagged with: list-comprehension
possible better answer: http://stackoverflow.com/a/49114510
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49114510
accepted answer: http://stackoverflow.com/a/49114459
has comment: http://stackoverflow.com/comment/85233734
has title: Check length of list in list comprehension (Iteration based on the count of elements within list comprehension)
has answer: http://stackoverflow.com/a/49114460
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/49114459
tagged with: python
has comment: http://stackoverflow.com/comment/85233677
answer count: 4

http://stackoverflow.com/comment/85041421
type: Comment
comment on: http://stackoverflow.com/q/49018087
type: QuestionComment
has text: Why all these `if` statements doing the same thing? Just convert the string into an integer and you'll avoid repeating the same code again and again.
score: 0

http://stackoverflow.com/a/49065373
has comment: http://stackoverflow.com/comment/85136499
answers question: http://stackoverflow.com/q/49065255
score: 0
type: Answer
has body: StringIO.close() or use with statement on Python 3.x.

http://stackoverflow.com/q/49019357
has comment: http://stackoverflow.com/comment/85044291
type: Question
tagged with: ttk
linked to: http://stackoverflow.com/q/7310511
score: 0
has body: Here is the pare of my code that is relevant. while True: p = int(psutil.cpu_percent(interval=0.1)) progressbar = ttk.Progressbar(orient=HORIZONTAL, length=screen_width, mode='determinate') progressbar['value'] = p progressbar.update_idletasks() So when I run this is just spits freezes on the first value it gets from the p variable. I have tried setting VARIABLE instead of setting value like this. Please help.
has comment: http://stackoverflow.com/comment/85044198
has title: Ttk progress bar won't update
tagged with: progress-bar
has comment: http://stackoverflow.com/comment/85044397
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85044022

http://stackoverflow.com/comment/85154739
type: QuestionComment
type: Comment
has text: first run of any query is slow on redshift. as it is "compiling" - could this be the reason?
score: 0
comment on: http://stackoverflow.com/q/49073662

http://stackoverflow.com/comment/98237387
comment on: http://stackoverflow.com/a/49026969
has text: I'm having the same issue (container stops at epoch 1/1) and I don't have any library named uwsgi. Could you please elaborate the solution?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85044328
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49019468
has text: Please show your code; in my code, both interactive and script, these produce a single each each, not a list.
score: 0

http://stackoverflow.com/q/49008237
score: -3
downvote count: 3
has title: Capture negative dollar values
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49008282
has body: the following expression captures positive dollar values i.e. 400$ how can i modify this to capture negative values only. pattern = re.compile(r'^\d+\$$')
has comment: http://stackoverflow.com/comment/85020888
linked to: http://stackoverflow.com/q/15814592
upvote count: 0
answer count: 1
tagged with: string
favorite count: 0
duplicate of: http://stackoverflow.com/q/15814592
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49008282

http://stackoverflow.com/q/48968350
has title: How to find the absolute value of a complex function?
has answer: http://stackoverflow.com/a/48968364
has comment: http://stackoverflow.com/comment/84942290
upvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48968364
score: -3
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8370637
downvote count: 3
has body: I want to find the absolute value of something like 'i' but when I type 'abs(1)' it says 'i' is not defined. What do I do?
duplicate of: http://stackoverflow.com/q/8370637
type: Question

http://stackoverflow.com/a/49080704
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49022086
score: 3
downvote count: 0
has body: Since the OP is using the openpyxl module I wanted to show a way to do this using that module. With this answer I demonstrate a way to move the original data to new column and row coordinates (there may be better ways to do this). This fully reproducible example first creates a workbook for demonstration purposes called 'test.xlsx', with three sheets named 'test_1', 'test_2' and 'test_3'. Then using openpyxl, it copies 'test_2' into a new workbook called 'new.xlsx' shifting the cells over 4 columns and down 3 columns. It makes use of the ord() and chr() functions. import pandas as pd import numpy as np import openpyxl # This section is sample code that creates a worbook in the current directory with 3 worksheets df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC')) writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='test_1', index=False) df.to_excel(writer, sheet_name='test_2', index=False) df.to_excel(writer, sheet_name='test_3', index=False) wb = writer.book ws = writer.sheets['test_2'] writer.close() # End of sample code that creates a worbook in the current directory with 3 worksheets wb = openpyxl.load_workbook('test.xlsx') ws_name_wanted = "test_2" list_all_ws = wb.get_sheet_names() for item in list_all_ws: if item != ws_name_wanted: remove = wb.get_sheet_by_name(item) wb.remove_sheet(remove) ws = wb['%s' % (ws_name_wanted)] for row in ws.iter_rows(): for cell in row: cell_value = cell.value new_col_loc = (chr(int(ord(cell.coordinate[0:1])) + 4)) new_row_loc = cell.coordinate[1:] ws['%s%d' % (new_col_loc ,int(new_row_loc) + 3)] = cell_value ws['%s' % (cell.coordinate)] = ' ' wb.save("new.xlsx") Here's what 'test.xlsx' looks like: And here's what 'new.xlsx' looks like:

http://stackoverflow.com/comment/85036261
type: AnswerComment
type: Comment
has text: Actually, you can probably do this inside the loop, which will be efficient. Just use `enumerate` so you can check the forward indices, and do not yield a word if it is a stopword *or* if it forms one of the pieces of your trigram stopword, based on index checking.
comment on: http://stackoverflow.com/a/49015400
score: 0

http://stackoverflow.com/comment/84948676
comment on: http://stackoverflow.com/q/48971745
type: Comment
has text: Please format properly.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49078479
accepted answer: http://stackoverflow.com/a/49078750
favorite count: 0
possible better answer: http://stackoverflow.com/a/49078602
upvote count: 2
has comment: http://stackoverflow.com/comment/85163060
tagged with: python
tagged with: merge
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/49078750
has title: Merge 2 Pandas dataframes by dates within a few days of each other?
linked to: http://stackoverflow.com/q/21201618
tagged with: date
has comment: http://stackoverflow.com/comment/85163340
answer count: 2
has body: I have these two pandas dataframes I created and cleaned from online data, and I was trying to merge them based on their dates, which are all by month. However, the first dataset has its days on the last day of the month, whether the second dataset is based on the first day of the month. # data1 0 1987-01-01 63.752 1 1987-02-01 64.152 2 1987-03-01 64.488 3 1987-04-01 64.995 # data2 0 1987-01-31 1115.10 1 1987-02-30 1095.63 2 1987-03-30 1036.19 3 1987-04-30 1057.08 I would normally merge them by something like this if I had daily data with a few missing days data3 = pd.merge(left=data1, left_on='Date', right=data2, right_on='Date') but in this case they are never matching, even though they are all similar dates. How would I go about "telling" Pandas to combine the datasets based on dates that are just a few days apart, and name each data by just "month - year"? I don't know where to begin.
tagged with: pandas
has answer: http://stackoverflow.com/a/49078602
has comment: http://stackoverflow.com/comment/85163081
downvote count: 0
has comment: http://stackoverflow.com/comment/85163233

http://stackoverflow.com/q/48972044
favorite count: 0
tagged with: crf
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 11
downvote count: 0
has body: CRF++ allows us to get marginal probabilities for each tag (a kind of confidece measure for each output tag) and a conditional probably for the output (confidence measure for the entire output). % crf_test -v2 -m model test.data # 0.478113 Rockwell NNP B B/0.992465 B/0.992465 I/0.00144946 O/0.00608594 International NNP I I/0.979089 B/0.0105273 I/0.979089 O/0.0103833 Corp. NNP I I/0.954883 B/0.00477976 I/0.954883 O/0.040337 's POS B B/0.986396 B/0.986396 I/0.00655976 O/0.00704426 Tulsa NNP I I/0.991966 B/0.00787494 I/0.991966 O/0.00015949 unit NN I I/0.996169 B/0.00283111 I/0.996169 O/0.000999975 .. Tensorflow has its own implementation for crf. After training a crf model, we can get the best tag sequence y and its unormalized score for each test input sequence x through tf.contrib.crf.viterbi_decode() or tf.contrib.crf.crf_decode(). However, it's not sufficient for me to get one best sequence. Currently, the top-k best sequences and their corresponding scores are all useful to me. I notice that currently the aforementioned two functions do not provide these informations. Hence, i am wondering is it possible to get the top-k best candidates after minor modifications to tensorflow source code. top-k tag sequences and their corresponding unormalize scores. marginal probabilities for each tag (as CRF++)
tagged with: tensorflow
type: Question
tagged with: beam-search
upvote count: 11
has title: how to get top-k best candidate sequences when using CRF for decoding in tensorflow
tagged with: viterbi

http://stackoverflow.com/a/49062934
has comment: http://stackoverflow.com/comment/85131091
type: Answer
score: 5
has comment: http://stackoverflow.com/comment/85132476
upvote count: 5
has body: Based on the comments of the previous answer, do you want something like this: n = 0 while True: if True: #Replace True with any other condition you like. print(n) n+=1 EDIT: Based on the comments by OP on this answer, what he wants is for the data to persist or in more precise words the variable n to persist (Or keep it's new modified value) between multiple runs times. So the code for that goes as(Assuming Python3.x): try: file = open('count.txt','r') n = int(file.read()) file.close() except IOError: file = open('count.txt','w') file.write('1') file.close() n = 1 print(n) n += 1 with open('count.txt','w') as file: file.write(str(n)) print("Now the variable n persists and is incremented every time.") #Do what you want to do further, the value of n will increase every time you run the program NOTE: There are many methods of object serialization and the above example is one of the simplest, you can use dedicated object serialization modules like pickle and many others.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49062852
answers question: http://stackoverflow.com/q/49062852

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/48984567
tags question: http://stackoverflow.com/q/49071561

http://stackoverflow.com/q/48984180
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/48984343
answer count: 1
has comment: http://stackoverflow.com/comment/84973111
tagged with: python
type: AnsweredQuestion
has body: everyone, I'm doing some research in animal protection. I've collected some animal species data, it contains Chinese character as well as other non-english characters. for instance 中文名 . 拉丁名 . cites附录等级 蜂猴 Nycticebus bengalensis (Lacépède, 1800) Ⅰ 倭蜂猴 Nycticebus pygmaeus Bonhote, 1907 Ⅰ I'm not sure which encoding to choose from ,any help ? thanks a lot with open('animal_protection.csv',encoding = "utf-8") as csvDataFile:
has answer: http://stackoverflow.com/a/48984343
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84973048
has title: python import csv file with both chinese character and latin character

http://stackoverflow.com/comment/84958339
score: 0
comment on: http://stackoverflow.com/q/48974903
type: Comment
type: QuestionComment
has text: wouldn't that only work after the module has been imported ? i want to speed up the imports.

http://stackoverflow.com/a/49074813
score: 0
type: Answer
has body: This will do, if your dataframe is called df # find the ids that have at least one 'Yes' entry yes_ids = df.loc[df.Accepted == 'Yes', 'ID'] # Drop all those indices df.drop(df[df.ID.isin(yes_ids)].index) Returns: ID Company Accepted 3 2 B No 4 2 C No 9 4 A No 10 4 C No
answers question: http://stackoverflow.com/q/49074772

http://stackoverflow.com/q/49021098
linked to: http://stackoverflow.com/q/15148496
tagged with: pointers
has comment: http://stackoverflow.com/comment/85047849
answer count: 1
has comment: http://stackoverflow.com/comment/85047928
favorite count: 0
tagged with: reference
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85048599
tagged with: python
has comment: http://stackoverflow.com/comment/85047588
has comment: http://stackoverflow.com/comment/85049755
has title: Accessing variables by reference in python
has body: I am not sure if this makes any sense in python, but consider I have two variables x and y: x = 1 y = x Now, at a later time when I change x, I want y to see this change. that is if I do x = 2 I want y to be 2 also. Is there a way to do reference(x) = 2, so that all variables that were assigned to x will see this change? One way to make this work is to use lists for everything as described here. This would work if I had defined x as list, so if x = [1] y = x then, doing x.clear() and x.append(val) for val in new_list would work, and y will change according to the new list. But I would like to do it for any type, because otherwise I will need to revisit most of my codebase. Is there a mutable type so I don't have to redefine all my y's to be x[0]. Any suggestion is appreciated.
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85047566
downvote count: 1
has answer: http://stackoverflow.com/a/49021156
type: Question
has comment: http://stackoverflow.com/comment/85047508

http://stackoverflow.com/q/49078098
has body: I am plotting a 3D point cloud on an XYZAxis with the Markers visual. In addition, I would like to plot a plane that shows how these points are separated; in this case, I have the coefficients c_0, c_1, c_2, c_3 of the plane c_0x_ + c_1y + c_2z + c_3 = 0. How can I do this? I've tried using the Plane visual, but I'm not sure how to tailor the Plane to the coefficients. Thanks!
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49078276
has title: Plot a plane in vispy
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: vispy

http://stackoverflow.com/q/49081175
tagged with: nlp
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49084834
score: 1
has body: can any one tell me whether any package is available in python to frame questions from nouns? and help me with similar projects.
type: Question
tagged with: nltk
tagged with: rdbms
downvote count: 0
has title: Is there any existing modules on NLP
answer count: 1

http://stackoverflow.com/q/49019073
tagged with: matplotlib
score: 0
tagged with: imagemagick
has title: Python animation ffmpeg error - ValueError: I/O operation on closed file
has comment: http://stackoverflow.com/comment/85043527
has comment: http://stackoverflow.com/comment/85043754
tagged with: ffmpeg
linked to: http://stackoverflow.com/q/46386759
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85043628
tagged with: python
has comment: http://stackoverflow.com/comment/85043848
answer count: 0
type: Question
has body: I'm trying to follow this example here to do a simple animation: https://matplotlib.org/examples/animation/basic_example_writer.html I get this error: ValueError Traceback (most recent call last) /fsr/rfs07/ELEGANCE/work/code/python/s5p/animation_test.py in &lt;module&gt;() 25 line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), 26 interval=50, blit=True) ---&gt; 27 line_ani.save('lines.mp4', writer=writer) 28 29 fig2 = plt.figure() /software/local/apps/python/2.7.9/lib/python2.7/site-packages/matplotlib/animation.pyc in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs) 1061 # TODO: See if turning off blit is really necessary 1062 anim._draw_next_frame(d, blit=False) -&gt; 1063 writer.grab_frame(**savefig_kwargs) 1064 1065 # Reconnect signal for first draw if necessary /software/local/apps/python/2.7.9/lib/python2.7/contextlib.pyc in __exit__(self, type, value, traceback) 33 value = type() 34 try: ---&gt; 35 self.gen.throw(type, value, traceback) 36 raise RuntimeError("generator didn't stop after throw()") 37 except StopIteration, exc: /software/local/apps/python/2.7.9/lib/python2.7/site-packages/matplotlib/animation.pyc in saving(self, *args, **kw) 287 yield self 288 finally: --&gt; 289 self.finish() 290 291 def _run(self): /software/local/apps/python/2.7.9/lib/python2.7/site-packages/matplotlib/animation.pyc in finish(self) 307 def finish(self): 308 'Finish any processing for writing the movie.' --&gt; 309 self.cleanup() 310 311 def grab_frame(self, **savefig_kwargs): /software/local/apps/python/2.7.9/lib/python2.7/site-packages/matplotlib/animation.pyc in cleanup(self) 346 def cleanup(self): 347 'Clean-up and collect the process used to write the movie file.' --&gt; 348 out, err = self._proc.communicate() 349 self._frame_sink().close() 350 verbose.report('MovieWriter -- ' /software/local/apps/python/2.7.9/lib/python2.7/site-packages/subprocess32.pyc in communicate(self, input, timeout) 9…

http://stackoverflow.com/q/49012323
type: Question
upvote count: 4
score: 4
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/57575539
tagged with: jupyter-notebook
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: opencv
has body: Are there any ways I can play mp4 videos with the same speed as the actual file on jupyter notebook using python opencv? When I make .py file and use cv2.imshow() then the speed is normal, but when I try the code below on jupyter notebook, it gets very slow. My code: import cv2 import matplotlib.pyplot as plt from IPython import display %matplotlib inline cap = cv2.VideoCapture('video.mp4') while(cap.isOpened()): try: ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) plt.imshow(frame) display.clear_output(wait=True) display.display(plt.gcf()) except KeyboardInterrupt: cap.release()
has title: How to play mp4 at normal speed on jupyter notebook using python opencv
tagged with: matplotlib

http://stackoverflow.com/a/49164313
answers question: http://stackoverflow.com/q/49097667
score: 1
downvote count: 0
type: Answer
upvote count: 1
has body: I think you should consider a "vector" representation for your data, instead of the current "raster" representation. A vector representation would mean that, instead of each "voxel" being defined by its position in a grid, you would have some sort of list of voxels, with actual 3D coordinates. So instead of having an MxNxD matrix where each voxel is a "black/white" dot, you could have a Mx3 matrix, where each row is a point, with columns being X, Y and Z. That way, you would multiply the list by a 3x3 rotation matrix, and get another list of transformed coordinates. You would remain with the problem of "rendering" these vector points (or lines, better yet) to a raster matrix (either pixels or voxels, but your sample image looks like 3D info has been projected to 2D space). There are a lot of techniques for doing this.

http://stackoverflow.com/a/49115891
upvote count: 1
has comment: http://stackoverflow.com/comment/85238357
downvote count: 0
has comment: http://stackoverflow.com/comment/85238325
answers question: http://stackoverflow.com/q/49063991
type: Answer
has comment: http://stackoverflow.com/comment/85238236
has comment: http://stackoverflow.com/comment/85238118
has body: Here is one way to replace all substrings in a dictionary. Just note that the order may become important if any of the values and keys of the dictionary collide: import pandas as pd s = pd.Series(['Wood', 'Wooden', 'Woody Woodpecker', 'wood', 'wood', 'wool suit']) d = {'Wood': 'Wooden', 'wool': 'soft'} for k, v in d.items(): s = s.str.replace(k, v) # 0 Wooden # 1 Woodenen # 2 Woodeny Woodenpecker # 3 wood # 4 wood # 5 soft suit # dtype: object
score: 1

http://stackoverflow.com/q/49064162
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/49065965
has body: I want to iterate each element of a list and passing it to the function. This is what i tried but getting below errors. import call_functions newObject = call_functions.call_functions_class() size_DF = newObject.descr_size(sc, dataBase) size_RDD = sc.parallelize(size_DF).map(lambda x : x[0]) def full_item_new(sc, dataBase, length, end_date): newObject.full_item(sc, dataBase, length, end_date) size_RDD.map(lambda x : full_item_new(sc, dataBase, x[0], end_date)).collect() def full_item(sc, dataBase, length, end_date): sqlContext = SQLContext(sc) insertDF = sqlContext.sql("insert into -----") return insertDF error : "It appears that you are attempting to reference SparkContext from a broadcast " Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.
tagged with: pyspark
score: 0
tagged with: apache-spark
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: iterate each element of a list and passing to a function
tagged with: databricks

http://stackoverflow.com/comment/85138277
type: Comment
type: AnswerComment
has text: Only for a specific case, e.g. a static key or highly dynamic? If the latter would definitely be beyond the scope of a SO question. Anyways, asking about ``regex`` is a separate question since you are asking explicitly how to achieve that with ``libconf``.
comment on: http://stackoverflow.com/a/49066101
score: 0

http://stackoverflow.com/comment/85206485
has text: @user2357112 huh? Really? I had considered this the definition of an iterable?
score: 0
comment on: http://stackoverflow.com/q/49100416
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85105410
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49050166
has text: Am unable to reproduce this issue, can you share sample `X_selection` and `X_model` dataframes?
type: Comment

http://stackoverflow.com/q/49059672
score: 0
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49060233
type: Question
has title: Displaying all search results in Python web scraper
accepted answer: http://stackoverflow.com/a/49060233
has body: I am quite new to Python and am building a web scraper, which will scrape the following page and links in them: https://www.nalpcanada.com/Page.cfm?PageID=33 The problem is the page's default is to display the first 10 search results, however, I want to scrape all 150 search results (when 'All' is selected, there are 150 links). I have tried messing around with the URL, but the URL remains static no matter what display results option is selected. I have also tried to look at the Network section of the Developer Tools on Chrome, but can't seem to figure out what to use to display all results. Here is my code so far: import bs4 import requests import csv import re response = requests.get('https://www.nalpcanada.com/Page.cfm?PageID=33') soup = bs4.BeautifulSoup(response.content, "html.parser") urls = [] for a in soup.findAll('a', href=True, class_="employerProfileLink", text="Vancouver, British Columbia"): urls.append(a['href']) pagesToCrawl = ['https://www.nalpcanada.com/' + url + '&amp;QuestionTabID=47' for url in urls] for pages in pagesToCrawl: html = requests.get(pages) soupObjs = bs4.BeautifulSoup(html.content, "html.parser") nameOfFirm = soupObjs.find('div', class_="ip-left").find('h2').next_element tbody = soupObjs.find('div', {"id":"collapse8"}).find('tbody') offers = tbody.find('td').next_sibling.next_sibling.next_element seeking = tbody.find('tr').next_sibling.next_sibling.find('td').next_sibling.next_sibling.next_element print('Firm name:', nameOfFirm) print('Offers:', offers) print('Seeking:', seeking) print('Hireback Rate:', int(offers) / int(seeking))
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85195904
type: QuestionComment
has text: read about [string manipulation in python](http://www.pythonforbeginners.com/basics/string-manipulation-in-python)
comment on: http://stackoverflow.com/q/49095426
score: 0
type: Comment

http://stackoverflow.com/comment/85176068
comment on: http://stackoverflow.com/q/49084955
type: Comment
type: QuestionComment
score: 1
has text: please give a sample of input and desired output

http://stackoverflow.com/comment/85451074
has text: so I agree with you. But the problem is that, even after initializing the model, using `sess.run(init_op)`, I am restoring the whole graph using `saver_torestore.restore`. Hence, I am not initializing randomly as you have mentioned. Please correct me if I'm mistaken. Thank you.
type: Comment
comment on: http://stackoverflow.com/a/49223634
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85169419
has text: I don't this is a duplicate because it asks "what causes this effect?"
comment on: http://stackoverflow.com/q/49081980
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48970416
downvote count: 0
score: 1
type: Question
answer count: 2
tagged with: for-loop
has body: I am learning python and i wanted to iterate only specified number of time but using an array variable. I searched over the net that we can use range function for it. But I'm not able to iterate using range() here is my simplified code:- array=[1,2,3,4,5] for record in array: print(record) I wanted to print only first 3 indexes. Here i just have taken numbers in array for reference actually i'm pilling content from an text file and storing it in array and printing it line by line. And then do further sorting Here is the code i'm trying :- array=[1,2,3,4,5] for record in range(0,2,array): print(record) Error I'm getting:- List object cannot be interpreted as integer
has comment: http://stackoverflow.com/comment/84946279
upvote count: 1
has title: how to specify range if we are taking an array in for loop
has comment: http://stackoverflow.com/comment/84946319
favorite count: 0
has answer: http://stackoverflow.com/a/60489943
has comment: http://stackoverflow.com/comment/84946257
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48970484
tagged with: python

http://stackoverflow.com/q/49064851
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/116730649
type: Question
has title: Insert INTEGER/NUMERIC into sqlite but turning to BLOB
has body: I'm writing SQL with python and sqlite. I have a python list called supermarket_ids and each element of the list is a number: 2. I also have a column in a sqlite table which stores INTEGER or NUMERIC. I use a for loop to loop the list and insert to sqlite database. I INSERT the variable to the column, but when I SELECT it from the table, it returns b'\x02\x00\x00\x00\x00\x00\x00\x00' instead of 2. I tried to alter the column to store either INTEGER or NUMERIC but it is still the same. My code for INSERT is as follows: c.execute("INSERT INTO SKU_Table (Supermarket_ID) VALUES (?)", (supermarket_ids[i])) And when I view it with a database software called DB Browser for SQLite, it shows that the Supermarket_ID is now a BLOB. Any idea?
downvote count: 0
tagged with: sql
linked to: http://stackoverflow.com/q/49456158
has comment: http://stackoverflow.com/comment/85210467
tagged with: sqlite
has comment: http://stackoverflow.com/comment/85155697
has comment: http://stackoverflow.com/comment/85216252
favorite count: 0
has comment: http://stackoverflow.com/comment/109656984

http://stackoverflow.com/a/48997875
has comment: http://stackoverflow.com/comment/85004163
type: Answer
has comment: http://stackoverflow.com/comment/85187909
accepted answer of: http://stackoverflow.com/q/48973777
answers question: http://stackoverflow.com/q/48973777
score: 0
type: AcceptedAnswer
has body: This color is closer to the rest of the picture than one think (in the HLS space). IMO, the best way to enhance it is by means of the Euclidean distance to that particular orange in RGB space. For instance, the pixels at distance 32√3:

http://stackoverflow.com/a/49044226
has body: You have to look for the scripts, Then look for the 'window._sharedData' exits in it. If exits then perform the regular expression operation. import re username_extract = 'lazada_my' url = 'https://www.instagram.com/'+ username_extract r = requests.get(url) soup = BeautifulSoup(r.content,'lxml') s = re.compile(r'"followed_by":{"count":\d*}') for i in soup.find_all('script'): if 'window._sharedData' in str(i): print s.search(str(i.contents)).group() Result, "followed_by":{"count":407426}
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49043857

http://stackoverflow.com/q/49093535
tagged with: deep-learning
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/85217700
has comment: http://stackoverflow.com/comment/85192289
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85192385
answer count: 0
has title: tensorflow inception v3 transfer learning
tagged with: tensorflow
type: Question
has body: I'd like to use tensorflow's trained inception model to classify flower photos. By loading tensorflow_inception_graph.pb, I imported two tensors from the graph:pool_3/_reshape:0 and DecodeJpeg/contents:0 bottleneck_tensor_name='pool_3/_reshape:0' jpeg_data_tensor_name='DecodeJpeg/contents:0' model_dir='C:/Users/User/PycharmProjects/Neural_Network' model_file='tensorflow_inception_graph.pb' with gfile.FastGFile(os.path.join(model_dir,model_file),'rb') as f: graph_def=tf.GraphDef() graph_def.ParseFromString(f.read()) bottleneck_tensor,jpeg_data_tensor=tf.import_graph_def(graph_def,return_elements=[bottleneck_tensor_name,jpeg_data_tensor_name]) After loading my own image_data, I performed: bottleneck_values=sess.run(bottleneck_tensor,{image_data_tensor:image_data}) bottleneck_values=np.squeeze(bottleneck_values) However, I got two types of errors: (1) BatchNormalization Deprecated (2) shape is incompatible. Is it because jpeg_data_tensor_name's shape from the graph is different from my photo's shape? Where can I get the source code to check how pool_3/_reshape:0 and DecodeJpeg/contents:0 are specified? If BatchNormalization is deprecated, need to retrain from scratch? 2018-02-25 20:42:07.519912: W C:\tf_jenkins\workspace\rel-win\M\windows\PY\36\tensorflow\core\framework\op_def_util.cc:343] Op BatchNormWithGlobalNormalization is deprecated. It will cease to work in GraphDef version 9. Use tf.nn.batch_normalization(). Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1350, in _do_call return fn(*args) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1329, in _run_fn status, run_metadata) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.erro…
tagged with: neural-network
score: 0

http://stackoverflow.com/q/48970391
tagged with: python
has body: I am reading lines from an input file and splitting it into words so I can process each word. I want to get characters from each word at specific indexes. This is what I am trying, which does not work properly, anything greater than word[0] is out of index. I do not understand why it wouldn't work since word should be a string and indexing with strings work without a problem. Any help is appreciated. Thanks edit: sorry, to clarify - I want to get characters from word with indexing. e.g word = something, word[3] = 'e'. I am using fileinput module so import fileinput line = f.readline() for word in line.split(): print(word, end="") r = int(word[1]) // I want to get the 2nd character from this word in the line c = int(word[3]) Input File: 1 (1,1) 2 (1,2) (1,3) 5 (2,1) (2,2) (3,1) (3,2) (3,3) 4 (2,3) (2,4) (1,4) (1,5) 3 (3,4) (3,5) (2,5) I want to set r = the first number in the perenthesis and c = the second number in the parenthesis
possible better answer: http://stackoverflow.com/a/48970442
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48970499
has answer: http://stackoverflow.com/a/48970442
score: 1
type: Question
has answer: http://stackoverflow.com/a/48970745
has answer: http://stackoverflow.com/a/48970499
upvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/84946290
downvote count: 1
favorite count: 0
tagged with: python-3.x
has title: Python - Splitting a line and extracting characters from the words

http://stackoverflow.com/a/49028656
upvote count: 3
has comment: http://stackoverflow.com/comment/85062184
score: 3
accepted answer of: http://stackoverflow.com/q/49028546
has comment: http://stackoverflow.com/comment/85062179
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49028546
has body: You should use UserList's constructor to initialize it, instead of list's constructor: class customList(UserList): def __init__(self, liste): super().__init__(liste)
type: Answer
has comment: http://stackoverflow.com/comment/85062333

http://stackoverflow.com/comment/117974877
has text: why do you disable all that stuff like gpu, extensions, default apps etc. before starting?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49114113
type: Comment

http://stackoverflow.com/q/49007341
has comment: http://stackoverflow.com/comment/85019245
has title: printing terminal outputs to text file
has comment: http://stackoverflow.com/comment/85019277
has body: Im trying to send all my outputs to a file,not exclusively print statements but all statements,I'm running an algorithm which gives outputs of its own and some logger outputs, Right now Im trying f = open('/mnt/sdc1/Ryan/Test/output_logs/{}.txt'.format(file),'w') sys.stdout=f but this outputs only the print statements, I have also tried experimenting with f = open('/mnt/sdc1/Ryan/Test/output_logs/{}.txt'.format(file),'w') sys.stderr=f but this too does not give me everything that the terminal outputs, Any suggestions would be helpful,Thanks in advance.
linked to: http://stackoverflow.com/q/17602878
has comment: http://stackoverflow.com/comment/85019357
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85019204
answer count: 0
has comment: http://stackoverflow.com/comment/85019212
score: 0
has comment: http://stackoverflow.com/comment/85019151
type: Question
linked to: http://stackoverflow.com/q/38776104

http://stackoverflow.com/q/49074117
has answer: http://stackoverflow.com/a/49074427
has answer: http://stackoverflow.com/a/49074465
has answer: http://stackoverflow.com/a/49074357
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49074465
has comment: http://stackoverflow.com/comment/85154026
tagged with: loops
has comment: http://stackoverflow.com/comment/85154103
type: Question
tagged with: boolean
has title: IndexError - Using Python 3.4.3
has answer: http://stackoverflow.com/a/49074158
has body: I'm trying to write a code for a small program that takes a list as an input and returns a Boolean indicating whether there are any consecutively repeated numbers (the list must have at least 2 elements). I keep getting the following error: IndexError: list index out of range. Any advice on how to fix this will be greatly appreciated! def two_length_run(n): i = 0 while i &lt; len(n): if len(n) &gt;= 2: if (n[i] == n[i + 1]) and (n[i + 1] &lt;= len(n)): return True else: i = i + 1 else: return False
accepted answer: http://stackoverflow.com/a/49074357
score: 0
tagged with: while-loop
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/49074443

methods
tags question: http://stackoverflow.com/q/49020632
tags question: http://stackoverflow.com/q/49070312
tag name: methods
tags question: http://stackoverflow.com/q/49020361
tags question: http://stackoverflow.com/q/49088836
type: Tag
tags question: http://stackoverflow.com/q/49100946
tags question: http://stackoverflow.com/q/49058775
tags question: http://stackoverflow.com/q/49080090
tags question: http://stackoverflow.com/q/49070653
tags question: http://stackoverflow.com/q/49120813
tags question: http://stackoverflow.com/q/49013245

http://stackoverflow.com/q/49055279
tagged with: pyglet
has title: pyglet - Retrieve width of Label
upvote count: 2
has answer: http://stackoverflow.com/a/49067134
accepted answer: http://stackoverflow.com/a/49067134
answer count: 1
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I have a label element for displaying text on the screen: nameLabel = pyglet.text.Label(name, font_name='Tahoma', x=50, y=50, font_size=12, batch=batch.overlay2, height=self.scale_y, bold=True) With the label I also have a pyglet.sprite.Sprite: sprite = pyglet.sprite.Sprite.__init__(res.IMG_COLOR_BLACK, batch=batch.overlay1) The image of this sprite is 1x1 pixels and I am using the scale_x and scale_y values to draw a rectangle. I would like to set the width of this sprite to the width of the text, so that the text fits inside it. I have tried using Label.width: sprite.scale_x = nameLabel.width However, the width is only returning None and therefore raising an error. I can't think of any other way to retrieve the width of this label. Does anyone know how I can do this? Thanks, David.
type: Question

http://stackoverflow.com/comment/84940749
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48967302
score: 0
has text: the the objects in my_album list are of the model UserAlbum and the objets in albums list is of the model Album. Their ids won't ever match :/

http://stackoverflow.com/comment/85166336
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49080194
has text: look up list comprehesion and note that string.split returns a list
score: 0

http://stackoverflow.com/a/48989690
answers question: http://stackoverflow.com/q/48989295
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84984019
type: Answer
has body: Because request encode , symbol into %2C while it was processed. You can find more about URL percent encoding on Wiki When a character from the reserved set (a "reserved character") has special meaning (a "reserved purpose") in a certain context, and a URI scheme says that it is necessary to use that character for some other purpose, then the character must be percent-encoded. Percent-encoding a reserved character involves converting the character to its corresponding byte value in ASCII and then representing that value as a pair of hexadecimal digits. The digits, preceded by a percent sign (%) which is used as an escape character, are then used in the URI in place of the reserved character. (For a non-ASCII character, it is typically converted to its byte sequence in UTF-8, and then each byte value is represented as above.)
has comment: http://stackoverflow.com/comment/84984441
accepted answer of: http://stackoverflow.com/q/48989295

http://stackoverflow.com/a/49109870
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/85225294
has body: I only checked the Python version and there's indeed an error in the implementation. Namely, your testfunc, ie the target function of root-finding brentq routine, behaves non-deterministically. During a root-finding run (i.e. one call to brentq() until it returns), brentq needs to call the same callback multiple times until convergence is reached. However, each time brentq calls this callback, the target equation changes as r gets a new pseudo-random value. As a result, the root-finding routine cannot converge to your desired solution. What you need to do instead, conceptually, is to first generate a sample of uniform random variables, and apply the same, deterministic transformation (i.e. the inverse distribution function) to them. Of course you don't need to do root-solving, as you can use the ppf (percentile function, i.e. inverse of cdf) method of scipy.stats random variable classes. As a proof of concept, you can run the following code with the (unnecessarily expensive and not very accurate) transformation method on an array of standard uniform sample: import numpy import numpy.random from scipy.optimize import brentq from scipy.stats import norm # Setup n = 10000 numpy.random.seed(0x5eed) ran_array = numpy.random.uniform(size=n) sol_array = numpy.empty_like(ran_array) # Target function for root-finding: F(x) - p = 0 where p is the probability level # for which the quantile is to be found def targetfunc(x, p): return norm.cdf(x, 5, 2) - p for i in range(n): sol_array[i] = brentq(targetfunc, -100.0, 100.0, args=(ran_array[i],)) print("mean = %10f" % sol_array.mean()) print("std = %10f" % sol_array.std()) Output: mean = 5.011041 std = 2.009365
has comment: http://stackoverflow.com/comment/85224929
has comment: http://stackoverflow.com/comment/85296639
score: 3
accepted answer of: http://stackoverflow.com/q/49109481
answers question: http://stackoverflow.com/q/49109481
has comment: http://stackoverflow.com/comment/85278577
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85225310

http://stackoverflow.com/a/49063758
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49063738
score: 16
has body: You need numpy.sign df['new'] = np.sign(df['col']) Sample: df = pd.DataFrame({ 'col':[-1,3,-5,7,1,0]}) df['new'] = np.sign(df['col']) print (df) col new 0 -1 -1 1 3 1 2 -5 -1 3 7 1 4 1 1 5 0 0
type: AcceptedAnswer
upvote count: 16
type: Answer
answers question: http://stackoverflow.com/q/49063738

http://stackoverflow.com/comment/84958389
has text: Thank you! The global variable was the issue.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48976097
score: 0

http://stackoverflow.com/q/48985922
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84976550
tagged with: inputstream
accepted answer: http://stackoverflow.com/a/48986913
linked to: http://stackoverflow.com/q/48916243
has comment: http://stackoverflow.com/comment/84977149
has body: I want to read two different files from sys.stdin, I can read and write file but there is no separation from first and second file. When I run below code on cmd in Windows 10 and Python 3.6: D:\digit&gt;cat s.csv s2.csv Result is: 1 2 3 4 5 1 2 3 4 5 6 7 I can print both files. My Python code is: import sys import numpy as np train=[] test=[] #Assume below code is function 1 which just and must read s.csv reader = sys.stdin.readlines() for row in reader: train.append(int(row[0])) train = np.array(train) print(train) #I need some thing here to make separation #sys.stdin.close() #sys.stdin = sys.__stdin__ #sys.stdout.flush() #Assume below code is function 2 which just and must read s2.csv reader = sys.stdin.readlines() for row in reader: test.append(int(row[0])) test = np.array(test) print(test) I run below command on cmd prompt: D:\digit&gt;cat s.csv s2.csv | python pytest.py Result is: [1 2 3 4 5 1 2 3 4 5 6 7] [] Do I need reset sys.stdin for next file? I used below ones but none of them was answer: sys.stdin.close() sys.stdin = sys.__stdin__ sys.stdout.flush()
linked to: http://stackoverflow.com/q/43554363
has title: How to read two different files in Python by sys.stdin
has comment: http://stackoverflow.com/comment/84977339
linked to: http://stackoverflow.com/q/48966769
has comment: http://stackoverflow.com/comment/84976600
type: AnsweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84977447
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48998584
has comment: http://stackoverflow.com/comment/84976395
has comment: http://stackoverflow.com/comment/84976496
has comment: http://stackoverflow.com/comment/84976422
has answer: http://stackoverflow.com/a/48986913
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48998584
answer count: 2
tagged with: streaming

http://stackoverflow.com/a/49054177
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49053956
accepted answer of: http://stackoverflow.com/q/49053956
has body: This mod should be enough to get you started: def write_row_to_que(self,*args, **kwargs): csv_que.put( (args, kwargs) ) Put the parameters into a tuple and the get() method at the other end will retrieve them. args, kwargs = csv_que.get() This line will retrieve the items, but: args will be a tuple of the unnamed arguments. kwargs will be a dictionary of the keyword arguments originally supplied.
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/85221778
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49108465
has text: Try using Requests. Link: http://docs.python-requests.org/en/master/
score: 0

http://stackoverflow.com/comment/85244425
type: QuestionComment
comment on: http://stackoverflow.com/q/49119392
score: 0
has text: @blue-sky `flatten` isn't the right tool for this problem.
type: Comment

http://stackoverflow.com/comment/85140711
type: QuestionComment
type: Comment
has text: Have you tried b"bucket_name" and b"key_name"?
score: 0
comment on: http://stackoverflow.com/q/49067785

http://stackoverflow.com/a/48995004
downvote count: 0
answers question: http://stackoverflow.com/q/48994844
type: Answer
upvote count: 1
score: 1
has body: Google held the answer :) Try passing hatch='/' to bar(). All hatch options (from here): ['/' | '' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*'] Demo: https://matplotlib.org/examples/pylab_examples/hatch_demo.html

http://stackoverflow.com/q/49043061
type: UnansweredQuestion
tagged with: classification
tagged with: regression
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/85096702
has answer: http://stackoverflow.com/a/49043264
tagged with: numpy
score: 0
linked to: http://stackoverflow.com/q/13794754
answer count: 1
has comment: http://stackoverflow.com/comment/85091188
has title: Inefficient Regularized Logistic Regression with Numpy
has body: I am a machine learning noob attemping to implement regularized logistic regression via Newton's method. The data have two features which are supposed to be expanded to 28 through finding all monomial terms of (u,v) up to degree 6 My code converges to the correct solution of norm(theta)=0.9384 after around 500 or so iterations when it should only take around 15 for lambda = 10, though the exercise is based on Matlab instead of Python. Each cycle of the parameter update is also very slow with my code and I am not sure exactly why. If anyone could explain why my code takes so many iterations to converge and why each iteration is painfully slow I would be very grateful! The data are taken from Andrew Ng's open course exercise 5. The problem information and data can be found here http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&amp;doc=exercises/ex5/ex5.html although I posted the data and my code below. X data with two features 0.051267,0.69956 -0.092742,0.68494 -0.21371,0.69225 -0.375,0.50219 -0.51325,0.46564 -0.52477,0.2098 -0.39804,0.034357 -0.30588,-0.19225 0.016705,-0.40424 0.13191,-0.51389 0.38537,-0.56506 0.52938,-0.5212 0.63882,-0.24342 0.73675,-0.18494 0.54666,0.48757 0.322,0.5826 0.16647,0.53874 -0.046659,0.81652 -0.17339,0.69956 -0.47869,0.63377 -0.60541,0.59722 -0.62846,0.33406 -0.59389,0.005117 -0.42108,-0.27266 -0.11578,-0.39693 0.20104,-0.60161 0.46601,-0.53582 0.67339,-0.53582 -0.13882,0.54605 -0.29435,0.77997 -0.26555,0.96272 -0.16187,0.8019 -0.17339,0.64839 -0.28283,0.47295 -0.36348,0.31213 -0.30012,0.027047 -0.23675,-0.21418 -0.06394,-0.18494 0.062788,-0.16301 0.22984,-0.41155 0.2932,-0.2288 0.48329,-0.18494 0.64459,-0.14108 0.46025,0.012427 0.6273,0.15863 0.57546,0.26827 0.72523,0.44371 0.22408,0.52412 0.44297,0.67032 0.322,0.69225 0.13767,0.57529 -0.0063364,0.39985 -0.092742,0.55336 -0.20795,0.35599 -0.20795,0.17325 -0.43836,0.21711 -0.21947,-0.016813 -0.13882,-0.27266 0.18376,0.93348 0.22408,0.77997 0.29896,0.619…
tagged with: python

http://stackoverflow.com/a/49091969
downvote count: 1
has comment: http://stackoverflow.com/comment/85189342
has body: We should try to avoid using + operator with string as much as we can, since each + may create one intermediate string. Use """ (double quote) or ''' (single quote) for multiline string or use \ for seperating them. NOTE: """ and ''' should be used with care otherwise it may print too many spaces in between two lines. Use format or similar concepts to format the string. def __str__(self): return "Team name is {0}\n"\ "Their regular season record was {1}\n"\ "Their win streak is {2}\n"\ "heir scoring percentage is {3}\n"\ "Their average rebounds are {4}\n"\ "Their passing is {5}\n"\ "Their turnovers are {6}".format( self.teamName, self.record, self.winStreak, self.scoringPercentage,self.rebounds, self.passing, self.turnovers ) Use """ def __str__(self): return """Team name is {0} Their regular season record was {1} Their win streak is {2} Their scoring percentage is {3} Their average rebounds are {4} Their passing is {5} Their turnovers are {6}""".format( self.teamName, self.record, self.winStreak, self.scoringPercentage, self.rebounds,self.passing, self.turnovers ) Use format with keyword arguments. def __str__(self): return """Team name is {name} Their regular season record was {record} Their win streak is {streak} Their scoring percentage is {score} Their average rebounds are {rebounds} Their passing is {passing} Their turnovers are {turnovers}""".format( name=self.teamName, record=self.record, streak=self.winStreak, score=self.scoringPercentage, rebounds=self.rebounds,passing=self.passing, turnovers=self.turnovers ) Use string format style like C/C++. def __str__(self): return """Team name is %s Their regular season record was %.2f Their win streak is %s Their scoring percentage is %s Their average rebounds are %s Their passing is %s Their turnovers are %s"""%( self.teamName, self.record, self.winStreak, self.scoringPercentage, self.rebounds,self.passing, self.turnovers ) https://ideone.com/xJ31fN
has comment: http://stackoverflow.com/comment/85189367
has comment: http://stackoverflow.com/comment/85189298
type: Answer
has comment: http://stackoverflow.com/comment/85189202
score: 2
has comment: http://stackoverflow.com/comment/85189211
answers question: http://stackoverflow.com/q/49091846
upvote count: 3

http://stackoverflow.com/comment/85043099
comment on: http://stackoverflow.com/q/49018652
type: Comment
type: QuestionComment
score: 0
has text: Added in the code.

http://stackoverflow.com/comment/84963611
type: QuestionComment
has text: And running the framework in a Python? It's quite a project, particular handling graphics. How far have you come?
comment on: http://stackoverflow.com/q/48971102
score: 0
type: Comment

http://stackoverflow.com/q/49053435
has answer: http://stackoverflow.com/a/49053823
tagged with: python
has answer: http://stackoverflow.com/a/49053557
has answer: http://stackoverflow.com/a/49053757
score: 1
has answer: http://stackoverflow.com/a/49053663
tagged with: django
has answer: http://stackoverflow.com/a/49054434
upvote count: 1
type: Question
has title: Group a large list of dictionaries by key value in django
type: AnsweredQuestion
answer count: 6
possible better answer: http://stackoverflow.com/a/49053573
linked to: http://stackoverflow.com/q/1663807
accepted answer: http://stackoverflow.com/a/49053663
has answer: http://stackoverflow.com/a/49053573
has body: I have a list of dictionaries as follows [{'grade': '1', 'past_student_sum': 1611}, {'grade': '2', 'past_student_sum': 1631}, {'grade': '3', 'past_student_sum': 1598}, {'grade': '1', 'current_student_sum': 1611}, {'grade': '2', 'current_student_sum': 1631}, {'grade': '3', 'current_student_sum': 1598}] I got this list by combining 2 query sets in the following fashion: grade_list = list(past_enrollments) + list(current_enrollments) Is there a better alternatives to combine these in such a way to get a list that looks like this: [{'grade': '1', 'past_student_sum': 1611, 'current_student_sum': 1621}, {'grade': '2', 'past_student_sum': 1511, 'current_student_sum': 1521}]
has comment: http://stackoverflow.com/comment/85111722
downvote count: 0
has comment: http://stackoverflow.com/comment/85111695
favorite count: 0

http://stackoverflow.com/comment/85166502
comment on: http://stackoverflow.com/a/49080268
has text: @JukesOnYou That was my point. The way you have it currently is better than the alternative,
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48996425
has comment: http://stackoverflow.com/comment/84999032
score: 4
has body: cell.min_bounds = min_bounds This doesn't do what you think it does (although I'm not 100% sure what it does do). You need to copy arrays element by element: cell.min_bounds[0] = min_bounds[0] cell.min_bounds[1] = min_bounds[1] Same for max_bounds. The line that I suspect is giving you that error message is: cell.center_of_mass = [0, 0] This is trying to assign a Python list to a C array (remembering that arrays and pointers are somewhat interchangeable in C), which doesn't make much sense. Again, you'd do cell.center_of_mass[0] = 0 cell.center_of_mass[1] = 0 All this is largely consistent with the C behaviour that there aren't operators to copy whole arrays into each other, you need to copy element by element. Edit: However that's not your immediate problem. You haven't declared PyMem_Malloc so it's assumed to be a Python function. You should do from cpython.mem cimport PyMem_Malloc Make sure it's cimported, not imported Edit2: The following compiles fine for me: from cpython.mem cimport PyMem_Malloc ctypedef double DTYPE_t ctypedef struct cell_t: DTYPE_t[2] min_bounds DTYPE_t[2] max_bounds cdef cell_t * make_cell(DTYPE_t[2] min_bounds, DTYPE_t[2] max_bounds) except NULL: cdef cell_t * cell = &lt;cell_t *&gt;PyMem_Malloc(sizeof(cell_t)) if not cell: raise MemoryError() return cell I've cut down cell_t a bit (just to avoid having to make declarations of UINT32_t). I've also given the cdef function an except NULL to allow it to signal an error if needed and added a raise before MemoryError(). I don't think either of these changes are directly related to your error.
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48995495
has comment: http://stackoverflow.com/comment/84998867
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84998439
type: Answer
has comment: http://stackoverflow.com/comment/84998723
answers question: http://stackoverflow.com/q/48995495
has comment: http://stackoverflow.com/comment/84998175

http://stackoverflow.com/comment/85234999
score: 0
type: AnswerComment
has text: @TarunLalwani thanks, i will appreciate if you find a way
comment on: http://stackoverflow.com/a/49113786
type: Comment

http://stackoverflow.com/comment/84970147
type: AnswerComment
comment on: http://stackoverflow.com/a/48982484
has text: type(patientGuid) is dict
score: 0
type: Comment

http://stackoverflow.com/a/48975447
type: Answer
score: 6
downvote count: 0
upvote count: 6
answers question: http://stackoverflow.com/q/48975383
has body: From the DOCS: When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches: manually escaping each variable; or automatically escaping everything by default. Jinja supports both. In the automatically escaping everything by default mode, to mark content as safe, and therefore not in need of escaping, use the filter: | safe Working with automatic escaping.

http://stackoverflow.com/a/49055173
score: 0
has body: Your last column isn't being parsed as floats, but strings. To fix this, try casting to numeric before summing: import locale locale.setlocale(locale.LC_NUMERIC, '') df['2017'] = df['2017'].map(locale.atoi) Better still, try reading in the data as numeric data. For example: df = pd.read_csv('file.csv', sep='\t', thousands=',')
has comment: http://stackoverflow.com/comment/85116164
type: Answer
accepted answer of: http://stackoverflow.com/q/49054969
answers question: http://stackoverflow.com/q/49054969
has comment: http://stackoverflow.com/comment/85116063
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85116041

http://stackoverflow.com/a/49076708
has comment: http://stackoverflow.com/comment/85163297
score: 0
has comment: http://stackoverflow.com/comment/85162780
type: Answer
has comment: http://stackoverflow.com/comment/85162793
answers question: http://stackoverflow.com/q/49076558
has comment: http://stackoverflow.com/comment/85204779
has body: Post your code also. Try following way, from tensorflow.python.ops import rnn_cell_impl

http://stackoverflow.com/a/49042336
type: Answer
has body: You can always use the find() method. def replaceWord(word, sentence): # find the starting position posStart = sentence.find(word) # find the ending position posEnd = posStart + sentence[posStart:].find(" ") - 1 # Get the word new_word = sentence[posStart:posEnd+1] # Turn word into a list list_word = list(new_word) # Find length of word word_length = len(sentence[posStart:posEnd + 1]) # replace the word with "*" star = "" for i in list_word: star = star + i.replace(i, "*") # Add back in sentence new_sentence = sentence[0:posStart - 1] + " " + star + " " + sentence[posEnd +2:] return new_sentence print(replaceWord("fox", "The fox is there"))
score: 0
answers question: http://stackoverflow.com/q/48980503

http://stackoverflow.com/comment/85193828
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49094247
has text: what if I want to print both pattern1 / pattern2 besides the strings in between ?
type: Comment

http://stackoverflow.com/a/49072284
has comment: http://stackoverflow.com/comment/85152520
has body: That print statement would print nothing even if it was actually defined as it prints what's entered in the UserInput before anything is entered. Remove the useless lines of: print(GetCountry) print(InputCountry) and add: print(InputCountry) in def GetCountry():'s scope. Additionally, functions set as command callbacks can't really return. One workaround would be to attach the value wanted to be returned to the method object itself. Replace: return InputCountry with: GetCountry.value = InputCountry finally to have: import tkinter #Quit Window when ESC Pressed def quit(event=None): window.destroy() def GetCountry(): InputCountry = UserInput.get() GetCountry.value = InputCountry print(InputCountry) #Create Main Window window=tkinter.Tk() window.geometry("%dx%d+%d+%d" % (330, 80, 200, 150)) window.title("Select Country to Analyze") window.bind('&lt;Escape&gt;', quit) UserInput = tkinter.Entry(window) UserInput.pack() ButtonClick = tkinter.Button(window, text='Enter', command=GetCountry) ButtonClick.pack(side='bottom') window.mainloop()
answers question: http://stackoverflow.com/q/49067147
has comment: http://stackoverflow.com/comment/85153633
score: 0
has comment: http://stackoverflow.com/comment/85153297
type: Answer
has comment: http://stackoverflow.com/comment/85153521

http://stackoverflow.com/comment/85153671
comment on: http://stackoverflow.com/q/49073609
score: 0
type: Comment
type: QuestionComment
has text: Welcome to SO. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)

http://stackoverflow.com/q/48991850
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/73838097
downvote count: 0
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/84988652
tagged with: sudo
favorite count: 0
has comment: http://stackoverflow.com/comment/84988588
tagged with: linux
has body: I want to get th variable TOKEN from my environment in Flask config.py: *config.py:* TOKEN = os.environ.get('TOKEN') So i export TOKEN=666 Then: $ sudo python3 manage.py shell &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ.get('TOKEN') &gt;&gt;&gt; quit() It return None. After i read this -->os.environ.get() does not return the Environment Value in windows? *local.env:* export TOKEN=666 *config.py:* TOKEN = os.environ.get('TOKEN') and $ source local.env $ echo $TOKEN 666 $ sudo python3 manage.py shell &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ.get('TOKEN') &gt;&gt;&gt; quit() so as :$ sudo python3 manage.py runserver if i print(TOKEN), it return NONE But if i run python directly: $ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ &gt;&gt;&gt; os.environ.get('TOKEN') '666' and if i set os.environ[TOKEN] = '666' directly...i can't keep it secretly:(
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42978739
tagged with: python
has title: In flask, os.environ.get() return None
has comment: http://stackoverflow.com/comment/85015171

http://stackoverflow.com/comment/85030338
has text: HAHAH ok yes I see this now. Thanks, everyone!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49012559
score: 1

http://stackoverflow.com/a/49038033
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49037998
answers question: http://stackoverflow.com/q/49037998
upvote count: 2
has body: You're trying to attach the event handler before the drop down menu is loaded into the DOM. You can use document.ready to wait until it is loaded to attach the handler $(document).ready(function(){ $(".auto-submit").change(function() { $(this).closest("form").submit(); //this.form.submit(); //less verbose }); });
has comment: http://stackoverflow.com/comment/85081662
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/85109404
type: Comment
comment on: http://stackoverflow.com/a/49051591
has text: Hrm... not sure i competely understand, but merge_asof joins on intergers, floats or datetime, therefore an extra digit is very far away on the number line. Can you trim the extra digit?
type: AnswerComment
score: 0

http://stackoverflow.com/q/48973817
favorite count: 0
tagged with: python-3.x
upvote count: 0
has comment: http://stackoverflow.com/comment/84956978
has comment: http://stackoverflow.com/comment/84956368
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84952535
accepted answer: http://stackoverflow.com/a/49005225
type: Question
downvote count: 2
has title: while writing into error: csv unsupported operand type(s) for +: 'float' and 'str'
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/49005225
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84952495
has comment: http://stackoverflow.com/comment/84978863
tagged with: python
has body: I am new to python. I have to write data into csv file but it is giving error unsupported operand type(s) for +: 'float' and 'str' with open('Csvc1s.csv', "wb") as file: file.write("Time, Total_network\'s_Belief, Total_network\'s_Disbelief, Total_network\'s_Uncertainty") file.write('\n') list1 = [float(i) for i in timeVar] list2 = [float(i) for i in beliefVar] list3 = [float(i) for i in disbelVar] list4 = [float(i) for i in uncerVar] for x in range(0,list1Len): textToWrite = (list1[x]) + "," + (list2[x]) + "," + (list3[x]) + "," + (list4[x]) file.write(textToWrite.rstrip()) file.write('\n') How can I fix this?

http://stackoverflow.com/a/49094316
has body: You could use a regular expression: import re time_list = re.findall('\d+[a-z]', received_string) The re.findall() function produces a list of all matches of a given pattern in the input string. Here the pattern looks for 1 or more digits, followed by one lower-case ASCII letter. You could make it more picky about what letters are allowed by using [ywdhms], but if your input is reasonably well-formed I'd not worry about that. Demo: &gt;&gt;&gt; import re &gt;&gt;&gt; received_string = "12y14w4d12h33m59s" &gt;&gt;&gt; re.findall('\d+[a-z]', received_string) ['12y', '14w', '4d', '12h', '33m', '59s'] You may want to further split out the digits and letters, however, to make it easier to then transform the information into an easier to work with format like a datetime.timedelta() object, perhaps into a dictionary: {type_: int(count) for count, type_ in re.findall('(\d+)([a-z])', received_string)} The added (..) groupings alter the re.findall() output to produce a tuple for each match, containing the separate group values (so ('12', 'y'), ('14', 'w'), etc.). This produces {'y': 12, 'w': 14, 'd': 4, 'h': 12, 'm': 33, 's': 59} for your input.
type: Answer
downvote count: 0
score: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49094294
upvote count: 7
answers question: http://stackoverflow.com/q/49094294
has comment: http://stackoverflow.com/comment/85193756

http://stackoverflow.com/a/49087014
type: Answer
has comment: http://stackoverflow.com/comment/85179635
has comment: http://stackoverflow.com/comment/85181685
has comment: http://stackoverflow.com/comment/85184358
has comment: http://stackoverflow.com/comment/85181610
score: 0
has comment: http://stackoverflow.com/comment/85179420
answers question: http://stackoverflow.com/q/49086903
has comment: http://stackoverflow.com/comment/85181626
has comment: http://stackoverflow.com/comment/85179576
has body: There is an invalid JSON file in your files, found out which one caused it by catching the error with try except import json import glob result = [] for f in glob.glob("/Users/EER/Desktop/JSON_Combo/*.json"): with open(f, "rb") as infile: try: result.append(json.load(infile)) except ValueError: print(f) with open("merged_file.json", "wb") as outfile: json.dump(result, outfile)

http://stackoverflow.com/q/49023895
linked to: http://stackoverflow.com/q/41876011
has answer: http://stackoverflow.com/a/49128939
has body: I am working on license plate recognition using python. I worked with tesseract for doing OCR recognition.For my project i wish to include person with disability symbol in tesseract library. I reviewed the following links for updating the tesseract library tutorial for tesseract library update I followed the steps for creating tff file but failed by notifying the image is not prescribed font. I understood from the studied literature people added various types of fonts and number style and couldn't find the information about how to add image into tesseract data set. Can anyone suggest me how could i succeed in adding the image to tesseract data set? I am grateful if someone provided me the links or information pertaining to the problem
answer count: 1
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49128939
tagged with: python-tesseract
has title: how to add person with disability (PwD) symbol to tesseract dataset
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/85111340
type: Comment
type: QuestionComment
has text: The error suggests that the engine thinks the fucntion is a script, and not a fucntion. Are you 100% sure that the contents of the file are what you shared here?
comment on: http://stackoverflow.com/q/49052756
score: 0

http://stackoverflow.com/comment/85074959
comment on: http://stackoverflow.com/q/49034403
score: 0
type: Comment
type: QuestionComment
has text: @lurker The point is: we can `INSERT into mytable VALUES(1, 2, 3)` without specifyin the col names (it automatically fits the DB structure). I would like to do the same with UPDATE, that's just that.

http://stackoverflow.com/a/49046986
answers question: http://stackoverflow.com/q/49038658
has comment: http://stackoverflow.com/comment/85106198
has comment: http://stackoverflow.com/comment/85120920
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85111664
has comment: http://stackoverflow.com/comment/85109158
type: AcceptedAnswer
downvote count: 0
has body: The problem is not in the traci part but in your adoID which is an array but should be a single id (a string) so you should probably just take the first element of that array.
accepted answer of: http://stackoverflow.com/q/49038658
type: Answer

http://stackoverflow.com/q/49007740
type: AnsweredQuestion
tagged with: regression
tagged with: equation
tagged with: loops
accepted answer: http://stackoverflow.com/a/49010155
has body: (NB: I'm very new to python and this is my first post on Stack Overflow!) I have a directory that has multiple .csv files, each with a column of Force and a column of Displacement data. I want to perform the same linear regression plot function to each of them without having to change the file name within the .py file. (Ideally I would like each equation to be an output, but for now I'm happy with multiple plots!) So far I have: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy import stats values = pd.read_csv('RawData_1.csv') slope, intercept, r_value, p_value, std_err = stats.linregress(values['Displacement'],values['Force']) ax = sns.regplot(x="Displacement", y="Force", data=values, color='b', line_kws={'label':"y={0:.1f}x+{1:.1f}".format(slope,intercept)}) ax.legend() plt.show() I've tried implementing lines from other posts but having no luck. Any help is much appreciated. Thanks :)
type: Question
has title: Automate data from multiple csv files and linear regression
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49010155
tagged with: python
tagged with: plot

http://stackoverflow.com/q/49102410
tagged with: docker
answer count: 1
favorite count: 0
has body: I'm currently using Django with Docker. I have main dispatcher Django project, and several other microservices that are running on different Docker containers. When I start up a new microservice, I want to add new Django model which has URLField pointing that microservice. But URLField doesn't accept such URLs, e.g. http://foo-service/ and it's because of these code. Of course I could define custom validator or custom field that inherits URLField, but shouldn't URLField accept those URLs?
has answer: http://stackoverflow.com/a/49105125
accepted answer: http://stackoverflow.com/a/49105125
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Django URLField doesn't accept hostname-only URLs
type: Question
downvote count: 0

http://stackoverflow.com/comment/84975200
type: QuestionComment
score: 1
has text: What are you really trying to do? 1. There is no exponential decay in your data - there are just uncorrelated random values that follow an exponential distribution. 2. You are basically minimizing this: `-np.sum(np.log(N) - 1 / L * data)`. I don't see how this should ever converge to anything meaningful.
comment on: http://stackoverflow.com/q/48984858
type: Comment

http://stackoverflow.com/q/49053033
downvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49068591
upvote count: 2
answer count: 1
has body: I am trying to use the graph transform tool on a tensorflow object detection model for tensorflow 1.4.1 in Linux Ubuntu 16.04 The instruction used is: bazel-bin/tensorflow/tools/graph_transforms/transform_graph --in_graph=/tf-optimizations/pascalvoc_gtt/frozen_inference_graph.pb --out_graph=/tf-optimizations/pascalvoc_gtt/optimized_frozen_inference_graph.pb --inputs='image_tensor' --outputs='detection_boxes,detection_scores,detection_classes,num_detections' --transforms=' add_default_attributes strip_unused_nodes(type=float) remove_nodes(op=CheckNumerics) fold_constants(ignore_errors=true) fold_batch_norms fold_old_batch_norms fuse_resize_pad_and_conv fuse_pad_and_conv fuse_resize_and_conv strip_unused_nodes sort_by_execution_order' When I try to query the optimized tensorflow graph, (boxes, scores, classes, num) = sess.run([detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded}) I get the following error: InvalidArgumentError: NodeDef mentions attr 'identical_element_shapes' not in Op&lt;name=TensorArrayV3; signature=size:int32 -&gt; handle:resource, flow:float; attr=dtype:type; attr=element_shape:shape,default=&lt;unknown&gt;; attr=dynamic_size:bool,default=false; attr=clear_after_read:bool,default=true; attr=tensor_array_name:string,default=""; is_stateful=true&gt;; NodeDef: Preprocessor/map/TensorArray = TensorArrayV3[clear_after_read=true, dtype=DT_FLOAT, dynamic_size=false, element_shape=&lt;unknown&gt;, identical_element_shapes=false, tensor_array_name="", _device="/job:localhost/replica:0/task:0/device:GPU:0"](Preprocessor/map/TensorArrayUnstack/strided_slice). (Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary.). [[Node: Preprocessor/map/TensorArray = TensorArrayV3[clear_after_read=true, dtype=DT_FLOAT, dynamic_size=false, element_shape=&lt;unknown&gt;, identical_element_shapes=false, tensor_array_name="", _device="/job:localhost/replica:0/task:0/dev…
has title: Error using tensorflow graph transform tool
tagged with: python
favorite count: 0
score: 2
tagged with: object-detection-api

rectangles
tags question: http://stackoverflow.com/q/49068622
tag name: rectangles
type: Tag

http://stackoverflow.com/a/49038060
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49037852
downvote count: 0
type: Answer
has body: For some reason you are using str() on the array, this is what causes the square brackets from array to appear in the print statement. See if the following methods suit you: print(arr) # ['C','D','E','I'] - the array itself print(str(arr)) # "['C', 'D', 'E', 'I']" - the array as string literal print(''.join(arr)) # 'CDEI' - array contents as string with no spaces print(' '.join(arr)) # 'C D E I' - array contents as string with spaces

http://stackoverflow.com/q/49018905
favorite count: 0
upvote count: 2
tagged with: python
has body: I am trying to join two pandas dataframes with the pd.DataFrame.join function, but there is a problem when I try to change the datetime of an existing index. I used: import pandas as pd import pytz import numpy as np # Creating date ranges sim_date = pd.date_range('1980-01-01', '1980-12-31', freq='1H', tz='UTC') obs_date = pd.date_range('1980-01-01', '1980-12-31', freq='1H') # Creating DataFrames with the time ranges as indices sim = pd.DataFrame(np.random.rand(len(interim_date)), index=interim_date, columns=['Sim']) obs = pd.DataFrame(np.random.rand(len(obs_date)), index=obs_date, columns=['Obs']) # Changing the timezone of the observed data index obs.index = obs.index.tz_localize('UTC').tz_convert('America/Phoenix') # Printing the result of the join print(pd.DataFrame.join(sim, obs).dropna()) Which yields: Sim Obs 1980-01-01 00:00:00+00:00 0.844345 0.117649 1980-01-01 01:00:00+00:00 0.505349 0.755907 1980-01-01 02:00:00+00:00 0.799555 0.169102 1980-01-01 03:00:00+00:00 0.194750 0.704400 1980-01-01 04:00:00+00:00 0.459079 0.241803 1980-01-01 05:00:00+00:00 0.496936 0.726264 1980-01-01 06:00:00+00:00 0.515039 0.989569 1980-01-01 07:00:00+00:00 0.271105 0.488859 1980-01-01 08:00:00+00:00 0.545269 0.434904 1980-01-01 09:00:00+00:00 0.817365 0.067979 1980-01-01 10:00:00+00:00 0.051024 0.068993 1980-01-01 11:00:00+00:00 0.170346 0.510406 1980-01-01 12:00:00+00:00 0.518609 0.583602 1980-01-01 13:00:00+00:00 0.725753 0.402805 1980-01-01 14:00:00+00:00 0.134059 0.879183 1980-01-01 15:00:00+00:00 0.304070 0.773884 1980-01-01 16:00:00+00:00 0.742448 0.158367 1980-01-01 17:00:00+00:00 0.539499 0.067725 1980-01-01 18:00:00+00:00 0.349432 0.027337 1980-01-01 19:00:00+00:00 0.549015 0.078190 1980-01-01 20:00:00+00:00 0.089871 0.878931 1980-01-01 21:00:00+00:00 0.100849 0.359007 1980-01-01 22:00:00+00:00 0.290280 0.168759 1980-01-01 23:00:00+00:00 0.074420 0.881724 1980-01-02 00:00:00+00:00 0.091413 0.820616 but when I use this: import pandas as pd import pytz import numpy as np …
tagged with: pytz
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49019165
type: Question
has title: Possible bug when joining pandas DataFrames with different Timezones
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49019165

http://stackoverflow.com/comment/110465934
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49031466
type: Comment
has text: Having an issue looking for guidance... it seems to work I get no error but my resultSet is empty and when i run insert command they arent added to the table.....

http://stackoverflow.com/a/49080203
has body: Your attempt df[df.duplicated(['col1', 'col2', 'col3'], keep=False)] works in my testing. You can leave out the column names: df[df.duplicated(keep=False)]
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/49080143
upvote count: 7
type: Answer

http://stackoverflow.com/q/49083727
has comment: http://stackoverflow.com/comment/85404351
has answer: http://stackoverflow.com/a/49207037
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85347893
tagged with: python
has comment: http://stackoverflow.com/comment/85179533
has comment: http://stackoverflow.com/comment/85353929
has body: I need help with the string.replace(" ", "") I am using google geocode and it is returning the geocode as (-1.2890979, 36.90147) --------- return latitude,longitude I have stored the geocode in a variable called location I want to send the coodinates without the brackets and without the space but location.replace give a 500 Internal server error. Any suggestions on what i can do to correct this?
has comment: http://stackoverflow.com/comment/85347978
score: 1
favorite count: 0
tagged with: geocoding
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85415765
has title: python geocode.replace(" ", "") Internal server error
tagged with: str-replace
has comment: http://stackoverflow.com/comment/85173060
has comment: http://stackoverflow.com/comment/85418811
has comment: http://stackoverflow.com/comment/85415757
downvote count: 1
has comment: http://stackoverflow.com/comment/85419063
has comment: http://stackoverflow.com/comment/85173222
has comment: http://stackoverflow.com/comment/85347706

http://stackoverflow.com/comment/84992419
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48989902
has text: Some old mailing list discussion - may be an issue with re-declaring the `cdef` parts of the class - https://www.mail-archive.com/cython-dev@codespeak.net/msg06133.html

http://stackoverflow.com/comment/85205434
type: AnswerComment
score: 0
has text: Haha well that happens... Maybe get some clarification from your instructor. Another point is that you don't account for the initial balance (so if the customer opens the credit card with $500 initially, he would not get any interest with your implementation)
type: Comment
comment on: http://stackoverflow.com/a/49099696

http://stackoverflow.com/comment/84981715
score: 0
comment on: http://stackoverflow.com/q/48988038
has text: @Divakar - unfortuantely not, I need mask with same length as `arr`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85533787
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49055725
has text: For .sh and .cgi the browser just downloads the files. Am I missing something?

http://stackoverflow.com/a/49035810
has comment: http://stackoverflow.com/comment/85110280
type: Answer
accepted answer of: http://stackoverflow.com/q/49035156
upvote count: 11
score: 11
has body: You can use PIL image but you're not actually loading the data as you would normally. Try something like this instead: import numpy as np import matplotlib.pyplot as plt for img,labels in train_data_loader: # load a batch from train data break # this converts it from GPU to CPU and selects first image img = img.cpu().numpy()[0] #convert image back to Height,Width,Channels img = np.transpose(img, (1,2,0)) #show the image plt.imshow(img) plt.show() As an update (02-10-2021): import torchvision.transforms.functional as F # load the image (creating a random image as an example) img_data = torch.ByteTensor(4, 4, 3).random_(0, 255).numpy() pil_image = F.to_pil_image(img_data) Alternatively import torchvision.transforms as transforms img_data = torch.ByteTensor(4, 4, 3).random_(0, 255).numpy() pil_image = transforms.ToPILImage()(img_data) The second form can be integrated with dataset loader in pytorch or called directly as so. I added a modified to_pil_image here essentially it does what I suggested back in 2018 but it is integrated into pytorch now.
answers question: http://stackoverflow.com/q/49035156
has comment: http://stackoverflow.com/comment/85286262
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49090099
has body: I have an external main dictionary where I store some values, and a secondary dictionary which I use to iterate with only some names and the values I define of the first dictionary, looking something like this: main_dict = { 'colors': { 'foo': 'orange', 'bar': 'blue', }, 'fruits': { 'xyz': 'apple', 'abc': 'orange', 'qwe': 'strawberry' } } secondary_dict = { 'word1': main_dict['colors']['bar'], 'word2': main_dict['fruits']['abc'], 'word3': main_dict['colors']['foo'] } #A function that iterates the keys from secondary_dict, does something, and outputs a new dictionary: new_dict = my_function(secondary_dict) And when I'm done creating that new dictionary I want to write BACK to the paths of original dictionary used as values in the secondary dictionary, but I'm not sure how to do so, so in a sense it would be kind of like doing this: secondary_dict = { 'word1': main_dict['colors']['bar'], 'word2': main_dict['fruits']['abc'], 'word3': main_dict['colors']['foo'] } To this: main_dict['colors']['bar'] = new_dict['word1'], main_dict['fruits']['abc'] = new_dict['word2'], main_dict['colors']['foo'] = new_dict['word3'] Or in (incorrect) pseudo code: for key, path in secondary_dict.items(): path = new_dict[key] One of my first ideas was to instead of directly storing the paths in the secondary_dict storing them as strings, flipping the dictionary and iterate using eval(). But from what I can gather using eval() is heavily discouraged as there is always "a better way"... So, is there any way to do what I am trying to do without using eval()? (Apologies if it is hard to understand what I'm trying to say, I realize that it is a rather specific problem)
possible better answer: http://stackoverflow.com/a/49090494
favorite count: 0
tagged with: python-3.x
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/49090494
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
answer count: 2
has title: Set values from one dictionary containing paths to another dictionary
has answer: http://stackoverflow.com/a/49090512
accepted answer: http://stackoverflow.com/a/49090512

http://stackoverflow.com/q/49043162
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/85091579
accepted answer: http://stackoverflow.com/a/49043818
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49043299
possible better answer: http://stackoverflow.com/a/49043299
tagged with: matplotlib
has title: Custom Yaxis plot in matplotlib python
has body: Let's say if I have Height = [3, 12, 5, 18, 45] and plot my graph then the yaxis will have ticks starting 0 up to 45 with an interval of 5, which means 0, 5, 10, 15, 20 and so on up to 45. Is there a way to define the interval gap (or the step). For example I want the yaxis to be 0, 15, 30, 45 for the same data set.
has answer: http://stackoverflow.com/a/49043818
type: AnsweredQuestion

http://stackoverflow.com/comment/85120701
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49057443
has text: whats this for?
score: 0

http://stackoverflow.com/comment/85035217
has text: Sorry. Here is the link to my file. https://www.dropbox.com/s/hrqjr2jgfsjs55x/PVC_Cs137.txt?dl=0
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49015129
type: Comment

http://stackoverflow.com/comment/84954492
type: Comment
has text: @erocoar It acts like a logical_not, converts True to False and vice versa.
score: 1
comment on: http://stackoverflow.com/a/48966537
type: AnswerComment

http://stackoverflow.com/comment/85200025
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49097424
has text: Yep, I knew that was the answer but was looking for a snippet with the proper syntax. The URL you provided has the snippet. Thanks
score: 0

http://stackoverflow.com/comment/84944807
type: QuestionComment
comment on: http://stackoverflow.com/q/48969623
has text: learning_logs is one of my APPS and I added this in my settings.py file. how would I import my APP here?
score: 0
type: Comment

http://stackoverflow.com/comment/85148966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49071561
has text: @Wagner I think pandas date difference is not useful in this case you should convert your pandas date into datetime and should use relativedelta because it will give you difference in year,remaining months and days . Hope it helps
score: 0

http://stackoverflow.com/comment/84951083
score: 5
type: Comment
type: QuestionComment
has text: Strange question. The Pi is a full computer, not an embedded board.
comment on: http://stackoverflow.com/q/48973038

http://stackoverflow.com/a/49103937
has body: The dictionary needs an entry with the key 'tag' already in it before you can access it. Without knowing more of the context, I can't advise further than that, though
score: 0
has comment: http://stackoverflow.com/comment/85213013
type: Answer
answers question: http://stackoverflow.com/q/49103913
has comment: http://stackoverflow.com/comment/85213088
has comment: http://stackoverflow.com/comment/85213039

http://stackoverflow.com/q/49117826
has comment: http://stackoverflow.com/comment/85242544
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/49118151
has body: I want to implement an online recursive parallel algorithm in python. So every time I got a new observation I want to calculate a new coefficient matrix. Each row on this matrix must be calculated on parallel. Is it too expensive to create for each time-step a new process that takes as an input the row of the previous time-step and calculates the row for the next and after the calculation kill it and create it again? Or is it better to have the process running for the whole time? If the second is the best of the two, how can I resume the same process but with different inputs? Is there any way?
upvote count: 1
tagged with: parallelism-amdahl
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Is it better to resume a process with different inputs in python or re-launch it?
tagged with: parallel-processing
linked to: http://stackoverflow.com/q/47587939
downvote count: 0
score: 1

http://stackoverflow.com/q/49097401
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49097458
tagged with: python
downvote count: 0
score: 1
has title: Monte Carlo March Madness Simulation
type: Question
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49097448
has body: for class I need to model predictions for the March Madness bracket... and I decided to go through Python rather than Excel. My approach is, basically, to generate x amount of random numbers, that x being each team's respective shots per game, and if that number is greater than y, which would be that respective team's shooting percentage, they would miss that shot. By doing so, scores of games and outcomes can be VERY roughly predicted. I am very new to Python but this is what I know: import random for i in range(25): print(random.random()) This gives me 25 random numbers, but now I have to compare these to the shooting percentage to each team. How do I compare all 25 of these random numbers to determine whether each is less than, say, 0.400... and count up the ones that are?
favorite count: 0

http://stackoverflow.com/comment/84977003
type: QuestionComment
has text: @PHD I wasn't just suggesting it for stylistic reasons, the logic in your current code does not work
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48985875

http://stackoverflow.com/q/49090339
has comment: http://stackoverflow.com/comment/85186226
upvote count: 1
has body: I am trying to grab the value of the version info, 1.0, in this case. If I right click and Inspect Element, I see the following: 1.0 If I copy CSS Selector in Firefox, it shows me the following: .version-numbers > div:nth-child(1) > span:nth-child(2) I am trying the following Python code: print(driver.find_element_by_css_selector(".version-numbers[value='$ctrl.backendVersion']").text) I haven't been able to get it to work with XPath either. I get an Unable to locate Element error. Any suggestions?
has answer: http://stackoverflow.com/a/49099887
has title: Unable to locate element error retrieving text value of class variable
favorite count: 0
score: 0
tagged with: element
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85186383
type: UnansweredQuestion
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/49129114
answer count: 2

http://stackoverflow.com/q/49067073
tagged with: pandas
has answer: http://stackoverflow.com/a/49067231
has body: I have 3 df's: df1=pd.DataFrame({"Name":["one","two","three"],"value":[4,5,6]}) df2=pd.DataFrame({"Name":["four","one","three"],"value":[8,6,2]}) df3=pd.DataFrame({"Name":["one","four","six"],"value":[1,1,1]}) I can append one by one but I want to append all the three data frames at a time and do some analysis. I am trying to count the name contains in how many data frame divided by total dataframes name present in dataframes/total dataframes My desired output is, Name value Count one 11 1 two 5 0.333 three 8 0.666 four 9 0.666 six 1 0.333 Please help, thanks in advance!
answer count: 1
favorite count: 0
tagged with: data-analysis
upvote count: 2
has title: how to append two or more dataframes in pandas and do some analysis
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49067231
type: Question
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/85139384

http://stackoverflow.com/comment/85154279
score: 0
has text: you must provide a [mcve]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49069305

http://stackoverflow.com/a/49117505
has body: This is mostly a response to your suggestion in the comments that CFFI functions can be made to work. This is true, but it's VERY limitted. You can convert a Cython cdef function to a CFFI function by going through a C function pointer. This conversion must take place in Cython. In order to work with Numba in nopython mode the cdef function must not take or return a Python object. This means that your Shrubbery class is not possible. A simple function that only accepts/returns C types will work from libc.stdint cimport uintptr_t cdef void f(int x) nogil: with gil: print(x+1) ctypedef void (*void_int_func_pointer)(int) def get_cffi_f(): cdef void_int_func_pointer f_ptr = f cdef uintptr_t f_ptr_int = &lt;uintptr_t&gt;f_ptr from cffi import FFI ffi = FFI() return ffi.cast('void (*)(int)',f_ptr_int) Within Python you call call get_cffi_f() to get a CFFI wrapping of f to pass to Numba functions. Note that I've declared the function as nogil and captured the GIL within it - I'm not 100% sure if Numba releases the GIL so I'm doing this to be safe. It may not be necessary. You can then pass those CFFI wrappings into Numba or access them as global variables: import numba as nb from cy import get_cffi_f func_global = get_cffi_f() @nb.jit(nopython=True) def simple_func(func): func(5) func_global(6) func(7) @nb.jitclass([('value', nb.int32)]) class Bag(object): def __init__(self,value): self.value = value def mixed_class_method(self,func): func(self.value) func_global(self.value-1) simple_func(get_cffi_f()) Bag(3).mixed_class_method(get_cffi_f()) My view is that trying to make something like a Cython class work here is a lost cause. There's probably other ways of achieving the same thing - you could get Cython to make headers with api or public and use those headers with CFFI.
type: Answer
has comment: http://stackoverflow.com/comment/85295362
score: 2
has comment: http://stackoverflow.com/comment/85296701
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85341083
accepted answer of: http://stackoverflow.com/q/49089713
answers question: http://stackoverflow.com/q/49089713
upvote count: 2

http://stackoverflow.com/a/49117818
has comment: http://stackoverflow.com/comment/85247213
score: 0
has body: A native Python approach, using itertools.product: from itertools import product #read file a, remove newline, replace commas with new delimiter and ignore empty lines a = [line[:-2].strip().replace(",", "|") for line in open("a.csv", "r") if line[:-2].strip()] #read file b, leave newline in string b = [line.replace(",", "|") for line in open("b.csv", "r") if line[:-2].strip()] #combine the two lists c = ["|".join([i, j]) for i, j in product(a, b)] #write into a new file with open("c.csv", "w") as f: for item in c: f.write(item) #output 1|a|x 1|b|y 1|c|z 2|a|x 2|b|y 2|c|z 3|a|x 3|b|y 3|c|z
answers question: http://stackoverflow.com/q/49116569
has comment: http://stackoverflow.com/comment/85243896
type: Answer
has comment: http://stackoverflow.com/comment/85243286
has comment: http://stackoverflow.com/comment/85246172
has comment: http://stackoverflow.com/comment/85290271

http://stackoverflow.com/q/48968097
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84942788
upvote count: 2
score: 0
downvote count: 2
has title: Passing nested dict to Django model
has comment: http://stackoverflow.com/comment/84941807
answer count: 1
has comment: http://stackoverflow.com/comment/84941961
has answer: http://stackoverflow.com/a/48968342
tagged with: django-models
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84941903
has body: Is it possible to pass a nested dict to Django model? I have passed single entry dicts before, such as: # create instance of model m = MyModel(**data_dict) m.save() But can I nest these entires within a dict to have them all processed vs. iterating through the dict and doing this one-by-one?
has comment: http://stackoverflow.com/comment/84941805
favorite count: 0
type: Question

python-typing
tags question: http://stackoverflow.com/q/49008718
tags question: http://stackoverflow.com/q/49095677
tags question: http://stackoverflow.com/q/48997386
tags question: http://stackoverflow.com/q/49101952
type: Tag
tags question: http://stackoverflow.com/q/49103579
tags question: http://stackoverflow.com/q/49088342
tag name: python-typing

http://stackoverflow.com/comment/85202588
comment on: http://stackoverflow.com/q/49098605
has text: Start with: `puzzle = [[''] * 9 for i in range(9)]`. Also, if you think you need to use `globals()` you are almost certainly wrong.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49042181
linked to: http://stackoverflow.com/q/1732348
score: 0
answer count: 3
tagged with: break
tagged with: python
has answer: http://stackoverflow.com/a/49042230
tagged with: regex
has comment: http://stackoverflow.com/comment/85089868
accepted answer: http://stackoverflow.com/a/49042230
has answer: http://stackoverflow.com/a/49042733
type: AnsweredQuestion
has body: I'm trying to extract some lines from an HTML source file. The one below is simplified but it's the same idea. Using the sample below, I am trying to get it to output in numerical order...that is Form 1, Form 2, Form 3, Form 4. The problem is that the second loop restarts at the second round. So I get: Form 1, Form 2, Form 3, Form 2. How can I edit so that the second loop continues to extract the Form 4 text? Code import re line = 'bla bla bla Form 1 some text... Form 2 more text?bla bla bla Form 3 some text... Form 4 more text?' for match in re.finditer(' (.*?) ', line, re.S): print match.group(1) for match1 in re.finditer(' (.*?) ', line, re.S): print match1.group(1) break
tagged with: loops
has answer: http://stackoverflow.com/a/49042394
type: Question
has title: Python - Using Regex to find multiple matches and report in a certain order
possible better answer: http://stackoverflow.com/a/49042733

http://stackoverflow.com/comment/85228644
score: 0
has text: No one on stackoverflow will mind if you include that traceback in your question. In fact, it's preferred. But you didn't answer the question about what version of websocket you're using.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49111583

http://stackoverflow.com/comment/84947751
score: 0
type: Comment
has text: Other possible solution is to sanitize the csv before using csv.reader. Sanitizing is a tricky one here.
comment on: http://stackoverflow.com/a/48971107
type: AnswerComment

http://stackoverflow.com/a/49134333
accepted answer of: http://stackoverflow.com/q/49112552
answers question: http://stackoverflow.com/q/49112552
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 21
has body: Vectorized is used in two ways when talking about numpy, and it`s not always clear which is meant. Operations that operate on all elements of an array Operations that call optimized (and in many cases multi-threaded) numerical code internally The second point is what makes vectorized operations much faster than a for loop in python, and the multithreaded part is what makes them faster than a list comprehension. When commenters here state that vectorized code is faster, they're referring to the second case as well. However, in the numpy documentation, vectorized only refers to the first case. It means you can use a function directly on an array, without having to loop through all the elements and call it on each elements. In this sense it makes code more concise, but isn't necessarily any faster. Some vectorized operations do call multithreaded code, but as far as I know this is limited to linear algebra routines. Personally, I prefer using vectorized operatios since I think it is more readable than list comprehensions, even if performance is identical. Now, for the code in question the documentation for np.char (which is an alias for np.core.defchararray), states The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations. So there are four ways (one not recommended) to handle strings in numpy. Some testing is in order, since certainly each way will have different advantages and disadvantages. Using arrays defined as follows: npob = np.array(milstr, dtype=np.object_) npuni = np.array(milstr, dtype=np.unicode_) npstr = np.array(milstr, dtype=np.string_) npchar = npstr.view(np.chararray) npcharU = npuni.view(np.chararray) This creates arrays (or chararrays for the last two) with the following datatypes…
upvote count: 21

http://stackoverflow.com/a/49013028
type: Answer
answers question: http://stackoverflow.com/q/49012294
has body: The program below should do the job a = open("Location of the file",'r') b= a.read() a.close() c = b.split() str = "" for i in c: if (((i.find('-')) != -1) and len(i)&lt;4 ): pass else: str = str+i+" " print(str) a = open("Location of the file",'w') a.write(str) a.close()
score: 0

http://stackoverflow.com/comment/123956396
type: AnswerComment
score: 0
has text: On Windows 10, Python 3.9, Anaconda3, I see Interpreter: <No interpreter> and clicking on it shows an empty dropdown menu. I have tried creating several new and existing environments but the simple scripts I have do not run.
type: Comment
comment on: http://stackoverflow.com/a/60770718

http://stackoverflow.com/comment/85203083
type: Comment
score: 1
has text: @Federico when you doing the unstack , it will change reshape your df , with index=name . column = year, in this situation , when there is missing year in your original df , it will fillna with taht , after we using stack (dropna=True), if will convert back to the format as your original df
type: AnswerComment
comment on: http://stackoverflow.com/a/49073403

http://stackoverflow.com/a/75000342
has body: If you just add a variable to a db.Model-derived calss that is a "normal" data type (i.e. a string or integer) - as opposed to a db.Column - it can be used, and does not appear to have any affect on the actual database.
score: 1
answers question: http://stackoverflow.com/q/49036259
downvote count: 0
type: Answer
upvote count: 1

amazon-redshift
tags question: http://stackoverflow.com/q/49073662
tag name: amazon-redshift
tags question: http://stackoverflow.com/q/49060160
type: Tag

terminal
tags question: http://stackoverflow.com/q/49004788
tags question: http://stackoverflow.com/q/48979900
tag name: terminal
tags question: http://stackoverflow.com/q/49066933
tags question: http://stackoverflow.com/q/49061871
type: Tag
tags question: http://stackoverflow.com/q/49058403
tags question: http://stackoverflow.com/q/49094724
tags question: http://stackoverflow.com/q/48991251

http://stackoverflow.com/comment/85229411
has text: these are class methods, are not these? Sorry, let me update the question with example data return from methods
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49112201
type: Comment

http://stackoverflow.com/comment/85151458
score: 0
type: AnswerComment
has text: also in the gist the property inside k8.yaml-- dmnginxservice is cluster and not clusterType
type: Comment
comment on: http://stackoverflow.com/a/49069479

http://stackoverflow.com/q/49106371
has title: Speeding a numpy correlation program using the fact that lists are sorted
has body: I am currently using python and numpy for calculations of correlations between 2 lists: data_0 and data_1. Each list contains respecively sorted times t0 and t1. I want to calculate all the events where 0 &lt; t1 - t0 &lt; t_max. for time_0 in np.nditer(data_0): delta_time = np.subtract(data_1, np.full(data_1.size, time_0)) delta_time = delta_time[delta_time &gt;= 0] delta_time = delta_time[delta_time &lt; time_max] Doing so, as the list are sorted, I am selecting a subarray of data_1 of the form data_1[index_min: index_max]. So I need in fact to find two indexes to get what I want. And what's interesting is that when I go to the next time_0, as data_0 is also sorted, I just need to find the new index_min / index_max such as new_index_min &gt;= index_min / new_index_max &gt;= index_max. Meaning that I don't need to scann again all the data_1. (data list from scratch). I have implemented such a solution not using the numpy methods (just with while loop) and it gives me the same results as before but not as fast than before (15 times longer!). I think as normally it requires less calculation, there should be a way to make it faster using numpy methods but I don't know how to do it. Does anyone have an idea? I am not sure if I am super clear so if you have any questions, do not hestitate. Thank you in advance, Paul
type: UnansweredQuestion
tagged with: numpy
has comment: http://stackoverflow.com/comment/85218165
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49115367
type: Question
tagged with: python
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/85189418
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49091967
type: Comment
has text: Sorry to ask for more but I guess that wasn't the problem I had. I kept getting an error saying inconsistent use of tabs and spaces in indentation. Here is my little part. while 1: result = m.mailBox() if result: c = re.search("<a href=\".*?(?=\")", str(yourDict["body"])) print(c.group()) else: print(result) time.sleep(2)

http://stackoverflow.com/comment/85107700
score: 1
type: AnswerComment
type: Comment
has text: `islice` returns an *iterator*.
comment on: http://stackoverflow.com/a/49051527

http://stackoverflow.com/comment/85248998
has text: The two-watch problem: "A man with a watch knows what time it is. A man with two watches is never sure."
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49115648
type: Comment

http://stackoverflow.com/a/49046042
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49042486
has body: As already noted, you loop the range and then test whether those numbers are in the set, but that check does not make sense. Instead, you should just loop the elements and print them directly. def printSet (A): for i in A: print(set(i), end="") But this does not really print those in "standard set notation". For example, the surrounding {...} are missing, and the empty set will print as set(). Instead, you can use something like this: def printSet (A): print("{" + ", ".join(str(set(i)) if i else "{}" for i in A) + "}") Output for printSet(powerset(randomSet(5, 10))): {{8, 9, 5, 6, 0}, {8, 9, 5, 6}, {8, 9, 5, 0}, {8, 9, 5}, {8, 0, 5, 6}, {8, 5, 6}, {8, 0, 5}, {8, 5}, {8, 9, 6, 0}, {8, 9, 6}, {8, 9, 0}, {8, 9}, {8, 0, 6}, {8, 6}, {8, 0}, {8}, {0, 9, 5, 6}, {9, 5, 6}, {0, 9, 5}, {9, 5}, {0, 5, 6}, {5, 6}, {0, 5}, {5}, {0, 9, 6}, {9, 6}, {0, 9}, {9}, {0, 6}, {6}, {0}, {}} For more levels of nesting, you could make a recursive function. Note that this does not print but return the result, i.e. you'd have to do print(tostr(...)). def tostr(A): if isinstance(A, (list, tuple, set, frozenset)): return "{" + ", ".join(map(tostr, A)) + "}" else: return str(A)
downvote count: 0
score: 1

http://stackoverflow.com/a/49026316
has comment: http://stackoverflow.com/comment/85060042
has body: Since you know AsyncHTTPClient is asynchronous, that means, the requests will run in background. So, when the for loop is finished, that does not mean all the requests are also finished - they are running in the background even when the loop finishes. That is why self.data is empty, because the requests aren't completed yet. How to fix this As you know the handle_response callback is called after every request is completed. You can call do_something function from this callback when all the requests are completed. Like this: def handle_response(...): ... if self.counter == self.number: self.do_something(self.data) print("Finish response")
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49013757
accepted answer of: http://stackoverflow.com/q/49013757

http://stackoverflow.com/comment/85076872
comment on: http://stackoverflow.com/q/49035843
type: QuestionComment
type: Comment
has text: and include a runnable piece of code
score: 0

http://stackoverflow.com/a/48973212
type: Answer
has comment: http://stackoverflow.com/comment/84957390
has body: Check this: class Student(): def __init__(self, no, name, departmant): self.no = no self.name = name self.departmant = departmant self.inputMessage = { self.no: 'student number to add: ', self.name: 'name of student to add: ', self.departmant: 'name of departmant to add: ' } self.studentList = [] def add(self): studentDict = {} for key, value in self.inputMessage.items(): userInput = input(value) if key == self.no: userInput = int(userInput) studentDict[key] = userInput self.studentList.append(studentDict) def show_students(self): for student in self.studentList: print("{}: {}".format(self.no, student[self.no])) print("{}: {}".format(self.name, student[self.name])) print("{}: {}".format(self.departmant, student[self.departmant])) def exit(self): print("exit...") sys.exit(0) if __name__ == "__main__": studentClass = Student("no", "name", "departmant") studentClass.add() print("Result:") studentClass.show_students() When you put variable in your class __init__ don't forget to add them when you instantiate your class. Instantiate your class first. Then call the add method. The add method is going to iterate through a dictionary that contains the name of the entry and the input sentence that you want to display. Thus it will have you fill all threee values. You'd better add your students into a list this way you can use the add method more than once and create a repository of students. Finally, I added a show_student so that you can see the result you will obtain.
has comment: http://stackoverflow.com/comment/84958513
has comment: http://stackoverflow.com/comment/84958890
answers question: http://stackoverflow.com/q/48972758
score: 0

http://stackoverflow.com/q/48983828
has answer: http://stackoverflow.com/a/48984962
type: UnansweredQuestion
has title: pyglet not running as expected in MacOS
type: Question
tagged with: pyglet
tagged with: pyopengl
has body: I was implementing simple text translation using pyglet. It works perfectly when there is no config added in window = pyglet.window.Window(). However, the code does not run after config is added in line 8. I am using Mac High Sierra. import pyglet platform = pyglet.window.get_platform() display = platform.get_default_display() screen = display.get_default_screen() template = pyglet.gl.Config() config = screen.get_best_config(template) window = pyglet.window.Window(config=config) label = pyglet.text.Label('Hello, world', x=window.width//2, y=window.height//2, anchor_x='center', anchor_y='center') def update(dt): #print(dt) # time elapsed since last time we were called label.x += 1 label.y += 1 @window.event def on_draw(): window.clear() label.draw() pyglet.clock.schedule(update) # cause a timed event as fast as you can! pyglet.app.run()
answer count: 1
score: 0
tagged with: python
tagged with: macos

http://stackoverflow.com/q/49106763
tagged with: python
type: AnsweredQuestion
tagged with: pyqt5
type: Question
tagged with: desktop-application
has title: Can't Insert array data into QTableWidget PyQt5
tagged with: qt5
score: 0
has body: I am making a desktop app for scientific purposes, and I am struggling to find info on the topic. I have the code that scans the specific folder of excel files and saves its names and paths sample_directory_2 = [] sample_files_2 = [] for (dirpath, dirnames, filenames) in walk('./Processed'): filenames = [f for f in filenames if not f[0] == '.'] sample_files_2.extend(filenames) break the_dir = "Processed" paths_2 = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')] sample_directory_2.append(sample_files_2) sample_directory_2.append(paths_2) Further, I have a piece of code, which gets the data from these files processed_info = [] for i in range(len(sample_directory_2[0])): file_info = [] sample_file_2 = sample_directory_2[0][i] sample_path_2 = sample_directory_2[1][i] sample_info_2 = pd.read_excel(ospath(sample_path_2), header = None, sheetname = 3) sample_info_2 = sample_info_2.iloc[0][0:3] file_info.append(sample_file_2) sample_info_2_list = numpy.array(sample_info_2).tolist() file_info.extend(sample_info_2_list) processed_info.append(file_info) It is saved into an array [['sample1 (02:03:2018 14-38).xlsx', 3892.523626752876, 18.64406779661017, 0.6938147012986077], ['sample2 (02:03:2018 14-38).xlsx', 6135.581250460564, 79.66101694915254, 0.6072608909734578], ['sample3 (02:03:2018 14-38).xlsx', 3461.456815612303, 5.084745762711865, 0.676008795372024], ['sample4 (05:03:2018 07-28).xlsx', 6135.581250460564, 79.66101694915254, 0.6072608909734578]] How to insert these pieces of data into QTableWidget cells, where each list (for example:['sample1 (02:03:2018 14-38).xlsx', 3892.523626752876, 18.64406779661017, 0.6938147012986077]) is inserted as a new row with 4 columns? UPD: Found a way to add an item with for row in range(len(processed_info)): for column in range(len(processed_info[row])): self.clickSample_list.setItem(row, column, QTableWidgetItem(processed_info[row][column])) but, for some reason, it ad…
answer count: 1
has answer: http://stackoverflow.com/a/49108791
accepted answer: http://stackoverflow.com/a/49108791

http://stackoverflow.com/a/49009661
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85030840
type: Answer
has comment: http://stackoverflow.com/comment/85030887
has comment: http://stackoverflow.com/comment/85030918
has comment: http://stackoverflow.com/comment/85023719
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49009475
has comment: http://stackoverflow.com/comment/85024840
answers question: http://stackoverflow.com/q/49009475
has body: This is one way: import numpy as np import sklearn as sk from sklearn.metrics import pairwise as pw df = pd.DataFrame({ "A": [1,2,3,4,5], "B": [6,7,8,9,10], "C": [7,8,1,9,10], "D": [2,3,4,5,6], }) df['E'] = df.apply(lambda row: pw.cosine_similarity(np.array([row['A'], row['B']]), np.array([row['C'], row['D']]))[0][0], axis=1) # A B C D E # 0 1 6 7 2 0.429057 # 1 2 7 8 3 0.594843 # 2 3 8 1 4 0.993533 # 3 4 9 9 5 0.798815 # 4 5 10 10 6 0.843661 A more easily extendible solution: df['E'] = [pw.cosine_similarity(i, j)[0][0] for i, j in \ zip(df[df.columns[:2]].values, df[df.columns[2:]].values)] Functional alternative: df['E'] = list(map(lambda i, j: pw.cosine_similarity(i, j)[0][0], df[df.columns[:2]].values, df[df.columns[2:]].values))
score: 1

http://stackoverflow.com/a/48972207
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/84949527
has comment: http://stackoverflow.com/comment/84949564
type: Answer
score: 6
has body: It's not quite clear on what you mean by arguments if it should be in the query string or arguments to a view. Either way, below is both solutions; redirect accepts args and kwargs redirect('new_view', flag='show') # This is the argument of a view or redirect('{}?flag=True'.format(reverse('new_view')) Then you can access it in the view like so show_flag = bool(request.GET.get('flag', False))
answers question: http://stackoverflow.com/q/48972160

http://stackoverflow.com/comment/85058816
comment on: http://stackoverflow.com/q/49026466
score: 0
type: Comment
type: QuestionComment
has text: So you run your script every 30 min, and if the number was 52400 in the previous run and now it is 53100 it should do something? In that case you will need a place (such as a file on disk) to persistently store the last number. Alternatively, use a loop and sleep inside.

http://stackoverflow.com/comment/128603629
type: AnswerComment
comment on: http://stackoverflow.com/a/52072580
type: Comment
has text: Doesn't solve the problem for me :(
score: 2

http://stackoverflow.com/a/49083784
has body: For first create new column by transform with first and multiple by C column: df['point'] = df.groupby('A')['B'].transform('first').mul(df['C']) print (df) A B C point 0 Bob 10 2 20 1 Bob 11 8 80 2 Sarah 23 -2 -46 3 Sarah 24 4 92 4 Jack 19 -4 -76 5 Jack 21 -1 -19 And then filter first all rows by condition and get only first rows by drop_duplicates - keep='first' is by default: df1 = df[df['point'] &gt; 50].drop_duplicates('A') print (df1) A B C point 1 Bob 11 8 80 3 Sarah 24 4 92 Then filter rows which are not in df1.A column by isin and inverted condition by ~, again drop_duplicates with keep last rows only: df2 = df[~df['A'].isin(df1['A'])].drop_duplicates('A', keep='last') print (df2) A B C point 5 Jack 21 -1 -19 Last use concat with dict comprehension for final dictionary: d = {k: v for k, v in pd.concat([df1, df2]).groupby('A')} print (d) {'Bob': A B C point 1 Bob 11 8 80, 'Jack': A B C point 5 Jack 21 -1 -19, 'Sarah': A B C point 3 Sarah 24 4 92}
accepted answer of: http://stackoverflow.com/q/49083649
answers question: http://stackoverflow.com/q/49083649
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/comment/84971163
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48976797
has text: Possibly a dupe of https://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield (I suppose wagtail is Django under the hood)
score: 0

http://stackoverflow.com/comment/85179352
type: Comment
comment on: http://stackoverflow.com/q/49086789
score: 0
has text: @Pam Attached a image to the question, I tried doing that, Please check!
type: QuestionComment

http://stackoverflow.com/comment/85101286
has text: When running the code without the `New_Toplevel_1` (is this your own class?) and assigning Tk() to welWindow, this code only displays one window. So maybe the New_Toplevel_1 is not implementing the destroy properly?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49048124

http://stackoverflow.com/a/49117143
answers question: http://stackoverflow.com/q/49117074
downvote count: 0
type: Answer
upvote count: 3
score: 3
has body: You can try with this: import pip def install(package): pip.main(['install', package]) try: import your_module except ImportError: print 'Module not installed' install('your_module')

http://stackoverflow.com/q/48974896
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48975161
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48975108
has title: Iterating dataframe by unit of time instead of row by row
tagged with: python
type: UnansweredQuestion
type: Question
has body: I have a pandas.DataFrame that something looks like this: Time(minutes) column2 column1 420 1 5 420 2 10 420 3 8 421 1 4 421 2 9 421 3 7 I know how to iterate row by row using iterrows(), but is there an efficient way to iterate by unit of time in the column (Time) so that I can work with data for that given time in each iteration? Something like: time = 420 while(time &lt;= max_time): temp &lt;- fetch the sub-dataframe for given time process(temp) update original df with temp #guaranteed it won't affect any other rows other than the current set of rows time += 1
has comment: http://stackoverflow.com/comment/84954681
tagged with: dataframe
score: 4
upvote count: 4

http://stackoverflow.com/comment/85230847
score: 0
type: Comment
type: QuestionComment
has text: I think it's called `chunk`; it's not in the module itself, but in the cookbook section near the end of the documentation.
comment on: http://stackoverflow.com/q/49074059

tabs
type: Tag
tags question: http://stackoverflow.com/q/48992583
tags question: http://stackoverflow.com/q/49030036
tag name: tabs

http://stackoverflow.com/comment/85139054
type: Comment
type: QuestionComment
has text: done sir ... now can you suggest some???
score: 0
comment on: http://stackoverflow.com/q/49066831

http://stackoverflow.com/q/48977369
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48977458
tagged with: python
tagged with: dictionary
has title: pandas df to nested dictionary for sparse matrix
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48977458
tagged with: group-by
tagged with: sparse-matrix
score: 0
has body: I'm seeking to convert my dataframe into a nested dictionary for later configuration of the data into a sparse matrix of similar artists. My attempt below is almost complete, but I'm unsure how to properly change what's a nested list into dictionary. Here is sample data: user artist plays 00001411dc427966b17297bf4d69e7e193135d89 animal collective 1373 00001411dc427966b17297bf4d69e7e193135d89 sting 1323 fffe8c7f952d9b960a56ed4dcb40a415d924b224 none more black 117 fffe8c7f952d9b960a56ed4dcb40a415d924b224 queen 117 Here is my code: user_artist_dict = user_artist_plays.groupby('users').artist.apply(list).to_dict() I envision the result to be {‘user1’: {‘artist’: plays, 'artist2': plays, 'artist3': plays}, 'user2': {‘artist’: plays, 'artist2': plays, 'artist3': plays}}

http://stackoverflow.com/a/49059113
has body: This is one straightforward method: lookup['D'] = lookup['C'].map(data.set_index('A')['B']) You can also reach this result via pd.merge, but the above is likely more efficient. Explanation data.set_index('A')['B'] creates a pd.Series mapping 'A' to 'B'. This works because the indices are unique. pd.Series.map can take a series as an input.
score: 0
has comment: http://stackoverflow.com/comment/85324379
type: Answer
answers question: http://stackoverflow.com/q/49058596

http://stackoverflow.com/q/49117304
score: 1
upvote count: 1
type: Question
tagged with: python-2to3
has comment: http://stackoverflow.com/comment/85239930
has comment: http://stackoverflow.com/comment/85240092
has comment: http://stackoverflow.com/comment/85240113
downvote count: 0
accepted answer: http://stackoverflow.com/a/49117428
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has title: BeautifulSoup HTMLparsingError between Python2 and Python3
has body: I run a bs4 program on Python27, it works faultless, I am having a problem once I used Python3. I am using updated version of bs4 for both. The file I am running this on is html and I noticed the error is on a tag. Is there a supporting module I need to update? like lxml? Code: from bs4 import BeautifulSoup data = open(directory +'\\'+ file) soup = BeautifulSoup(data, 'html.parser') Here is the error: ... File "C:\Anaconda3\lib\html\parser.py", line 174, in error raise HTMLParseError(message, self.getpos()) html.parser.HTMLParseError: unknown status keyword 'NKXE' in marked section, at line 318, column 49 Always appreciate the help!
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49117428

http://stackoverflow.com/q/49101649
type: UnansweredQuestion
tagged with: selenium
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/49101740
has title: Passing session ID from Selenium to Python Requests
has body: 100% Python noob, so I apologize if any terms or phrases I use are incorrect or ambiguous I am trying to go to a random word generator website, refresh the random words generated from the default, scrape the website after the refresh, ingest the words, sort them alphabetically, then print the pre-sorted and post-sorted lists to the screen. This is the website url: https://www.randomlists.com/random-words I am using the latest version of Python 3.x, which comes with Requests, and I have installed Selenium using Pip. Here's what I have been able to successfully do: Use Selenium to pass a refresh command to the website and generate a new list of words Use Requests to scrape the default words from the website. Sort the default word list alphabetically Print the pre-sorted and post-sorted default word lists to the screen Here's what I can't do that I want to do: Use Selenium to refresh the website from the default Then use Requests to scrape the refreshed words from the website Then sort alphabetically and print to the screen, pre-sort and post-sort. I've discovered that the reason for this is that Selenium and Requests are each using their own "instances", represented by Session IDs, of the website. So (finally) here is my question - how do I pass the captured Session ID from the website refreshed with Selenium to Requests which I then use to scrape the refreshed word list rather than the default word list? All of the topics around this issue have dealt with passing a username and password login session from one to the other, which isn't what I'm trying to do here. My apologies if this question has been already asked - I spent several hours today researching, but was not able to find anything with my, specific scenario. More than happy to post a copy of my current code if necessary. Thanks! Edit to add code below options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument("--test-type") options.binary_location = "/usr/bin…
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/85208588
tagged with: python
has comment: http://stackoverflow.com/comment/85232260
tagged with: selenium-webdriver
tagged with: python-3.x

http://stackoverflow.com/a/49089338
downvote count: 1
has comment: http://stackoverflow.com/comment/85184327
has comment: http://stackoverflow.com/comment/85184310
has comment: http://stackoverflow.com/comment/85185443
has body: You can query the underlying numpy array instead of the original dataframe: %timeit df[(df["A"] == 0) &amp; (df["B"] &gt; 1) ] #1000 loops, best of 3: 1.23 ms per loop ar = df.values %timeit ar[(ar[:,0] == 0) &amp; (ar[:,1] &gt; 1)] #100000 loops, best of 3: 11.5 µs per loop If you want to preserve the original index, convert it to a column before running the query and then back to the index.
has comment: http://stackoverflow.com/comment/85184285
has comment: http://stackoverflow.com/comment/85184422
type: Answer
answers question: http://stackoverflow.com/q/49089238
has comment: http://stackoverflow.com/comment/85184335
score: 2
has comment: http://stackoverflow.com/comment/85184365
upvote count: 3
has comment: http://stackoverflow.com/comment/85184345

http://stackoverflow.com/comment/85217458
has text: @Hsin have a look
type: Comment
comment on: http://stackoverflow.com/a/49026856
score: 0
type: AnswerComment

http://stackoverflow.com/a/49062478
has comment: http://stackoverflow.com/comment/85130336
has comment: http://stackoverflow.com/comment/85151551
type: Answer
has body: The fundamental intent in Python has changed over time. At the start, and until late in the development of Python 2, it was essentially the case that any two objects could be compared. Even mixed-type comparisons that made no intuitive sense, like: &gt;&gt;&gt; 3 &lt; [1] True In cases like that, it was actually the string names of the types that were compared, and the result above was due to that, as strings, "int" &lt; "list". This was driven mostly by a misguided (in hindsight) attempt to impose a total ordering on all objects. Looking ahead to Python 3, the intent changed, and started to be implemented with the datetime module types (which were introduced in Python 2): mixed-typed &lt;, &lt;=, &gt;, and &gt;= comparisons that made scant intuitive sense were to raise exceptions instead, while senseless mixed-type == would always return False and senseless mixed-type != always True. &gt;&gt;&gt; import datetime &gt;&gt;&gt; n = datetime.datetime.now() &gt;&gt;&gt; n &lt; 3 Traceback (most recent call last): ... TypeError: can't compare datetime.datetime to int &gt;&gt;&gt; n &gt;= 3 Traceback (most recent call last): ... TypeError: can't compare datetime.datetime to int &gt;&gt;&gt; n == 3 False &gt;&gt;&gt; n != 3 True Python 3 strives to act "like that" generally. Of course there are exceptions. For example, when comparing objects of different numeric types (like integers and floats), they're usually coerced to a common type under the covers. I was deeply involved in these decisions (and wrote the datetime module), so you can trust me on that. But as to what C++ intends, you'll have to ask someone else ;-) A Bit More Info I should add that, up until the introduction of "rich comparisons" in Python 2, all comparisons funneled through a cmp() protocol: in the CPython implementation, comparing two objects returned one of the integers in [-1, 0, 1]. __cmp__() methods had no idea which of &lt;, &lt;=, ==, !=, &gt;, and &gt;= was actually desired. So while the "compar…
has comment: http://stackoverflow.com/comment/85135240
has comment: http://stackoverflow.com/comment/85130441
score: 30
accepted answer of: http://stackoverflow.com/q/49062365
answers question: http://stackoverflow.com/q/49062365
has comment: http://stackoverflow.com/comment/85144420
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85134491
upvote count: 30

http://stackoverflow.com/comment/85194706
comment on: http://stackoverflow.com/q/49094597
score: 0
type: QuestionComment
type: Comment
has text: Did you try installing older tensorflow versions? pip install tensorflow==1.4 or 1.3 or 1.2?

http://stackoverflow.com/q/49082214
possible better answer: http://stackoverflow.com/a/49082332
type: AnsweredQuestion
has body: I was building a form for file uploads that is only visible to a student type of account. And I wanted that after the student submits the form, it will not show a second time, so in my Student model I used a boolean for that. After submission it will become true and the form should not appear again. Problem is, the boolean doesn't change value, so I think there is something wrong with the view. class StudentFileUpload(models.Model): course = models.ForeignKey("Course", related_name='files', on_delete=None, default=None) files = models.FileField(upload_to='student_files', null=True, blank=True) comment = models.CharField(max_length=100, blank=True) user = models.OneToOneField('courses.User', on_delete=models.CASCADE, primary_key=True, blank=True, default=None) def __str__(self): return str(self.files) def file_link(self): if self.files: return "download" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None) phone = models.CharField(max_length=15, null=True, blank=True, default=None, validators=[RegexValidator(regex='^[a-zA-Z0-9+]+$', message='Not a valid phone number.')], ) file_status = models.BooleanField(default=False) {% if user.is_student %} {{ user.student.file_sta…
answer count: 2
has title: Form boolean attribute won't change value after submission
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85171329
has answer: http://stackoverflow.com/a/49094487
has answer: http://stackoverflow.com/a/49082332
accepted answer: http://stackoverflow.com/a/49094487
tagged with: django
type: Question

grid
tags question: http://stackoverflow.com/q/48970332
tag name: grid
type: Tag

http://stackoverflow.com/a/48975157
answers question: http://stackoverflow.com/q/48974527
score: 0
type: Answer
has body: This is a very common problem, here is a quick solution. Before posting makes sure you try different code. In this example, I use an input file and output file (2 files to do it). infile = "file1.txt" outfile = "file2.txt" delete_list = ["Alex"] fin = open(infile) fout = open(outfile, "w+") for line in fin: for word in delete_list: line = line.replace(word, "") fout.write(line) fin.close() fout.close()

http://stackoverflow.com/comment/84992392
has text: I see. I can get that if I run what you've mentioned. If I could question you a little further, I've uploaded an image of the sparse matrix for `h_test` below in this comment. Can you tell me what it is and how exactly I should read this? It's really interesting but I feel a little out of my depth: https://imgur.com/a/rfZMK
type: AnswerComment
comment on: http://stackoverflow.com/a/48993441
score: 0
type: Comment

http://stackoverflow.com/q/49035368
downvote count: 0
possible better answer: http://stackoverflow.com/a/64949966
has answer: http://stackoverflow.com/a/64949966
answer count: 3
has comment: http://stackoverflow.com/comment/85082465
has answer: http://stackoverflow.com/a/49035652
favorite count: 0
tagged with: timer
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85079931
has answer: http://stackoverflow.com/a/62861507
has title: Is it possible to pass kwargs to the after() function in Tkinter?
tagged with: python
type: AnsweredQuestion
has body: I cannot find anything on google and I know that the syntax is after(delay_ms, callback=None, *args), so in a way already kinda know the answer... but anyway, I was wondering if it was possible to pass also *kwargs into it, and how. I mean something like this: frame.after(1000, button1.pack, side='left', fill='y') For example, in the script below, can I rewrite it so that I don't have to define the respawn function myself, and simply call the btn.pack method in the after()? import tkinter as tk def click(*args): btn.pack_forget() btn.after(1000, btn_respawn, tk.RIGHT, tk.Y) def btn_respawn(side, fill): btn.pack(side=side, fill=fill) root = tk.Tk() frame = tk.Frame(root, width=300, height=100, bg='orange') btn = tk.Button(frame, text="test button", font=("Consolas", 14)) frame.pack_propagate(0) frame.pack() btn.pack(side=tk.LEFT, fill=tk.Y) btn.bind("&lt;Button-1&gt;", click) root.mainloop()
score: 1
accepted answer: http://stackoverflow.com/a/49035652
upvote count: 1
type: Question

http://stackoverflow.com/comment/85140016
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49067278
has text: Waou, thks a lot, indeed it looks like to another question, but you take into account special cases so I do not know what to do.
score: 0

conv-neural-network
tags question: http://stackoverflow.com/q/48971221
tags question: http://stackoverflow.com/q/48964836
tags question: http://stackoverflow.com/q/49109014
tags question: http://stackoverflow.com/q/49017331
tags question: http://stackoverflow.com/q/49089025
type: Tag
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/49016723
tags question: http://stackoverflow.com/q/49051295
tags question: http://stackoverflow.com/q/49020509
tags question: http://stackoverflow.com/q/49103096
tags question: http://stackoverflow.com/q/49112683
tags question: http://stackoverflow.com/q/49013181
tags question: http://stackoverflow.com/q/49048758
tags question: http://stackoverflow.com/q/49103657
tags question: http://stackoverflow.com/q/49079115
tags question: http://stackoverflow.com/q/49007066
tags question: http://stackoverflow.com/q/49056451
tags question: http://stackoverflow.com/q/49075760

http://stackoverflow.com/q/48992036
has comment: http://stackoverflow.com/comment/84989435
has comment: http://stackoverflow.com/comment/84989322
has comment: http://stackoverflow.com/comment/84989144
accepted answer: http://stackoverflow.com/a/48992290
type: AnsweredQuestion
answer count: 1
tagged with: shell
favorite count: 0
has comment: http://stackoverflow.com/comment/84989234
type: Question
upvote count: 1
tagged with: python
tagged with: openfoam
has comment: http://stackoverflow.com/comment/84989111
tagged with: subprocess
has title: Python - using os.subprocess to call a shell script with nested commands
score: 0
has answer: http://stackoverflow.com/a/48992290
has body: I'm utilizing python to run a top level genetic algorithm to optimize 3D aircraft wing geometry for aerodynamic performance using OpenFOAM. I'm running Ubuntu 16.04, Python 3.6, and OpenFOAM 5. I have written several shell scripts that reside in the OpenFOAM case directory (directory containing geometry STL files, fluid dynamic parameters, and mesh). These scripts execute repetitive file management commands and OpenFOAM parallel process decomposition programs, along with commands that generate the 3D mesh and run the simulation. The python script should be in a different directory entirely because hundreds (if not thousands) of these case folders will be generated as offspring of the genetic algorithm. The problem is that using os.subprocess to call these shell scripts seems to generate and terminate a shell for each command in the script. For instance, if my code is (brief version): #!/bin/bash rm constant/polyMesh/* rm constant/triSurface/*.eMesh rm -rf 0.* find -type d -name '*e-0*' -exec rm -r {} + decomposePar (OpenFOAM utility) and I call said script with: subprocess.Popen(['./shellScript'],cwd=r'./pathToDirectory') I end up getting the error: ./shellScript: line #: decomposePar no such file or directory The only way I can see this happening if the shell is attempting to execute decomposePar in a directory other than the case directory (where it should go off without a hitch). For the case management commands, only the first command seems to work. I've scraped stack overflow for a solution to this problem but I'm not sure that I've found one. I've tried to set the working directory of the python script using os.chdir('casePath'), setting the cwd='casePath', and several other subprocess arguments that I don't quite understand! I know that I can just transcribe each shell command into Python, but I find it will be extremely tedious due to the number of shell commands and the potential for change to these shell scripts in the future. I'd like my method to be modu…
downvote count: 1

virtualenv
tags question: http://stackoverflow.com/q/49059669
tags question: http://stackoverflow.com/q/49040017
tags question: http://stackoverflow.com/q/49034824
tags question: http://stackoverflow.com/q/49000112
tags question: http://stackoverflow.com/q/48964177
tags question: http://stackoverflow.com/q/49017738
tags question: http://stackoverflow.com/q/49054463
tags question: http://stackoverflow.com/q/49013275
tag name: virtualenv
tags question: http://stackoverflow.com/q/49071121
tags question: http://stackoverflow.com/q/49098953
tags question: http://stackoverflow.com/q/49121286
tags question: http://stackoverflow.com/q/48964492
tags question: http://stackoverflow.com/q/49077277
tags question: http://stackoverflow.com/q/49006476
tags question: http://stackoverflow.com/q/49002274
tags question: http://stackoverflow.com/q/49076671
tags question: http://stackoverflow.com/q/49094597
type: Tag
tags question: http://stackoverflow.com/q/48976670

http://stackoverflow.com/a/49012742
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49007066
has comment: http://stackoverflow.com/comment/85051806
answers question: http://stackoverflow.com/q/49007066
score: 1
has body: This seems to be a very simple problem. There is very little structure inside the data, so I think you could try to reduce the depth of the neural network by removing the last two convolution and max pooling layers. Instead increase the number of nodes in the fully-connected layer, like this: model = Sequential() model.add(Conv2D(32, 3, activation='relu', input_shape=[100, 100, 1])) model.add(MaxPool2D()) model.add(BatchNormalization()) model.add(Conv2D(64, 3, activation='relu')) model.add(MaxPool2D()) model.add(BatchNormalization()) model.add(Flatten()) model.add(Dense(1000, activation='relu')) model.add(Dense(3, activation='softmax')) You could also try to use some image augmentation techniques like shifting and rotating to increase your dataset. Then I expect the convnet to outperform the standard mlp. Best

http://stackoverflow.com/q/48985817
type: UnansweredQuestion
has title: I just append a number to one list in a list, but why do all lists in the list' change?
linked to: http://stackoverflow.com/q/240178
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/84976121
type: Question
has answer: http://stackoverflow.com/a/48985842
score: -1
duplicate of: http://stackoverflow.com/q/240178
upvote count: 3
has body: In [33]: x=[[]]*6 In [34]: x Out[34]: [[], [], [], [], [], []] In [35]: x[0] Out[35]: [] In [36]: x[0].append(1) In [37]: x Out[37]: [[1], [1], [1], [1], [1], [1]] I just append 1 to x[0], but why do all lists in the list x change?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84976105

http://stackoverflow.com/comment/85015225
has text: Thanks a lot for the reply but I'm blank right now. so can you please tell me what exactly to do? I came to know that we can execute in the shell just now. so I hope you understand my situation.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49004205
type: Comment

http://stackoverflow.com/comment/84971282
has text: And what is `print(patientGuid)` ? It is weird.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48982484

http://stackoverflow.com/comment/85242796
has text: @Andersson, interesting. I have been using Explicit waits to override my Implicit waits for a very long time and have never noticed anything (probably because my implicit time is short relative to my explicit times). Even though the polling time is influencing my explicit time, I will continue to use it as I have, it is more effective in my case to use a short implicit and longer explicit when needed. Thanks.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49115992

http://stackoverflow.com/q/49120376
tagged with: web-crawler
type: Question
has body: I am trying to recursively crawl a Wikipedia url for all English article links. I want to perform a depth first traversal of n but for some reason my code is not recurring for every pass. Any idea why? def crawler(url, depth): if depth == 0: return None links = bs.find("div",{"id" : "bodyContent"}).findAll("a" , href=re.compile("(/wiki/)+([A-Za-z0-9_:()])+")) print ("Level ",depth," ",url) for link in links: if ':' not in link['href']: crawler("https://en.wikipedia.org"+link['href'], depth - 1) This is the call to the crawler url = "https://en.wikipedia.org/wiki/Harry_Potter" html = urlopen(url) bs = BeautifulSoup(html, "html.parser") crawler(url,3)
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49123421
has comment: http://stackoverflow.com/comment/85246438
tagged with: python
accepted answer: http://stackoverflow.com/a/49123421
type: AnsweredQuestion
score: 2
has title: Web crawler recursively BeautifulSoup
upvote count: 2
has comment: http://stackoverflow.com/comment/85250686

http://stackoverflow.com/q/49103097
tagged with: pandas
has comment: http://stackoverflow.com/comment/85211445
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85211447
has title: Load multiple csv files, look for missing merchandiseID in subsequent files, calculate the date sold based on it
tagged with: python
has body: I am relatively new to Pandas and Python, so pardon me if this is a basic question. I looked around, but could not find a solution. I have multiple csv files, one for each month, which among other things have: inventory_01312017.csv store_id stock_number merchandise_id date_acquired color price MSRP photo url 12973 7382 UISN78008 04/11/2017 Red $3200 $3650 ... 45973 9889 YHAN79807 08/09/2017 White $3600 $3650 ... inventory_02282017.csv store_id stock_number merchandise_id date_acquired color price MSRP photo url 45973 9889 YHAN79807 08/09/2017 White $3600 $3650 ... I need to load these files, which I was able to do without any issues using import pandas as pd ... prep_data1 = pd.read_csv("../data/inventory_0131170401.csv") prep_data2 = pd.read_csv("../data/inventory_0201170456.csv") prep_data = pd.concat([prep_data1, prep_data2], ignore_index=True) ... prep_data['age_months'] = age_count(prep_data['date_acquired']) #Adding a new column to get integer value for age Now, I have to scan these files and figure out when a particular item with a merchandise_id was sold and create a new column in the data frame and put it in the last csv it appears. If a item was sold, then it will not be in stock for that month and will not show up in that month's inventory csv file. For example, if the item was sold in Jan2018, it will not show up in the inventory file for Feb2018. I have to add this data to Jan2018's data frame or csv. Added an example above, in which case I should add a column in the first csv file, something like this: inventory_01312017.csv store_id stock_number merchandise_id date_acquired color price MSRP date_sold 12973 7382 UISN78008 04/11/2017 Red $3200 $3650 01/31/2017 45973 9889 YHAN79807 08/09/2017 White $3600 $3650 I need this data to be able to find out how long the item is in stock before it is sold (diff between data_acquired and date_sold) and how it affects its pricing. I thought about doing this manually, but it will take me weeks to finish this for so…
answer count: 0
score: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85211321

http://stackoverflow.com/a/49033452
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49033360
has body: Check out random.shuffle https://docs.python.org/2/library/random.html It will randomly reorder a list, you won't get duplicates since it's a reordering. prefill = [[4,0,0,1,0,2,6,3,0], [5,0,0,6,4,3,8,0,0], [7,6,0,5,0,8,4,1,2], [6,0,0,0,0,9,3,4,8], [2,4,0,8,3,0,9,5,0], [8,0,9,4,1,5,0,7,0], [0,7,2,0,0,4,0,6,0], [0,5,4,2,0,0,0,8,9], [0,8,6,3,0,7,1,2,4]] for row in prefill: random.shuffle(row) Note that it'll shuffle them in place though so a function to create a new matrix each time would look like: def create_random_square_matrix(size): matrix = [] values = range(1, size + 1) for i in range(size): row = list(values) random.shuffle(row) matrix.append(row) return matrix nine_by_nine = create_random_square_matrix(9)
type: Answer

http://stackoverflow.com/q/49053370
has comment: http://stackoverflow.com/comment/85112117
tagged with: python
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/85111925
has comment: http://stackoverflow.com/comment/85111810
has comment: http://stackoverflow.com/comment/85111620
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/85111415
has comment: http://stackoverflow.com/comment/85121740
score: 0
has comment: http://stackoverflow.com/comment/85111996
has comment: http://stackoverflow.com/comment/85111757
has comment: http://stackoverflow.com/comment/85111548
has body: I am running TableWidget example in pyqtgraph 0.10.0 on a Windows 7 (64 bit) machine on python 3.6.4. from pyqtgraph import examples examples.run() Then choose TableWidget example under Widgets and click Run Examples. When I try to save the TableWidget data in a local tsv by right clicking on the table and selecting 'Save All' and then 'Save' after entering a filename in the file selection popup, I get the following error: File "..\TableWidget.py", line 350, in save open(fileName, 'w').write(data) TypeError: expected str, bytes or os.PathLike object, not tuple I can not seem to find anything in the issues on their repository on GitHub. Does anyone else has similar issues?
tagged with: python-3.x
answer count: 0
has title: pyqtgraph examples TableWidget throws a TypeError when trying to save data in a tab seperated file
type: UnansweredQuestion

http://stackoverflow.com/q/48964682
score: 1
upvote count: 1
type: Question
has title: Premake cannot find lua script in my repo (exact same repo works on my mainpc)
has comment: http://stackoverflow.com/comment/84994868
tagged with: visual-studio-2017
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48973770
has body: I have a github repo which has an implementation of premake that works on my main PC, but not on my laptop. When I run my python script to generate the project files I get the error: "No Premake script (premake5.lua) found!" So I decided to follow premakes tutorial for writing your first script on my laptop and created a directory that contains four files: premake5.exe, premake5.lua, hello.c and generate_project_files.py. But it still doesn't work, I recieve the same error. You can see the files below. I also added a for loop which prints all the files in the directory. When the script runs, after saying that premake5.lua is not found, it lists all the files(including premake5.lua). python script: import os import subprocess premake_dir = os.path.dirname(os.path.realpath(__file__)) + "\\" args = [ premake_dir + "premake5.exe", "vs2017", "--file=" + premake_dir + "premake5.lua" ] subprocess.run(args) for file in os.listdir(premake_dir): print(file) lua script: -- premake5.lua workspace "HelloWorld" configurations { "Debug", "Release" } project "HelloWorld" kind "ConsoleApp" language "C" targetdir "bin/%{cfg.buildcfg}" files { "**.h", "**.c" } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" I have no idea how to solve this problem as I have never encountered it before, and after searching for a fix i've found nothing even remotely close. Please share if you've ever encountered anything similar or know a fix.
type: UnansweredQuestion
tagged with: premake
tagged with: python
tagged with: lua

http://stackoverflow.com/comment/138709610
type: Comment
comment on: http://stackoverflow.com/a/78571670
score: 0
type: AnswerComment
has text: Excellent work! Thanks!

http://stackoverflow.com/a/49116386
answers question: http://stackoverflow.com/q/49115972
upvote count: 1
has body: It sounds like what you might really want is co-operative multiple inheritance. E.g. You want to have class MyFileInput(DBAdminClearableFileInput, ResubmitBaseWidget): pass For that to work, both DBAdminClearableFileInput and ResubmitBaseWidget would need to be written with co-operative multiple inheritance in mind. It may not even be (theoretically) possible depending on how the end-state behaviour has to look. E.g. if DBAdminClearableFileInput wants to render the widget as &lt;foo&gt; and ResubmitBaseWidget wants to render the widget as &lt;bar&gt;, one of them has to 'win' (in the absence of additional code you might write yourself in MyFileInput. It's possible (though probably unlikely) that multiple inheritance will 'just work', depending on what methods etc both those classes override and whether they make they already make the correct calls to super(). It's probably worth a try at least, in the worst case scenario you can add some 'glue' to your MyFileInput class to make it work. Here's a trite example class Elephant: # Represents ClearableFileInput def colour(self): return "Grey" class BrownElephant(Elephant): # Represents ResubmitBaseWidget def colour(self): return "Brown" class PinkElephant(Elephant): # Represents DBAdminClearableFileInput def colour(self): return "Pink" Now, at the moment, these classes do not cooperate, and so if you do multiple inheritance, you get: class BrownAndPinkElephant(BrownElephant, PinkElephant): pass nelly = BrownAndPinkElephant() print(nelly.colour()) Will print "Brown", since the Method Resolution Order starts with BrownElephant, which returns "Brown" without ever calling super().colour(), and so Pink and 'default' Elephant's methods are never even called. You could 'fix' this in a very limited (but might be enough for your purposes) with a hacky 'glue' method like this: class BrownAndPinkElephant(BrownElephant, PinkElephant): def colour(self): colours = [ BrownElephant.colour(self), PinkElephant.colour(self), ] return " and…
has comment: http://stackoverflow.com/comment/85271911
type: Answer
has comment: http://stackoverflow.com/comment/85272195
downvote count: 0
score: 1

http://stackoverflow.com/q/48970898
tagged with: pymongo
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/48971972
score: 0
answer count: 1
has body: I want to run multiple spiders, so i try to use CrawlerProcess. But i find the method open_spider will run two times at the beginning and the end with process_item method. It causes when the spider open , i remove my collection and save the data into mongodb completed. It will remove my collection again finally. How do i fix the issue and why the method open_spider run two times ? I tyep scrapy crawl movies run the project: Here is my movies.py: # -*- coding: utf-8 -*- import scrapy from scrapy import Request import time # scrapy api imports from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from Tainan.FirstSpider import FirstSpider class MoviesSpider(scrapy.Spider): name = 'movies' allowed_domains = ['tw.movies.yahoo.com', 'movies.yahoo.com.tw'] start_urls = ['http://tw.movies.yahoo.com/movie_thisweek.html/'] process = CrawlerProcess(get_project_settings()) process.crawl(FirstSpider) process.start() It's my FirstSpider.py: # -*- coding: utf-8 -*- import scrapy from scrapy import Request class FirstSpider(scrapy.Spider): name = 'first' allowed_domains = ['tw.movies.yahoo.com', 'movies.yahoo.com.tw'] start_urls = ['http://tw.movies.yahoo.com/movie_thisweek.html/'] def parse(self, response): movieHrefs = response.xpath('//*[@class="release_movie_name"]/a/@href').extract() for movieHref in movieHrefs: yield Request(movieHref, callback=self.parse_page) def parse_page(self, response): print 'FirstSpider =&gt; parse_page' movieImage = response.xpath('//*[@class="foto"]/img/@src').extract() cnName = response.xpath('//*[@class="movie_intro_info_r"]/h1/text()').extract() enName = response.xpath('//*[@class="movie_intro_info_r"]/h3/text()').extract() movieDate = response.xpath('//*[@class="movie_intro_info_r"]/span/text()')[0].extract() movieTime = response.xpath('//*[@class="movie_intro_info_r"]/span/text()')[1].extract() imdbScore = response.xpath('//*[@class="movie_intro_info_r"]/span/text()')[3].extract() movieContent = respon…
has title: open_spider method run two times when using CrawlerProcess
has answer: http://stackoverflow.com/a/48971972
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85024907
score: 0
type: AnswerComment
has text: I have corrected a missing part in my code as the output should be a matrix not a stack of lists. I added .reshape((num_px*num_px*3,1))
comment on: http://stackoverflow.com/a/49008226
type: Comment

http://stackoverflow.com/comment/85102757
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49045318
has text: @PedroAlves - need parameter `include_lowest=True`

http://stackoverflow.com/a/49051166
has comment: http://stackoverflow.com/comment/126689683
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49050974
upvote count: 5
has comment: http://stackoverflow.com/comment/85107918
accepted answer of: http://stackoverflow.com/q/49050974
type: Answer
has comment: http://stackoverflow.com/comment/85108025
has body: Try this: Data['Married'].fillna(Data['Married'].mode(), inplace=True) Or Try this: Data['Married'].fillna(Data['Married'].value_counts().index[0], inplace=True) Ensure that dtype of your categorical variables is object or category.
score: 5
has comment: http://stackoverflow.com/comment/85108646
has comment: http://stackoverflow.com/comment/85107829

alexa-skills-kit
tag name: alexa-skills-kit
type: Tag
tags question: http://stackoverflow.com/q/49116900

http://stackoverflow.com/a/49025756
upvote count: 3
answers question: http://stackoverflow.com/q/49025657
downvote count: 0
has body: If order of new columns is important use join: df = df.join(pd.DataFrame(0, columns=new_cols, index=df.index))
has comment: http://stackoverflow.com/comment/85056083
score: 3
type: Answer

http://stackoverflow.com/a/55286490
has body: Although the question is for Python3, I got here while trying to install gdbm on Python2 so I post my answer as it may be useful for others. The correct command was conda install python-gdbm. Although conda install gdbm went through, the module couldn't be imported. As per here, however, this may not work for Python3.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49113718

http://stackoverflow.com/comment/85075819
has text: I recommend Biopyton for this stuff btw https://github.com/biopython/biopython
comment on: http://stackoverflow.com/q/49035425
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49111804
tagged with: opencv
has title: How to detect rectangle in noisy image - OpenCV using HoughTransform or other method?
tagged with: image-processing
type: Question
has body: I have images(sometime scanned) like this and and . I want to identify first two large rectangle at first and then last three smaller rectangle at second. I googled and found that i have to locate corner of the rectangle and use that info to indentify rectangle. But I am not sure how to approach this problem and handle noisy image like these. I came across this tutorial to detect line and somehow I managed to run this. I am just starting in Computer Vision. I would appreciate any help/pointer to sample code/documentation. Update: I managed to run this on my image. Now I am getting this . Any idea how to get the check if there is at least two larger or three smaller adjacent rectangles? Code: import cv2 import numpy as np img = cv2.imread("4.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # canny edge detection edges = cv2.Canny(img, 0, 200, apertureSize=2) minLineLength = 100 maxLineGap = 10 lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength, maxLineGap) for i in range(len(lines)): for x1, y1, x2, y2 in lines[i]: cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), thickness=2) cv2.imwrite('22.jpeg', img) Thanks in advance.
has comment: http://stackoverflow.com/comment/85229685
score: 0
has comment: http://stackoverflow.com/comment/85230739
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85230274
type: UnansweredQuestion

http://stackoverflow.com/comment/85154172
score: 1
has text: [I think the answer is yes](https://stackoverflow.com/q/26777832/8881141)
comment on: http://stackoverflow.com/q/49074021
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85161936
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49071624
score: 0
has text: Great thx! now it works. Last question: Now i created a user with read/write privileges on all db with `mongo.admin.command("createUser", "man", pwd="man", roles=["readWriteAnyDatabase"])` . I can connect using that user with `MongoClient('mongodb://%s:%s@127.0.0.1' % ('man', 'man'))` . All this works. Now I want to create a test for that new connection. I assign the MongoClient to the variable name `mongo`. Is there any attribute of `mongo` showing the username and the role?I know i can see that from the `mongo.adminsystem.users` but can i see it on the mongoclient instance?

http://stackoverflow.com/comment/85165248
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49079552
score: 3
has text: This is the difference between [capturing a repeated group and repeating a capturing group](https://www.regular-expressions.info/captureall.html). (That's a better explanation than I could write up.) You can match "d4e5f6" by making the group non-capturing: `(?:\D\d)+`.

http://stackoverflow.com/a/49019854
accepted answer of: http://stackoverflow.com/q/49019834
has body: Your c as you have it now is a print statement, which is indeed a NoneType. Try replacing c = print(interest_over_time_df.iloc[-1]['adele']) print(c) with c = int(interest_over_time_df.iloc[-1]['adele']) print(c) This prints c, which is explicitly cast as an int. Depending on how interest over time is calculated, you might actually want a float (not an int), so that you can compare for instance 1.0 to 1.1 if such values are possible. if that is the case, you can just replace int in my suggestion with float
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49019834
type: Answer

http://stackoverflow.com/q/49005853
has answer: http://stackoverflow.com/a/49005899
score: 0
has body: I have created a script in python using BeautifulSoup to parse some information from some html snippet. It is working fine when I use list comprehension. My goal here is to do the same using lambda expression. I've heard that the two list comprehension and lambda expression can work identically. However, I can't find any idea as to how I could apply lambda function to achieve the same result that I've got using list comprehension. Any help on this will be highly appreciated. Here is what my code so far: from bs4 import BeautifulSoup content=""" 0.00 % , 2.52 , 1.79 , 1.79 % , 0.72 , 1.08 % """ soup = BeautifulSoup(content,"lxml") data = [item.text for item in soup.find_all("td")] #it is doing fine # data = "wish to do the same like above using lambda" print(data)
answer count: 1
has comment: http://stackoverflow.com/comment/85016345
has comment: http://stackoverflow.com/comment/85016276
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/49005899
tagged with: python-3.x
has title: Trouble creating lambda expression to achieve certain results
tagged with: python
tagged with: lambda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85016413
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1247486

http://stackoverflow.com/q/48967941
tagged with: python
has comment: http://stackoverflow.com/comment/84941647
has answer: http://stackoverflow.com/a/48967986
tagged with: ip
type: Question
tagged with: network-programming
answer count: 1
has comment: http://stackoverflow.com/comment/84941461
score: 0
tagged with: udp
has comment: http://stackoverflow.com/comment/84941596
has body: Been trying to solve this simple script, without luck. The error I got is the following: python renato_script.py Enter HOSTNAME ip: 10.0.0.2 Enter TCP/UDP port: 443 Traceback (most recent call last): File "renato_script.py", line 8, in if s.connect_ex((ip, port)): TypeError: an integer is required (got type str) import socket ip = input( "Enter HOSTNAME ip: ") port = input ("Enter TCP/UDP port: ") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if s.connect_ex((ip, port)): print ("Port", port, "is closed") else: print ("Port", port, "is open")
type: UnansweredQuestion
tagged with: sockets
has title: Python socket - issues taking ip, takes it as a string

discord
tags question: http://stackoverflow.com/q/49091077
tags question: http://stackoverflow.com/q/49099168
tags question: http://stackoverflow.com/q/49098057
tags question: http://stackoverflow.com/q/49009148
type: Tag
tags question: http://stackoverflow.com/q/49030031
tags question: http://stackoverflow.com/q/49061324
tag name: discord
tags question: http://stackoverflow.com/q/49000679
tags question: http://stackoverflow.com/q/49082031
tags question: http://stackoverflow.com/q/48988516
tags question: http://stackoverflow.com/q/49015736
tags question: http://stackoverflow.com/q/49103844
tags question: http://stackoverflow.com/q/48987006

http://stackoverflow.com/comment/84984659
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48981864
has text: But in as_view we are sending model name through kwargs and it should be work

http://stackoverflow.com/a/49070934
upvote count: 13
score: 13
accepted answer of: http://stackoverflow.com/q/49049318
has comment: http://stackoverflow.com/comment/85191066
answers question: http://stackoverflow.com/q/49049318
type: AcceptedAnswer
downvote count: 0
has body: I managed to come up with a satisfactory solution to this. There are a few steps: Get contours Remove contours that are too small or too large in area Find the min/max x/y over all remaining contours Use those values to create a rectangle to crop in That's the basic process. Anyway, here's some code for the core parts: import cv2 from os.path import basename from glob import glob def get_contours(img): # First make the image 1-bit and get contours imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 150, 255, 0) cv2.imwrite('thresh.jpg', thresh) img2, contours, hierarchy = cv2.findContours(thresh, 1, 2) # filter contours that are too large or small size = get_size(img) contours = [cc for cc in contours if contourOK(cc, size)] return contours def get_size(img): ih, iw = img.shape[:2] return iw * ih def contourOK(cc, size=1000000): x, y, w, h = cv2.boundingRect(cc) if w &lt; 50 or h &lt; 50: return False # too narrow or wide is bad area = cv2.contourArea(cc) return area &lt; (size * 0.5) and area &gt; 200 def find_boundaries(img, contours): # margin is the minimum distance from the edges of the image, as a fraction ih, iw = img.shape[:2] minx = iw miny = ih maxx = 0 maxy = 0 for cc in contours: x, y, w, h = cv2.boundingRect(cc) if x &lt; minx: minx = x if y &lt; miny: miny = y if x + w &gt; maxx: maxx = x + w if y + h &gt; maxy: maxy = y + h return (minx, miny, maxx, maxy) def crop(img, boundaries): minx, miny, maxx, maxy = boundaries return img[miny:maxy, minx:maxx] def process_image(fname): img = cv2.imread(fname) contours = get_contours(img) #cv2.drawContours(img, contours, -1, (0,255,0)) # draws contours, good for debugging bounds = find_boundaries(img, contours) cropped = crop(img, bounds) if get_size(cropped) &lt; 400: return # too small cv2.imwrite('cropped/' + basename(fname), cropped) process_image('pic.jpg') This has the important parts, but I used two other tricks that worked well for my data set: Modify the threshold until a c…
has comment: http://stackoverflow.com/comment/137251118
type: Answer

http://stackoverflow.com/comment/85115111
score: 1
has text: Why is that your desired output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49055298

http://stackoverflow.com/comment/85096376
score: 0
type: Comment
type: QuestionComment
has text: my bad, I edited my post to include more info.
comment on: http://stackoverflow.com/q/49042698

http://stackoverflow.com/a/49103642
has comment: http://stackoverflow.com/comment/85799473
score: 0
answers question: http://stackoverflow.com/q/49103531
type: Answer
has body: From an implementation perspective, the short answer would be yes. However, I believe your question could be more specific, maybe what you mean is whether you could do it with tf.estimator?

http://stackoverflow.com/q/49072805
downvote count: 0
answer count: 1
has body: I'm trying to pad out a dataframe that I'm using to graph some sales data to fill the remaining weeks of the year with zeros. My code is as follows: weeks = [x for x in range(max(sales['WEEK']+1),53)] padding = pd.DataFrame(np.zeros((53max(sales['WEEK']+1),len(sales.columns))),index=weeks) Which returns me a pandas DataFrame 43 rows x 3 columns. What I really need to do is repeat the index of each of my 43 rows 7 times, giving me a DataFrame with 301 rows . I can't work this out, any ideas?
favorite count: 0
has answer: http://stackoverflow.com/a/49072862
has title: Creation of pandas dataframe, repeating entries with loop
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49072862
tagged with: pandas

http://stackoverflow.com/comment/84954407
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48974703
has text: If what you divide by is not standard python 0. but numpy 0. it only throws "RuntimeWarning: divide by zero encountered in true_divide" but not error.

http://stackoverflow.com/a/49075186
has body: This should work: testDataset[testDataset['Region'].str.contains('nebraska', regex=False, na=False) &amp; \ pd.notnull(testDataset['metric1'])] np.nan == np.nan is False (see explanation) which is why your method does not work. I've also added regex=False, which should improve performance, and na=False so that you do not get errors for unexpected types.
answers question: http://stackoverflow.com/q/49075138
score: 0
type: Answer

http://stackoverflow.com/comment/85247598
type: QuestionComment
has text: Can you post your test case?
comment on: http://stackoverflow.com/q/49120686
score: 0
type: Comment

http://stackoverflow.com/comment/85133729
comment on: http://stackoverflow.com/a/49063795
type: Comment
score: 1
has text: `$('#display_slots option').slice(1).remove();` from [this](https://stackoverflow.com/questions/17722433/remove-all-child-elements-from-table-except-for-first).
type: AnswerComment

http://stackoverflow.com/comment/85071050
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49022289
has text: Keyur, you're the best. Thanks so much. Worked for me and the explanation was very helpful
type: AnswerComment

http://stackoverflow.com/a/49029869
type: AcceptedAnswer
downvote count: 0
has body: I've found how to avoid that. In Spyder : Tools > Preferences > IPython console > Graphics > Unbox "Activate support" Reload Spyder.
type: Answer
answers question: http://stackoverflow.com/q/49027768
accepted answer of: http://stackoverflow.com/q/49027768
upvote count: 1
score: 1

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/48992794
type: Tag

http://stackoverflow.com/comment/84987162
type: Comment
type: QuestionComment
has text: So what would be the bias-less way to measure this?
comment on: http://stackoverflow.com/q/48990886
score: 0

http://stackoverflow.com/a/49114903
type: Answer
score: 0
has body: If I recall, they should not interfere with what you are trying to do as they will place a mutex on the resource and perform any operation independently, and as long as you catch an exception from the resource if it is empty when attempting to pop you should be good to go.
answers question: http://stackoverflow.com/q/49114725

http://stackoverflow.com/q/48964620
has comment: http://stackoverflow.com/comment/84935215
tagged with: stderr
has comment: http://stackoverflow.com/comment/84941632
has title: How to redirect stderr and stdout to a file and a screen in the same time for Python script?
answer count: 0
type: UnansweredQuestion
tagged with: http-redirect
tagged with: python
has comment: http://stackoverflow.com/comment/84935172
has body: I send files to my ftp server with this code. I would like to have error log on screen and the same traceback and error in my log file. For now, in my log file is only error name. How to put stdout and stderr in the file and on the screen in the same time? #!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime import ftplib import sys # FTP server login data ftpserver_ip = '192.168.0.100' username = 'uname' password = 'upass' # If there is command line argument, the first one is our file to upload if len(sys.argv) &gt; 1: upload_file = sys.argv[1] else: print('No input file') sys.exit() def ftpsend(): try: # ftp server running on 'ftpserver_ip' on port 21 session = ftplib.FTP(ftpserver_ip, username, password) file = open(upload_file, 'rb') session.storbinary('STOR '+upload_file, file) file.close() session.quit() except Exception as err: with open('error.log', 'w') as ferr: print(err) ferr.write(str(datetime.datetime.now())) ferr.write('\n') ferr.write(str(err)) return None with open('OK.log', 'w') as fok: fok.write(str(datetime.datetime.now())) fok.write(" OK") print(datetime.datetime.now(), "OK") ftpsend() If everything went well, file OK.log should be created. If an error occur, file `error.log' should be created with this content eg.: [Errno 2] No such file or directory: 'simple_table.pd' Traceback (most recent call last): File "ftp-send.py", line 35, in ftpsend file = open(upload_file, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'simple_table.pd'
has comment: http://stackoverflow.com/comment/84936930
tagged with: stdout
type: Question
has comment: http://stackoverflow.com/comment/84935371
has comment: http://stackoverflow.com/comment/84935224
score: 0

http://stackoverflow.com/q/48968019
accepted answer: http://stackoverflow.com/a/48971973
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: I have a Flask application where I let users access third party applications and fetch data from them and perform some visualizations.Now the user has to provide the application name and it's credentials in order to fetch the data.Now I want to avoid putting the application name in the url and rather all of the data should be sent as a POST request where I will parse the POST data, connect to the required app with the given credentials and perform some visualizations.This is what the user will send as a POST data { "application_name": "appdynamics", "account_id": "sdf632sef", "username": "kuhku86tg", "password": "oihsd832" } Now I want to trigger my particular REST API class based on the application name provided by the user. The way I planned was to create a seperate file that involves getting the POST data using request parser and then calling it in the main application where I will trigger my REST API class with a if condition based on the application name.Below is the file parse.py from flask_restful import reqparse # create a parser object parser = reqparse.RequestParser() # add agruments to the parser object parser.add_argument('account_id', type=str, required=False, help="Please define 'account_id'") parser.add_argument('username', type=str, required=False, help="Please define 'username'") parser.add_argument('password', type=str, required=False, help="Please define 'password'") parser.add_argument('application_name', type=str, required=False, help="Please define 'application name'") data = parser.parse_args() Now I call it in the main application app.py from parser import data from flask import Flask from flask_restful import Api app = Flask(__name__) # create an API for the Flask app api = Api(app) # if the user demands info for appdynamics, trigger the Appdynamics API class if data['application_name'] == "appdynamics": api.add_resource(AppdynamicsAPI, "/&lt;string:name&gt;") # the string will contain the metric requirement if __name__ == "__main__": app.ru…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48971973
downvote count: 1
type: Question
has title: How to trigger a REST API based on a condition in Flask?
score: -1
tagged with: flask-restful
tagged with: flask

http://stackoverflow.com/a/49127039
score: 7
accepted answer of: http://stackoverflow.com/q/49080027
has body: Credentials for MySQL include not only a username and a password, but also a set of allowed IP addresses. So, even if we have the correct username and password, but the connection is established from a not allowed IP, we will get the 1045 "Access denied" error from sqlmap. To illustrate the problem, I setup a test database testdb with user admin. Here are the user's credentials: MariaDB [testdb]&gt; select host,user,password from mysql.user where user='admin'; +-------------+-------+-------------------------------------------+ | host | user | password | +-------------+-------+-------------------------------------------+ | 92.168.0.20 | admin | *00A51F3F48415C7D4E8900010101010101010101 | +-------------+-------+-------------------------------------------+ As it is shown in the host column, the user admin is allowed to access the server only from the IP 92.168.0.20. Now, if I run sqlmap from this IP it succeeds: $ sudo sqlmap -d 'mysql://admin:12345@92.168.0.99:3306/testdb' ... [*] starting at 09:28:43 [09:28:43] [INFO] connection to mysql server 92.168.0.99:3306 established [09:28:43] [INFO] testing MySQL [09:28:43] [INFO] resumed: u'1'... [09:28:43] [INFO] confirming MySQL [09:28:43] [INFO] resumed: u'1'... [09:28:43] [INFO] the back-end DBMS is MySQL back-end DBMS: MySQL &gt;= 5.0.0 [09:28:43] [INFO] connection to mysql server 92.168.0.99:3306 closed [*] shutting down at 09:28:43 If I run sqlmap from a different IP it fails with the 1045 "Access denied" error (exactly as in your output): $ sudo sqlmap -d 'mysql://admin:12345@92.168.0.99:3306/testdb' ... [*] starting at 09:32:00 [09:32:00] [CRITICAL] SQLAlchemy connection issue ('(_mysql_exceptions.OperationalError) (1045, "Access denied for user 'admin'@'92.168.0.55' (using password: YES)")') [*] shutting down at 09:32:00 So, if you are sure that you have the correct username and password, the problem is highly likely in the allowed IPs. When creating a MySQL user, it is common practice to allow access only …
answers question: http://stackoverflow.com/q/49080027
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85282562
type: Answer
has comment: http://stackoverflow.com/comment/85268130
upvote count: 7
has comment: http://stackoverflow.com/comment/85285043
has comment: http://stackoverflow.com/comment/85273520

http://stackoverflow.com/comment/85247716
type: QuestionComment
has text: `for y in range(0, self.size)` makes `y` an integer, which you try to treat like a list with `y[x]`. Not sure, what you intended to do in this step. Maybe `heightarray[y][x]`?
comment on: http://stackoverflow.com/q/49120985
score: 1
type: Comment

http://stackoverflow.com/a/48979155
has body: Trying to generate elements one by one is a bad idea, and saving them all is even worse. You only need one element's value, and you can compute it directly. Suppose the element you want is at index 2**i + k, where k &lt; 2**i. Then this element is the negation of the element at index k, and the element at index k can be computed the same way. You end up negating element 0 once for each set bit in your desired index's binary representation. If there are an even number of set bits, the value is True. Otherwise, the value is False.
type: Answer
has comment: http://stackoverflow.com/comment/84966226
upvote count: 2
answers question: http://stackoverflow.com/q/48978530
score: 2
downvote count: 0

http://stackoverflow.com/comment/84959196
score: 0
type: Comment
has text: Feel glad that it helped. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/48976454

http://stackoverflow.com/q/49063655
score: -1
has answer: http://stackoverflow.com/a/49063786
downvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: Reading json file with multiple objects python
has body: Hey I am newbie working with JSON files I have a sample JSON file like this (twitter data scrape) here each[] contains multiple JSON objects, I want to extract the text from these objects, the problem is json.load is not working on multiple JSON array structure ([][][]) in the sample example below first [] contains three JSON objects and second one has 2 JSON objects [{ "created_at": "2014-12-07 02:17:18", "favorite_count": 5, "id_str": "541416129567019008", "in_reply_to_screen_name": "panellington", "retweet_count": 15, "retweeted": false, "text": "minutes ago. #berkeley #BlackLivesMatter #EricGarner #LAPD" }, { "created_at": "2014-12-04 19:21:13", "favorite_count": 13, "id_str": "540586640595369984", "in_reply_to_screen_name": null, "retweet_count": 38, "retweeted": false, "text": "#BlackLivesMatter" }, { "created_at": "2014-12-13 00:50:27", "favorite_count": 1, "id_str": "543568596299808768", "in_reply_to_screen_name": null, "retweet_count": 0, "retweeted": false, "text": "MLK Riot is language of unheard #Ferguson #ICantBreathe #BlackLivesMatter" }] [{ "created_at": "2015-04-28 13:21:35", "favorite_count": 0, "id_str": "593042377658519552", "in_reply_to_screen_name": null, "retweet_count": 5, "retweeted": false, "text": "RT @fsmith827: A lot of folks speaking against civil unrest have been willfully blind, willfully silent @ #BlackLivesMatter &amp;amp; #PoliceBrutal\u2026", }, { "created_at": "2014-12-07 03:17:27", "favorite_count": 0, "id_str": "541431264897937408", "in_reply_to_screen_name": null, "retweet_count": 456, "retweeted": false, "text": "RT @thecrisismag: #ICantBreathe Protesters in Paris march in solidarity with #EricGarner and #MikeBrown #BlackLivesMatter #GrandJury" }] I want to read it as JSON object and want to work on this (ex: data[0]['text']) Problem is my file contains multiple JSON array objects [some random number of JSON objects],[some random number of JSON objects] and so on.. with open('tweets.json') as json_data: d = json.load(json_data…

http://stackoverflow.com/q/49040998
score: 0
has comment: http://stackoverflow.com/comment/85125112
tagged with: apache
has comment: http://stackoverflow.com/comment/85087333
has comment: http://stackoverflow.com/comment/85113718
tagged with: gcc
type: UnansweredQuestion
tagged with: python
has body: I can't import tensorflow in my python CGI program on my server. I have a VPS with CentOS6.9 operation system. I already installed gcc-4.9.0 and python3.6 so I can run python script which import tensorflow and keras. Now I want to write a python CGI program which also import tensorflow and keras. But as soon as I add "import tensorflow as tf" my script returns a server 500 error. After removing this line of code my script runs fine. The same situation goes for keras module as well. I googled some. It seems to be related to apache enviroment values maybe it still use gcc-4.4.7 although I already linked usr/bin/gcc to my latest gcc-4.9.0. But there are not exlaborate answer to this. The error log on apache shows: Traceback (most recent call last): File "/usr/local/python3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/local/python3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/usr/local/python3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/usr/local/python3/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/usr/local/python3/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.7' not found (required by /usr/local/python3/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test.py", line 8, in &lt;module&gt; import tensorflow as tf File "/usr/local/python3/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; fro…
answer count: 0
tagged with: cgi
has title: How to import tensorflow in python CGI program on CentOS server
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/61381723
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49109359
has body: Something has changed since 1.0. sudo pip install html5lib==0.90

http://stackoverflow.com/q/49053839
type: UnansweredQuestion
has body: I have a package structure as follows: package __init__.py subpackageA api.py __init__.py subpackageB action.py start.py __init__.py The main package only serves to expose one class in subpackageB start.py called Schedule. All other classes are used internally and cant be exposed. Therefore my package/__init__.py is as follows: from package.subpackageB.start import Schedule However, when I try to import package, i get the following error: ImportError: No module named 'package.subpackageB' What am I doing wrong here? Update So after a bit of toiling I realised that my approach was probably wrong for what I was trying to achieve. I changed it so that api.py, action.py and start.py are no longer in sub packages, but within the main package only. I then reworked action.py so that its contents where part of start.py. What this enabled me to do was to use the __all__ parameter to only import the Schedule module I wanted from start.py As I use api.py it will also be imported by start.py, but this isn't a big issue for now so the new approach works for me. package __init__.py api.py start.py (action.py contents now part of start.py)
type: Question
has answer: http://stackoverflow.com/a/49054534
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/85113089
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/85114335
has title: Cannot import subpackage using __init__.py
has comment: http://stackoverflow.com/comment/85113141
has comment: http://stackoverflow.com/comment/85135371
has comment: http://stackoverflow.com/comment/85114391
has comment: http://stackoverflow.com/comment/85112857
has comment: http://stackoverflow.com/comment/85114457

http://stackoverflow.com/a/49109613
has body: Yes, you can do that. For that purpose I recommend to create an custom decorator like so: decorators.py: from django.core.exceptions import PermissionDenied from .models import YourBlogPostModel def user_is_blog_post_user(function): def wrap(request, *args, **kwargs): post = YourBlogPostModel.objects.get(pk=kwargs['blog_post_id']) if post.user == request.user: return function(request, *args, **kwargs) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap You can then use it in conjunction with other decorators. views.py: @login_required @user_is_blog_post_user def function_based_view(request, blog_post_id): # ... Take a look here for a more detailed explanation. If you are using CVB you can either create an own Mixin or decorate the class. class UserIsBlogPostAdmin(object): """Verify that the current user is the user of the blog post.""" def dispatch(self, request, *args, **kwargs): blog_post = get_object_or_404(YourBlogPostModel, pk=args[0]) if blog_post.user != request.user raise Http404 return super().dispatch(request, *args, **kwargs)
answers question: http://stackoverflow.com/q/49109363
score: 1
accepted answer of: http://stackoverflow.com/q/49109363
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85226389
upvote count: 1

http://stackoverflow.com/a/49079722
has body: Your solution isn't really "dangerous," but there is a generally better way to access the nth binary digit of a number (which should work in most languages as a bonus): bitwise operations. Solution (in Python) You can access the binary digit with index n (with the right-most digit having index 0) of any number num using the following code: digit = (num &amp; (1 &lt;&lt; n)) &gt;&gt; n If you want this data as a string, you can add digit = str(digit) afterwards. Explanation Filtering Numbers Using &amp; ("bitwise and") The &amp; operation takes two binary numbers and gives back a third binary number with 1s only in those positions where both of the original numbers had 1s. You can use this property to "fish out" (or "mask out") the value of any binary digit of any number. For example, if we wanted to figure out the value of the 4th binary digit of the number 51: 1 1 0 0 1 1 (51 in binary) & 0 1 0 0 0 0 (filter value - see below) ------------- 0 1 0 0 0 0 (result) The "filter" value above is a number that we build using our knowledge of which binary digit we want to check. Since we want the digit at index 4, we use a number consisting of all 0's, except for a 1 in the 4th position (again, counting from the right, and starting from 0). Since our filter value only has a 1 in the 4th position, we know that our result will have 0s in every position except the 4th position. The 4th position could be a 0 or a 1, depending on the other number. This is fine on paper, but how do we obtain the filter value based on the index? For this we use another bitwise operation: left shift. Constructing A Filter Using &lt;&lt; ("bitwise left shift") The left shift operation essentially pads a number with a certain number of 0's on the right side. For example, here's 1 &lt;&lt; 4: 1 (binary) &lt;&lt; 4 (decimal) --------- 1 0 0 0 0 (binary) This gives us a way to construct the filter value using only the digit's index: If we want a number with a 1 in position n, and 0s everywhere else, we …
downvote count: 0
answers question: http://stackoverflow.com/q/49079440
type: Answer
upvote count: 7
score: 7

http://stackoverflow.com/q/49076404
tagged with: python
has body: I can't convert a string passed throug command line to a function to float. I'll explain better. I have this function who takes two arguments, the second one is a float def function(): first_param = sys.argv[1] second_param = float(sys.argv[2]) Then I have this other function who calls the first one in a software container def callFunction(first_arg, second_arg): cmd = 'docker run --rm -v pathFunction:/home/fenics/shared -w /home/fenics/shared quay.io/fenicsproject/stable "python2 function.py ' + first_arg + str(second_arg) process = subprocess.Popen(cmd, shell=True) When I call: callFunction("some_string",0.02) it returns me an error in function at the line at whick I try the conversione to float saying: could not convert string to float : shell UPDATE I've found that the problem is that the first string I'm passing is a path with some spaces in it. Something like: some_string = C:\blabla\my directory\file.txt" with a space between 'my' and 'directory'. I can't change the path, do you know how could I fix it?
linked to: http://stackoverflow.com/q/12902227
tagged with: command-line
has title: From string to float with argv in python
tagged with: subprocess
score: 0
has comment: http://stackoverflow.com/comment/85158738
type: Question
has answer: http://stackoverflow.com/a/49076538
answer count: 2
has answer: http://stackoverflow.com/a/49076499
tagged with: args
has comment: http://stackoverflow.com/comment/85158890
type: UnansweredQuestion

http://stackoverflow.com/q/49080027
downvote count: 1
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/85338916
has comment: http://stackoverflow.com/comment/85249880
has comment: http://stackoverflow.com/comment/85248586
has comment: http://stackoverflow.com/comment/85256243
tagged with: sqlmap
accepted answer: http://stackoverflow.com/a/49127039
has comment: http://stackoverflow.com/comment/85235110
linked to: http://stackoverflow.com/q/8348506
answer count: 3
has body: I have the credentials of a TARGET website database and SQLMap Claims that you can connect to the database directly Here are my Commands on SQLMap in Kali Linux sudo sqlmap -d mysql://USER:PASSWORD@TARGET_IP:MySQL_Port/DATABASE example sudo sqlmap -d mysql://admin:12345@95.12.45.12:3306/information_schema but this is the error I get every time [CRITICAL] SQLAchemy connection issue ('(_mysql_exceptions.OperationalError) (1045, "Access denied for user 'admin'@'17.45.65.11' (using password: YES)")') The IP 17.45.65.11 was my IP ofc which denied So is there a Problem with my command? OR anyone knows a better way to connect directly to a target database with credentials?
score: 1
has answer: http://stackoverflow.com/a/49121548
favorite count: 0
has title: Connecting directly to database with credentials in SQLMap
possible better answer: http://stackoverflow.com/a/49113786
has answer: http://stackoverflow.com/a/49113786
has comment: http://stackoverflow.com/comment/85268010
tagged with: sql-injection
has comment: http://stackoverflow.com/comment/85235249
tagged with: python
has comment: http://stackoverflow.com/comment/85246727
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/85234683
has answer: http://stackoverflow.com/a/49127039
tagged with: mysql
has comment: http://stackoverflow.com/comment/85212452

http://stackoverflow.com/q/48967197
has comment: http://stackoverflow.com/comment/84941051
possible better answer: http://stackoverflow.com/a/48967314
has answer: http://stackoverflow.com/a/48967317
downvote count: 1
favorite count: 0
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84940329
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48967739
type: Question
has body: I am having trouble with logic checks. There is a coordinate system grid that is 15x15, row x column. There is a random list of 2-tuples that contains coordinates:[(3,3),(4,5),(14,14),(13,0),(0,13)]. (r, c) I would like to check if some random choice tuple is within a certain range: 2x2 and 12x12. So for example the tuple: (3,3) and (4,5) would be allowed, but (13,0) and (0, 13) would not. How would I go about implementing checks to see if a tuple pair lies within the range?
accepted answer: http://stackoverflow.com/a/48967317
has answer: http://stackoverflow.com/a/48967314
has comment: http://stackoverflow.com/comment/84940085
tagged with: if-statement
score: -1
has title: Keep a 2-tuple of ints within a specific range

http://stackoverflow.com/comment/84988527
type: AnswerComment
comment on: http://stackoverflow.com/a/48990126
score: 0
type: Comment
has text: অ-1 আ-1 ই-2 ঈ-4 I want to print like this for example.... Those characters are occurring those many times in that text file...

http://stackoverflow.com/a/49042217
type: Answer
answers question: http://stackoverflow.com/q/49029907
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49029907
type: AcceptedAnswer
downvote count: 0
has body: Ok. The issue is resolved. I had to use global variables to resolve it. Please find the modified code below for reference. main.py from sanic import Sanic from DAO import Motor_Connection from REST import User_REST import commons app = Sanic() @app.listener('before_server_start') def init(sanic, loop): commons.db = Motor_Connection() app.add_route(User_REST.as_view(), '/') if __name__ == "__main__": app.run(host="0.0.0.0", port=8000, workers=3, debug=True) commons.globals.py db = None user_DAO.py import commons class User_DAO(object): async def register_user(self, serialized_user): result = await commons.db.users.insert_one(serialized_user) return result.inserted_id Explanation: While the motor connection class was a singleton and returned the same instance, as it was initialized during the imports, Sanic could not get a handle on the event loop. Sanic has to be initialized first to be able to get a handle on the event loop. By using a global variable and initializing it in the before_server_start block, Sanic gets the handle. Now when you use the same variable in the DAO class, you have access to Sanic's event loop.

http://stackoverflow.com/comment/85066198
comment on: http://stackoverflow.com/q/49029995
score: 0
type: Comment
type: QuestionComment
has text: @MattTimmermans thanks, that solved a big part of the problem! Now only the SciPy solution is different (see edit in original question)

http://stackoverflow.com/comment/134805331
has text: Link is dead....
type: AnswerComment
comment on: http://stackoverflow.com/a/69447517
type: Comment
score: 1

http://stackoverflow.com/comment/85104194
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49019319
has text: Nothing is stored at that point (except the initialization). It's only a computational graph. Calling Eval creates the value.
score: 0

http://stackoverflow.com/q/49057589
answer count: 2
upvote count: 1
tagged with: data-processing
has answer: http://stackoverflow.com/a/49057696
accepted answer: http://stackoverflow.com/a/49057696
tagged with: replace
has title: Pandas - create new column with replaced values while keeping original column
has body: I'm a newbie to python so please bear with me. I have a data frame where I want to replace values for specific strings. Below is my starting df (df_train): A B C D 0 .5 Ex Ex Po 1 35 Gd TA Gd 2 52 TA Fa Ex 3 47 Bd Po Gd I can easily replace the values I'd like and create a new df(df_train_scaled), per below: df_train_scaled = df_train.replace(['Ex','Gd','TA','Fa','Po'], [5, 4, 3, 2, 1]) I'm curious if I should do this and go to a new df(df_train_scaled) to continue data pre-processing before modeling, or if I should create a new column in the same df (df_train). Regardless of the answer, I do want to figure out how to add a new column to the same df with the replaced values. Output below: A B B_new C C_new D D_new 0 .5 Ex 5 Ex 5 Po 1 1 35 Gd 4 TA 3 Gd 4 2 52 TA 3 Fa 2 Ex 5 3 47 Gd 4 Po 1 Gd 4 If I do this, I can experiment to see if my ordinal, or scaled, variables will perform better in my modeling efforts. Thanks in advance for any help!
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/49057964
has answer: http://stackoverflow.com/a/49057964

http://stackoverflow.com/q/48998826
tagged with: matplotlib
type: Question
has body: I'm new to geopandas dataframes and I got a GeoDataframe which coordinates make a plot very large. I intend to rotate the plot 90° or change the x-y coordinates from each of the polygons. I haven't achieved any of these options. I also want to put a legend of other GeoDataframe (this one with Points), but i'm afraid that with the rotation, the legend will also be rotated (if.. it's possible). Until now, the code looks like this: from shapely.geometry import Point import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt # Import data Zones = gpd.read_file('myfile_with_polygons.shp') Barr = pd.read_csv('myfile_with_LongLat_Coordinates.csv') # Create GeoDataFrame from Pandas Dataframe geometry = [Point(xy) for xy in zip(Barr.Longitud, Barr.Latitud)] Barr = gpd.GeoDataFrame(Barr, crs={'init': 'epsg:4326'}, geometry=geometry) # plots f, ax = plt.subplots(1) ax.set_title('such title') Zones.plot(ax=ax, facecolor='lightgray', edgecolor='gray') Barr.plot(ax=ax, facecolor='green', edgecolor='gray') plt.axis('scaled') plt.show() Edit: Format of myfile_with_LongLat_Coordinates.csv file: Name,Longitud,Latitud My Name,-72.5,-30.7 Such Wow,-69.47,-21.93 Very Name,-71.92,-18.53 ... Where the GeoDataFrame Zones has a format: Zone_name geometry 0 ZoneA (POLYGON ((-541621.6191 1675026.112, -541621.1... 1 ZoneB POLYGON ((636925.4216666555 6552020.6959, 3679... 2 ZoneC (POLYGON ((226598.6520999998 3110548.9596, 276... ....
tagged with: shapefile
upvote count: 3
has comment: http://stackoverflow.com/comment/85038997
tagged with: geopandas
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: Rotate or exchange x-y axis in geopandas dataframe plot
score: 3
downvote count: 0

http://stackoverflow.com/a/57258342
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/132898863
has comment: http://stackoverflow.com/comment/115277023
has comment: http://stackoverflow.com/comment/131983965
answers question: http://stackoverflow.com/q/49060525
has comment: http://stackoverflow.com/comment/111821580
upvote count: 4
has body: I had some issue with existing *.egg-info files, removing those allowed pip to work again
downvote count: 0

http://stackoverflow.com/q/49098873
type: UnansweredQuestion
has title: Caesar Cipher Python numbers and characters
has comment: http://stackoverflow.com/comment/85244414
tagged with: python
has body: I am new to Python and I'm trying to create a Caesar Cipher. So far, I've been using my own knowledge of Python and some online resources and I have managed to come up with the code below. I wanted the program to be able to take both number and text values and shift them by 13 and 5. Initially, when testing for text values the program seemed to work but after adding the code to include numbers it stopped working. Now, it does not output anything. I have included the code and I am using IDLE 3.6 key = 'abcdefghijklmnopqrstuvwxyz' def encrypt(n, plaintext): """Encrypt the string and return the ciphertext""" result = '' for l in plaintext.lower(): try: i = (key.index(l) + n) % 26 result += key[i] except ValueError: result += l return result.lower() def decrypt(n, ciphertext): """Decrypt the string and return the plaintext""" result = '' for l in ciphertext: try: i = (key.index(l) - n) % 26 result += key[i] except ValueError: result += l return result def show_result(plaintext, n): """Generate a resulting cipher with elements shown""" encrypted = encrypt(n, plaintext) decrypted = decrypt(n, encrypted) print 'Rotation: %s' % n print 'Plaintext: %s' % plaintext print 'Encrytped: %s' % encrypted print 'Decrytped: %s' % decrypted
answer count: 0
score: 1
tagged with: caesar-cipher
has comment: http://stackoverflow.com/comment/85203159
type: Question
has comment: http://stackoverflow.com/comment/85246021
has comment: http://stackoverflow.com/comment/85202977
upvote count: 1
has comment: http://stackoverflow.com/comment/85203477
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/105965631

http://stackoverflow.com/comment/85221857
has text: Add some sample that you expect and output as well..
comment on: http://stackoverflow.com/q/49108465
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84948151
type: AnswerComment
type: Comment
score: 2
has text: The for loop starts at i = 1, so it should be fine.
comment on: http://stackoverflow.com/a/48971490

http://stackoverflow.com/q/49106529
type: Question
has comment: http://stackoverflow.com/comment/85218349
tagged with: blender
has comment: http://stackoverflow.com/comment/85218248
has comment: http://stackoverflow.com/comment/85218597
has comment: http://stackoverflow.com/comment/85223222
score: 0
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85218160
has comment: http://stackoverflow.com/comment/85218421
has comment: http://stackoverflow.com/comment/85218742
tagged with: python
has title: Blender for loop relocation
has body: I'm trying to make a loop, which is moving object beyond the previous like that cube50 - move to 50y cube100 - move to 50y + 100 cube400 - move to 150y + 400 but I have trouble with loop, my idea was location = locationY + dimensionY import bpy for ob in bpy.context.selected_objects: bpy.context.scene.objects.active = ob Y = ob.dimensions[1] for Y in ob: ob.location[1] = ob.dimensions[1] + Y but meh... hope some one can help ^_^
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48980388
has body: One column of my data frame is male_female_ratio. And I want to convert it to float with a self defined function but got a error message. This is my data looks like: 0 NaN 1 33 : 67 2 37 : 63 3 42 : 58 4 45 : 55 5 46 : 54 6 46 : 54 7 50 : 50 8 37 : 63 9 50 : 50 This is my code: def convertGender (x): a, b= x.split(':') c = int(a)/int(b) return c times['female_male_ratio'].apply(convertGender) Here is the error message: AttributeError Traceback (most recent call last) &lt;ipython-input-70-ae173d1b923c&gt; in &lt;module&gt;() ----&gt; 1 times['female_male_ratio'].apply(convertGender) C:\Users\Aslan\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds) 2353 else: 2354 values = self.asobject -&gt; 2355 mapped = lib.map_infer(values, f, convert=convert_dtype) 2356 2357 if len(mapped) and isinstance(mapped[0], Series): pandas\_libs\src\inference.pyx in pandas._libs.lib.map_infer (pandas\_libs\lib.c:66645)() &lt;ipython-input-69-3584a8e2ceb3&gt; in convertGender(x) 1 def convertGender (x): ----&gt; 2 a, b= x.split(':') 3 c = int(a)/int(b) 4 return c AttributeError: 'float' object has no attribute 'split'
answer count: 3
has answer: http://stackoverflow.com/a/48980483
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48981240
type: UnansweredQuestion
has title: How to convert ratio to float in Pandas Dataframe?
has answer: http://stackoverflow.com/a/48980490
type: Question
score: 0

http://stackoverflow.com/comment/85084840
has text: Have you checked: https://github.com/tqdm/tqdm?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49039750
score: 2

http://stackoverflow.com/comment/85243737
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49117586
type: Comment
has text: @GerardH.Pille, The problem comes form the names of images. Instead of having this format 0.jpg..., I have to get this format 0000.jpg...

http://stackoverflow.com/a/48996329
score: 0
type: Answer
has body: No, I have done this exemple to test it, and it work. Indices of x are tuple m=Model('Mine_LongTermes_5') vX={} for bl in Blocs: for e in OpEq: for t in Te: vX[bl,t,e]= m.addVar(vtype = GRB.BINARY,name = "vX_i{}_e{}_t{}".format(bl,e,t)) m.update() for bl in Blocs: for e in OpEq: for t in Te: m.addConstr((vX[bl,t,e]*OpEq_C[e]) &lt;= (58.0),name = "C04_1_IniX_i{}_t{}_e{}".format(bl,t,e)) m.update() m.setObjective(quicksum([OpEq_P[e]*vX[bl,t,e] for bl in BlocsR for e in OpEq for t in Te]), GRB.MAXIMIZE) m.update() m.optimize()
answers question: http://stackoverflow.com/q/48965106

http://stackoverflow.com/q/49025999
tagged with: python
has body: I want to convert a string to a Python statement. Taking string input from a text file e.g. 'dataframe['Column_name'].sum()' Executing the string as a Python statement e.g. dataframe['Column_name'].sum() Storing the result in some variable
has title: String to Python statement?
score: -5
type: Question
has comment: http://stackoverflow.com/comment/85056599
has answer: http://stackoverflow.com/a/49026034
downvote count: 5
answer count: 2
tagged with: pandas
upvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49026116

http://stackoverflow.com/comment/84989408
type: QuestionComment
has text: Please read https://stackoverflow.com/help/mcve. For this, a sample data set of both tables, and the desired output would greatly help understand what you are trying to do. Remember, we do not know your context.
comment on: http://stackoverflow.com/q/48990921
score: 0
type: Comment

http://stackoverflow.com/comment/85235066
score: 0
type: Comment
has text: @jpp I meant once all of the elements in `id = ['01','1133', '02', '2222']` are indexed and compared to all `id_str` in `data`
type: QuestionComment
comment on: http://stackoverflow.com/q/49114633

http://stackoverflow.com/comment/85025843
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48997476
has text: ... Another test: With depth 31000 yours doesn't crash on my PC, so I can compare it with mine there. Yours takes about 2.8 seconds and mine takes about 0.021 seconds, so yours is about 133 times slower there. And really, 2.8 seconds to do 31000 steps is just unreasonably slow. And the 8.5 seconds for 50000 steps is even worse. I'm not running this on a pocket calculator but on an i7-6700 desktop PC.

http://stackoverflow.com/q/49017230
score: 1
possible better answer: http://stackoverflow.com/a/49017293
favorite count: 0
has comment: http://stackoverflow.com/comment/85039795
has answer: http://stackoverflow.com/a/49017406
has comment: http://stackoverflow.com/comment/85039645
type: Question
has comment: http://stackoverflow.com/comment/85039737
has comment: http://stackoverflow.com/comment/85040049
tagged with: python
has body: I want to iterate through a list of key value pairs as efficiently as possible. The aim is to iterate through the data set to find the key value pair containing the key corresponding to the code I'm trying to find, this is nested in another for loop which is iterating through a set of codes. my logos object looks something like: data_set = [{'key1': 'value'}, {'key2': 'value2'}, {'key3': 'value3'}, ] codes = ['key1', 'key2', 'key3'] where the keys correspond to codes and the value is the data I want to extract for code in codes: data = '' for idx, data_obj in enumerate(data_set): for (key, value) in data_obj.items(): if key == code: data = value break if data != '': del data_set[idx] break do_something_with_data(data) My method at the moment works fine and reasonably fast but I can't help but wonder if there isn't a cleaner/faster way of doing it
has comment: http://stackoverflow.com/comment/85039498
has title: Iterating through a list of dictionaries containing one key value pair
answer count: 3
upvote count: 1
accepted answer: http://stackoverflow.com/a/49017406
has answer: http://stackoverflow.com/a/49017261
has answer: http://stackoverflow.com/a/49017293
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85039516
downvote count: 0

http://stackoverflow.com/a/49072288
type: Answer
has comment: http://stackoverflow.com/comment/85151393
has comment: http://stackoverflow.com/comment/85150693
has comment: http://stackoverflow.com/comment/85151836
has comment: http://stackoverflow.com/comment/85151446
has comment: http://stackoverflow.com/comment/85151137
answers question: http://stackoverflow.com/q/49069317
has body: Another beating around the bush with your cam can be done with below debugging code. The exceptionhook should spam error code back you normally won't see if the script hits a roadblock and terminates silently. I use that in editors. import sys, cv2, time def my_exception_hook(exctype, value, traceback): # Print the error and traceback print(exctype, value, traceback) # Call the normal Exception hook after sys._excepthook(exctype, value, traceback) sys.exit(1) def runcam(): camera = cv2.VideoCapture(0) for i in range(10): time.sleep(1) # implemented for cams with long image aquisition time. Its 1 sec. # delay before the next step is repeated until range has finished. # From first image to last each image becomes brighter. return_value, image = camera.read() cv2.imwrite('opencv'+str(i)+'.png', image) print ' taking image %s' % (i+1) del(camera) # Back up the reference to the exceptionhook sys._excepthook = sys.excepthook # Set the exception hook to our wrapping function sys.excepthook = my_exception_hook def check_cam_index(): i = 0 found = False for i in range(4): capture = cv2.VideoCapture(i) if not capture: print "UNABLE TO CAPTURE CAMERA" else: found = True print "taken camera from index: ", i break if found == False: print "!!! No camera was found." sys.exit() if __name__ == '__main__': check_cam_index() runcam()
score: 0

http://stackoverflow.com/q/48974523
tagged with: python-multiprocessing
downvote count: 0
has comment: http://stackoverflow.com/comment/84954048
has body: I wrote a script in Python 3.6 initially using a for loop which called an API, then putting all results into a pandas dataframe and writing them to a SQL database. (approximately 9,000 calls are made to that API every time the script runs). Realising the calls inside the for loop were processed one-by-one, I decided to use the multiprocessing module to speed things up. Therefore, I created a module level function called parallel_requests and now I call that instead of having the for loop: list_of_lists = multiprocessing.Pool(processes=4).starmap(parallel_requests, zip(....)) Side note: I use starmap instead of map only because my parallel_requests function takes multiple arguments which I need to zip. The good: this approach works and is much faster. The bad: this approach works but is too fast. By using 4 processes (I tried that because I have 4 cores), parallel_requests is getting executed too fast. More than 15 calls per second are made to the API, and I'm getting blocked by the API itself. In fact, it only works if I use 1 or 2 processes, otherwise it's too damn fast. Essentially what I want is to keep using 4 processes, but also to limit the execution of my parallel_requests function to only 15 times per second overall. Is there any parameter of multiprocessing.Pool that would help with this, or it's more complicated than that?
favorite count: 0
answer count: 3
type: UnansweredQuestion
has title: Set the nr of executions per second using Python's multiprocessing
tagged with: python
has comment: http://stackoverflow.com/comment/84954093
has answer: http://stackoverflow.com/a/48976411
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48976957
has answer: http://stackoverflow.com/a/48977493
score: 1

http://stackoverflow.com/a/49067544
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49067407
has body: You can do something like this: import numpy as np L = 50 arrs = [np.linspace(0, 49, 50), np.linspace(0, 29, 30), np.linspace(0, 14, 15)] arrs = [np.r_[np.tile(a, L // len(a)), a[:L % len(a)]] for a in arrs] Content of arrs: [array([ 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.]), array([ 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., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.]), array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 0., 1., 2., 3., 4.])] Breakdown np.tile literally "tiles" an array, that is, it concatenates several copies of the same array. Here np.tile(a, L // len(a)) tiles as many times as the integer division of the desired length L and the array length len(a); for 50 it would be 1, for 15 it would be 2, for 60 it would be 0. a[:L % len(a)] takes a slice from the beginning of the array up to L modulo its length. This is the final "partial copy" of the array that you need to fill up to L elements. For 50 it would be 0, for 15 it would be 5, for 60 it would be 50. In all cases, note that obviously len(a) * (L // len(a)) + (L % len(a)) = L, meaning that the result of concatenating these two pieces will always have size L. np._r is just an abbreviated syntax for, in this case, concatenate along the first dimension. Here, it is equivalent to np.concatenate([np.tile(a, L // len(a)), a[:L % len(a)]]).
has comment: http://stackoverflow.com/comment/85140457
accepted answer of: http://stackoverflow.com/q/49067407
has comment: http://stackoverflow.com/comment/85140136
type: AcceptedAnswer

http://stackoverflow.com/a/49044066
type: Answer
accepted answer of: http://stackoverflow.com/q/49043922
has body: Your '' is either None nor NaN: import math print(None == '') print(float('nan')=='') print(math.isnan(float('nan'))) Output: False False True Doku: dropna() Remove missing values from an SFrame. A missing value is either None or NaN. Your value '' is neither so it stays.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49043922

http://stackoverflow.com/comment/85126558
comment on: http://stackoverflow.com/q/49060525
score: 0
type: Comment
has text: Hmmm, everything looks OK to me and both your pip installations are up to date (9.0.1 is current).
type: QuestionComment

http://stackoverflow.com/comment/85165921
type: Comment
type: QuestionComment
has text: There's more happening after those checks. and get_y() might depend on get_x()
score: 0
comment on: http://stackoverflow.com/q/49080018

http://stackoverflow.com/comment/107128713
has text: Does this answer your question? [For Loop in Python](https://stackoverflow.com/questions/34340130/for-loop-in-python)
comment on: http://stackoverflow.com/q/49107346
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48967433
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84940620
has body: I think that's a problem of indentation, what you're trying to do is: lstA = ['R0', 'R1', 'R2', 'R3'] lstB = [('R0', 'R1'), ('R0', 'R2'), ('R0', 'R3'), ('R0', 'R4'), ('R1', 'R2'), ('R1', 'R3'), ('R2', 'R3')] dic = {('R0', 'R1'): 0.04, ('R0', 'R2'): 0.05, ('R0', 'R3'): 0.03, ('R1', 'R2'): 0.1, ('R1', 'R3'): 0.06, ('R2', 'R3'): 0.074} output = [] for i in range(len(lstA)): result = 0 for j in range(len(lstB)): if lstA[i] in lstB[j] and lstB[j] in dic: result += dic[lstB[j]] output.append(result) print(output)
has comment: http://stackoverflow.com/comment/84940585
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84940623
has comment: http://stackoverflow.com/comment/84940674
accepted answer of: http://stackoverflow.com/q/48967353
has comment: http://stackoverflow.com/comment/84940646
answers question: http://stackoverflow.com/q/48967353
type: Answer

anaconda
tags question: http://stackoverflow.com/q/49003881
type: Tag
tags question: http://stackoverflow.com/q/49082426
tags question: http://stackoverflow.com/q/49097952
tags question: http://stackoverflow.com/q/49113933
tags question: http://stackoverflow.com/q/49074022
tags question: http://stackoverflow.com/q/49047588
tags question: http://stackoverflow.com/q/49075214
tags question: http://stackoverflow.com/q/49092807
tags question: http://stackoverflow.com/q/49115628
tags question: http://stackoverflow.com/q/49036662
tags question: http://stackoverflow.com/q/49097715
tags question: http://stackoverflow.com/q/49081444
tags question: http://stackoverflow.com/q/49088038
tags question: http://stackoverflow.com/q/49089894
tags question: http://stackoverflow.com/q/49007149
tags question: http://stackoverflow.com/q/49088408
tags question: http://stackoverflow.com/q/49063379
tags question: http://stackoverflow.com/q/49021437
tag name: anaconda
tags question: http://stackoverflow.com/q/49075473
tags question: http://stackoverflow.com/q/49106336
tags question: http://stackoverflow.com/q/49042353
tags question: http://stackoverflow.com/q/49070450
tags question: http://stackoverflow.com/q/48990333
tags question: http://stackoverflow.com/q/48999177
tags question: http://stackoverflow.com/q/49101560
tags question: http://stackoverflow.com/q/49032998
tags question: http://stackoverflow.com/q/49099147
tags question: http://stackoverflow.com/q/49022088
tags question: http://stackoverflow.com/q/48984000
tags question: http://stackoverflow.com/q/49107183
tags question: http://stackoverflow.com/q/48964177
tags question: http://stackoverflow.com/q/49113718
tags question: http://stackoverflow.com/q/49012051
tags question: http://stackoverflow.com/q/49043025
tags question: http://stackoverflow.com/q/48984449

http://stackoverflow.com/q/49108344
tagged with: python
type: AnsweredQuestion
tagged with: mapping
has comment: http://stackoverflow.com/comment/85222006
has answer: http://stackoverflow.com/a/49108478
has title: Use the .map() function depending on another columns value when there is mire than two conditions
type: Question
duplicate of: http://stackoverflow.com/q/45334020
tagged with: dataframe
linked to: http://stackoverflow.com/q/45334020
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/85221572
has comment: http://stackoverflow.com/comment/85222671
accepted answer: http://stackoverflow.com/a/49108478
has body: I have the following dataframe: gene sample SQ assay 0 FAM coop1 842.400000 SIQ 1 FAM 2 NaN SIQ 2 HEX 2 NaN EEK 3 FAM 3 NaN SIQ 4 HEX 3 6.225000 TSI I want to replace the values under genesaccording to these dictionaries: SIQ_map = {'FAM':'qnrS','Texas Red':'IC','HEX':"Sul1"} TSI_map = {'FAM':'blaSHV','Texas Red':'Int1','HEX':'TetB'} MOA_map = {'FAM':'blaOXA','Texas Red':'Aph3a','HEX':'MecA'} EEK_map = {'FAM':'','Texas Red':'','HEX':'blaKPC'} BAM_map = {'FAM':'TetM','Texas Red':'VanB','HEX':'VanA'} I've used the .map() function in dataframes with only one type of assay. But how can I choose a different dictionary for mapping depending on the assay value, if there is more than one? What I want is this output: gene sample SQ assay 0 qnrS coop1 842.400000 SIQ 1 qnrS 2 NaN SIQ 2 2 NaN EEK 3 qnrS 3 NaN SIQ 4 TetB 3 6.225000 TSI I saw using np.where() in another question, but this seems useful only for case with two conditions. In my case, I have 5 conditions (SIQ, TSI,MOA,EEK and BAM). How would I get the desired output in that case?

http://stackoverflow.com/q/49105693
upvote count: 3
type: UnansweredQuestion
downvote count: 1
score: 2
has body: I have the following code: import csv import requests from bs4 import BeautifulSoup import datetime with open("D:/python/sursa_alimentare.csv", "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"])` Because I run this quite often, I want to save the csv file with a name that include the datetime format. Any help would appreciated. Thank you.
has answer: http://stackoverflow.com/a/49106713
type: Question
has answer: http://stackoverflow.com/a/49105810
has title: Save a csv file in python with datetime as filename
favorite count: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/85216401
has comment: http://stackoverflow.com/comment/85216373
has answer: http://stackoverflow.com/a/49105809

http://stackoverflow.com/comment/85130410
type: Comment
has text: There is far too much code; please reduce the code to the essentials, such that it is still a standalone example. See also https://stackoverflow.com/help/mcve
score: 0
comment on: http://stackoverflow.com/q/49062445
type: QuestionComment

http://stackoverflow.com/q/48973400
tagged with: python
has body: Consider the general case of the following list: l = [['path/to/file', 0], ['path/to/folder$IDX/', 2], ['and/another/', 5]] Meaning, a list of lists, where each list has a string on its first element that may or may not contain a special marker (in the example above it's $IDX) and some random integer on its second element. My goal is to have a new list of lists, where every inner-list that has the special marker in its first element, will be replaced with X new lists, having X = 0, 1, 2..., n (where n is known) in place of the special marker. For example, if n = 2, for the input above, the output should be: l = [['path/to/file', 0], ['path/to/folder0/', 2], ['path/to/folder1/', 2], ['path/to/folder2/', 2], ['and/another/', 5]] another example (again, for n = 2): input: l = [['random_text$IDX', 512], ['string', 2], ['more_$IDX_random_text', 5]] output: l = [['random_text0', 512], ['random_text1', 512], ['random_text2', 512], ['string', 2], ['more_0_random_text', 5], ['more_1_random_text', 5], ['more_2_random_text', 5]] My first thought was dividing the original list to two list of lists, one that has the marker (l_with) and a second that hasn't (l_without), then processing l_with and adding it to l_without, but this rather naive attempt failed right away at the start: &gt;&gt;&gt; l = [['path/to/file', 0], ['path/to/folder$IDX/', 2], ['and/another/', 5]] &gt;&gt;&gt; l_with = [e for e in l if '$IDX' in e[0]] &gt;&gt;&gt; l_without = [e for e in l if '$IDX' not in e[0]] &gt;&gt;&gt; l_new = l_without + [[e[0].replace('$IDX', str(i)), e[1]] for i in range(3) for e in l_with] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: expected a character buffer object In addition, even if the above would work, it's not that scalable... (consider a more general case: what if each inner-list has more than two elements? The only assumption I can make for now is that my (special-or-not) string will be the first element on each inner-list.)…
tagged with: list
has title: Python: list of lists: replacing inner-lists with multiple/modified inner-lists
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48973488
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48973488
type: Question

http://stackoverflow.com/comment/85011194
type: QuestionComment
comment on: http://stackoverflow.com/q/48989065
type: Comment
score: 2
has text: That's impressive work, although it does come with a cost that it made the parser fundamentally incompatible with asyncio (and similar forms of cooperative multitasking). I wonder, though, if the cost of _one_ heap allocation (for all tokens) really makes a difference compared to the actual parsing work done by the function?

http://stackoverflow.com/a/48974415
answers question: http://stackoverflow.com/q/48974070
score: 1
has body: First, a caveat. Pickles allow for arbitrary code execution. Do not use this to accept arbitrary connections, and preferably use cryptography to ensure you are only exchanging trusted data. Even then, consider using a safer exchange format. Next, take into account that UDP packets are limited in size. You need to make sure your pickle data is small enough to fit in a UDP packet (the maximum payload size is 65507 bytes). At least when you receive the packet, you'll know you have all the data. Use 65535 as the buffer size to ensure large packets can be fully received. On sending, make sure you don't cross the size limits: MAX_UDP_SIZE = 65507 # https://en.wikipedia.org/wiki/User_Datagram_Protocol a = pickle.dumps(p) if len(a) &gt; MAX_UDP_SIZE: raise ValueError('Message too large') s.sendto(a, (host, port)) and on the other side, use pickle.loads() to turn the pickle data stream back into an object: UDP_MAX = 2 ** 16 - 1 data, addr = s.recvfrom(UDP_MAX) object = pickle.loads(data) I urge you strongly to at the very least verify that addr is trusted, or you leave yourself open to executing arbitrary code. 65507 bytes is ample space to send a pickle that takes control of your process. If you need to send more data, then you'll need to use TCP instead of UDP, because you'll have to send across data in a specific order, spread across multiple packets, and need for all packets to arrive on the receiving end; TCP provides that layer of reliability. At that point you'd have to prefix your pickle with a fixed number of bytes encoding the size of the pickle, so you can ensure you read that same amount of data again on the other side.
has comment: http://stackoverflow.com/comment/84954034
has comment: http://stackoverflow.com/comment/84955841
has comment: http://stackoverflow.com/comment/84955845
has comment: http://stackoverflow.com/comment/84995569
type: Answer
has comment: http://stackoverflow.com/comment/84956427
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/84954503

http://stackoverflow.com/q/49024029
has title: Neo4J with NeoModel: How to speed up graph creation?
upvote count: 4
has answer: http://stackoverflow.com/a/49051693
downvote count: 0
tagged with: neo4j
type: UnansweredQuestion
tagged with: neomodel
favorite count: 0
has comment: http://stackoverflow.com/comment/125381725
has body: I am trying to use Neo4J with neomodel to represent some graph relationships. However I have performance issues when I am trying to construct a graph with millions of nodes and relationships. When I have graph with 10k nodes and 30k relationships among them, it takes 4:20s to import it it Neo4j. It takes 1:40 to create nodes and 2:40 to create relationships with calling foo.connect(bar). It's extremely slow. When I have used batch api provided by neomodel, I am able to create all nodes in just 4s, but it doesn't affect the time needed for relationships creation. Neomodel is using CYPHER queries to create relationships 1 by 1. So, I have decided to write my own queries, where I first match all nodes needed for creating 100 relationships and then I create those relationships. It happened once or twice that it finished in few seconds. In other cases it again takes minutes. When I use htop to see, what is going on, I can see, that 2 cores are fully utilized by neo4j database. I have found following article: Import 10M Stack Overflow Questions into Neo4j In Just 3 Minutes which is using neo4j-import, but I would like to avoid it. I am using default configuration, except that I am using dbms.jvm.additional=-Xss256M to be able to execute those batch relationships queries. I have unique index over property that I am using for node lookup. Before each experiment I delete all nodes and relationships. Do you have any idea, how to speed it up?
type: Question
tagged with: python
score: 4
answer count: 1
tagged with: graph-databases

exception
tags question: http://stackoverflow.com/q/48996016
tags question: http://stackoverflow.com/q/49001647
tags question: http://stackoverflow.com/q/49096749
type: Tag
tags question: http://stackoverflow.com/q/49113057
tags question: http://stackoverflow.com/q/49050030
tags question: http://stackoverflow.com/q/48998130
tags question: http://stackoverflow.com/q/49048620
tags question: http://stackoverflow.com/q/48964408
tags question: http://stackoverflow.com/q/49041912
tags question: http://stackoverflow.com/q/49023801
tag name: exception
tags question: http://stackoverflow.com/q/49099637
tags question: http://stackoverflow.com/q/49015001
tags question: http://stackoverflow.com/q/49100416

http://stackoverflow.com/a/49059690
accepted answer of: http://stackoverflow.com/q/49059621
answers question: http://stackoverflow.com/q/49059621
score: 0
type: AcceptedAnswer
has body: The issue is here yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te) There is no implicit multiplication in python, so when you attempt to do D(Ta/Te - 1) it is being interpreted as a function call rather than D multiplied by what is in the bracket. Rewrite it like this yt = D*(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
type: Answer
has comment: http://stackoverflow.com/comment/85126067

http://stackoverflow.com/comment/85035595
score: 0
has text: @StevenRumbalski No I didn't yet ran into one, although my program does seem to slow down a bit when it reaches the iteration function. This led me to the Python Docs and after reading the info there I thought I most likely wasn't taking the best approach, but I couldn't really think of a better solution myself, so I posted the question here.
comment on: http://stackoverflow.com/q/49014601
type: Comment
type: QuestionComment

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/49111104
tags question: http://stackoverflow.com/q/49100427
tags question: http://stackoverflow.com/q/49077598
tags question: http://stackoverflow.com/q/49088302
tags question: http://stackoverflow.com/q/48976797
type: Tag

http://stackoverflow.com/q/49000293
has answer: http://stackoverflow.com/a/49000554
tagged with: python
has comment: http://stackoverflow.com/comment/85005888
type: AnsweredQuestion
has body: I have a list of (x,y) values like below. k = [(3, 6), (4, 7), (5, 8), (6, 9), (7, 10), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)] I would like create a plot that draws lines on opposite axes like below with the assumption that the axis values are in the range 1-15. Please find the figure here . I tried using twinx and twiny, but not exactly sure how to achieve this. I think it might be easier to do using Microsoft Excel, but I have all my values in python npy files.
has comment: http://stackoverflow.com/comment/85006040
has title: Line plot with two y-axes using matplotlib?
tagged with: plot
accepted answer: http://stackoverflow.com/a/49000554
has comment: http://stackoverflow.com/comment/85006104
type: Question
possible better answer: http://stackoverflow.com/a/49000490
has answer: http://stackoverflow.com/a/49000490
has comment: http://stackoverflow.com/comment/85006009
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85005910
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85006016
has comment: http://stackoverflow.com/comment/85005960
linked to: http://stackoverflow.com/q/19877666

http://stackoverflow.com/a/49010414
has body: You have to use some kind of structure to keep your samples in groups: GROUPS = { "group1":["sample1","sample2"], "group2":["sample1","sample2","sample3"] } then something like this: rule all: input: expand("{group}/variants/{group}.vcf.gz", group=list(GROUPS.keys())) rule alignment: input: rules.download.output.fastq output: '{group}/alignment/{sample}.bam' shell: "bash scripts/02_alignment.sh {wildcards.group} {wildcards.samples}" rule variant_calling: input: lambda wildcards: expand("{group}/alignment/{sample}.bam", group=wildcards.group, sample=GROUPS[wildcards.group] output: '{group}/variants/{group}.vcf.gz' shell: "bash scripts/03_variant_calling.sh {input} {output}" of course there are missing rules that you didn't show but I think you'll get the point ! The shell command from rule variant_calling might be hard to handle but you can alway define a directory as params like: params: groupAlignDir = "{group}/alignment" and use that in the shell: "bash scripts/03_variant_calling.sh {params.groupAlignDir} {output}" and get all the bam file in the directory in your script "variant_calling.sh"
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/49008846
answers question: http://stackoverflow.com/q/49008846
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85133121

http://stackoverflow.com/a/49032245
type: Answer
answers question: http://stackoverflow.com/q/49032070
has body: while True: if alive: obstacle.sety(75) obstacle.setx(random.randint(-80, 81)) for moves in range(30): time.sleep(0.1) obstacleY -= 5 obstacle.sety(obstacleY) else: print("GAME OVER... TRY AGAIN") SHOULD BE while alive: obstacle.sety(75) obstacle.setx(random.randint(-80, 81)) for moves in range(30): time.sleep(0.1) obstacleY -= 5 obstacle.sety(obstacleY) else: print("GAME OVER... TRY AGAIN")
score: 0

http://stackoverflow.com/comment/85419063
has text: Well, `str(sometuple)` will give you the space and parentheses. Just use string formatting: `"{},{}".format(*sometuple)` should do it.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49083727

http://stackoverflow.com/a/63960772
has body: Closing the loop on this as it's lonely &amp; stale--tackling in order of magnitude: Check indentation - methods need to be indented within a class (see below) Inherited attributes don't need to be re-instantiated - i.e. restaurant name &amp; cuisine type in IceCreamStand don't need to be instantiated outside the call to super().__init__() because that passes them to the __init__() method of Restaurant, making them accessible to IceCreamStand Args passed into methods should be referenced on their own like a regular function unless you're intentionally instantiating attributes when a method is called (as opposed to when the object is created and its __init__() method is called) All changes: class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('This restaurant is called ' + self.restaurant_name + '.') print('This restaurant serves dishes acoording to ' + self.cuisine_type + '.') def open_restaurant(self, hours): print(self.restaurant_name.title() + ' is opened ' + str(hours) + '!') class IceCreamStand(Restaurant): def __init__(self, restaurant_name, cuisine_type): super().__init__(restaurant_name, cuisine_type) self.flavours = ['chocolate', 'vanilia', 'strawberry','lime', 'orange'] def flavours(self): print('Available flavours: ') for flavour in self.flavours: print(flavour) stand = IceCreamStand(' Matt IceCream ', 'ice creams') stand.describe_restaurant() stand.flavours()
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49052359

http://stackoverflow.com/a/49008240
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49008188
has body: Firstly you cannot use integer literals, like 1, as variable names. This is to avoid ambiguity, so the interpreter knows whether it is looking at a variable or a number (see rules for Python identifiers). Secondly, to properly instantiate your class you need to use (). Try: level_1 = place() level_1.name='Ruby City' level_1.nearplaces=[2,3] level_1.ground=[1] level_1.monsters=[]
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49008188
type: AcceptedAnswer

http://stackoverflow.com/comment/85041357
comment on: http://stackoverflow.com/a/48998888
score: 0
type: Comment
has text: Your description doesn't match your screenshot. Until you provide the dataset sample, I can't help u any further.
type: AnswerComment

http://stackoverflow.com/comment/85086157
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49038440
type: Comment
has text: is this the loss on the train or validation set?

oauth-2.0
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/49071504
type: Tag
tags question: http://stackoverflow.com/q/49064826

http://stackoverflow.com/comment/133886890
has text: this answer should be approved @dnates. be a good stack citizen.
comment on: http://stackoverflow.com/a/52072580
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85093106
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49042729
has text: @susim can you just print df.head() (all necessary columns atlest)

http://stackoverflow.com/comment/85001574
comment on: http://stackoverflow.com/a/48977873
has text: Thank you! That was very helpful, there is definitely an improvement requesting access to URL. I will look into improving the writing to sql code a bit further.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85023201
type: QuestionComment
has text: @ajsp socket cannot send over *socket* connection but with `sendmsg(2)` syscall within the same machine, you do want that?
comment on: http://stackoverflow.com/q/48974176
score: 0
type: Comment

http://stackoverflow.com/a/48999248
score: 1
answers question: http://stackoverflow.com/q/48999187
downvote count: 0
has comment: http://stackoverflow.com/comment/85004058
has comment: http://stackoverflow.com/comment/85003999
has comment: http://stackoverflow.com/comment/85003940
type: Answer
has body: Try closing the file. I do think it's the problem. # script_1 from ephem import * import time, math, commands, sys, os elements = open('orbital_elements.txt') # Then does some stuff and takes information from the text file, calculating diff_x, diff_y, diff_z elements.close() return diff_x, diff_y, diff_z
has comment: http://stackoverflow.com/comment/85004063
upvote count: 1
has comment: http://stackoverflow.com/comment/85004020

http://stackoverflow.com/comment/85089197
comment on: http://stackoverflow.com/a/49041824
score: 0
type: Comment
has text: What would you do @NoticeMeSenpai if you have to concatenate multiple amounts of data frames in order to make a list to use `pandas.concat`. For example: if at 11:00 A.M. you have 90 data frames named `[df1, df2,..., df90]` and at 11:10 A.M. you have 110 data frames named `[df1, df2,..., df110]`(the change in the amount of data frames depends on the amount of csv files in a folder that is updated constantly). How would you use python to create such a list of dynamic data frames automatically?
type: AnswerComment

http://stackoverflow.com/q/49112447
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/49112590
type: Question
has answer: http://stackoverflow.com/a/49112590
score: -1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85229978
has title: Python subprocess : Difficulties in using Pipe and communciate
favorite count: 0
has body: C Code of binary format3 Python Code I'm basically trying to run '(./format3 | attackString) | grep searchString' in my python script, but i can't access the pipe of the format3 process (baby in the code), since it's closed after the communicate call. And i need the communciate call to supply my attackString to the binary. I know i could write the stdout of baby into a file and then use that file as stdin for grep, but I feel like there has to be another way to solve this.
tagged with: python
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/49096214
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49096040
type: Answer
answers question: http://stackoverflow.com/q/49096040
has comment: http://stackoverflow.com/comment/85197917
has comment: http://stackoverflow.com/comment/85198097
has comment: http://stackoverflow.com/comment/85197418
has body: Try this it worked for me- filename contains 4 lines. It displays each line as a column in r number of rows. Replace r by your number of files and input accordingly. import Tkinter root = Tkinter.Tk() #reading lines from the file lines = [line.rstrip('\n') for line in open('filename')] for r in range(3): #r-rows for c in range(4): #c-columns Tkinter.Label(root, text=lines[c], borderwidth=1).grid(row=r, column=c) root.mainloop() Output - Update - for displaying headers - import Tkinter root = Tkinter.Tk() lines = [line.rstrip('\n') for line in open('filename')] for r in range(4): for c in range(5): #0th row 0th column, leave it empty if c==0 and r==0: pass #non-0th row non-0th column, fill with values elif r!=0 and c!=0: Tkinter.Label(root, text=lines[c-1], borderwidth=1).grid(row=r, column=c) else: #0th column, meaning ROW headers if c==0: Tkinter.Label(root, text="row"+str(r), borderwidth=1).grid(row=r, column=c) #0th row, meaning COLUMN headers if r==0: Tkinter.Label(root, text="column"+str(c), borderwidth=1).grid(row=r, column=c) root.mainloop() Output -
has comment: http://stackoverflow.com/comment/85197475
has comment: http://stackoverflow.com/comment/85197873
has comment: http://stackoverflow.com/comment/85251808
has comment: http://stackoverflow.com/comment/85251046
has comment: http://stackoverflow.com/comment/85197945
score: 0
upvote count: 1

http://stackoverflow.com/comment/85078400
has text: Why do you need to save the user as a thread-local variable outside of the `request` object?
comment on: http://stackoverflow.com/q/49036709
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85245179
score: 0
type: Comment
type: QuestionComment
has text: @MarcinMożejko Ahh. It should be.
comment on: http://stackoverflow.com/q/49118388

http://stackoverflow.com/comment/85409301
type: QuestionComment
score: 0
has text: If interested at all in swapping to mod_wsgi-express, suggest taking the discussion to the mod_wsgi mailing list.
comment on: http://stackoverflow.com/q/49021734
type: Comment

scrapy-splash
tag name: scrapy-splash
tags question: http://stackoverflow.com/q/49007301
tags question: http://stackoverflow.com/q/49011260
tags question: http://stackoverflow.com/q/49026524
type: Tag

http://stackoverflow.com/a/61656623
has body: import os import pandas as pd path = 'path-to-the-folder' os.chdir(path) lists = os.listdir(path) labels = [] file_lst = [] for folder in lists: files = os.listdir(path +"/"+folder) for file in files: path_file = path + "/" + folder + "/" + file file_lst.append(path_file) labels.append(folder) dictP_n = {"path": file_lst, "label_name": labels, "label": labels} data = pd.DataFrame(dictP_n, index = None) data = data.sample(frac=1) data['label'] = data['label'].replace({"class1": 0, "class2": 1 }) data.to_csv("path-to-save-location//file_name.csv", index =None)
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49070242
score: 3

http://stackoverflow.com/q/48978287
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49039424
tagged with: email
favorite count: 0
has body: I am trying to send a S3 file as an attachment using mailx , I have below command which works fine for sending a normal file on unix file system, but how to use it with a s3 file system. mailx -r ${from} -a ${file_path_attach} -s "${subject}" "${recipients}" &lt;&lt; EOM ${message} EOM
accepted answer: http://stackoverflow.com/a/49039424
upvote count: 1
tagged with: python
answer count: 1
tagged with: amazon-s3
score: 0
has title: sending s3 file as an attachment in mailx
downvote count: 1
tagged with: amazon-web-services
tagged with: linux
type: Question

http://stackoverflow.com/comment/85028550
comment on: http://stackoverflow.com/q/49011916
type: QuestionComment
type: Comment
score: 0
has text: Error is obvious. plotting libraries like matplotlib expects data in float format and your dataframe has float data as strings(like '5.567').Please do preprocessing.

http://stackoverflow.com/comment/85169922
score: 0
type: Comment
type: QuestionComment
has text: Hi, I have edited the question to show the import code and the error. Thanks.
comment on: http://stackoverflow.com/q/49075062

http://stackoverflow.com/comment/85030802
type: Comment
has text: Thanks for the advice.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49011141

http://stackoverflow.com/comment/85137313
score: 1
has text: @juanpa Fair enough, but same difference. :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49065828

http://stackoverflow.com/comment/85011255
comment on: http://stackoverflow.com/q/49003440
type: QuestionComment
has text: The question is very unclear. What do you have now?
score: 0
type: Comment

http://stackoverflow.com/comment/85162046
type: QuestionComment
has text: Do you have a [**Minimal, Complete, Verifiable** Example](https://stackoverflow.com/help/how-to-ask) that doesn't involve `pyfancy` and `colors`?
score: 0
comment on: http://stackoverflow.com/q/49077913
type: Comment

http://stackoverflow.com/a/48998032
answers question: http://stackoverflow.com/q/48997836
has body: This is one way. I assume that the first row in your result is incorrect. pd.merge(df1, df2'type', 'name', 'first'\ .drop_duplicates('first'), how='left', left_on='3', right_on='first')\ .drop('first', 1) Result 1 2 3 4 type name 0 101 1 C 22.6253 CA VAL 1 101 2 O -32.7148 NaN NaN 2 101 3 N 119.0569 N VAL 3 101 4 H 26.8502 H VAL 4 101 5 C 126.1352 CA VAL Explanation You need a left merge in order to maintain the structure of df1 and only add data from df2. drop_duplicates('first') on df2 ensures you don't get duplicate rows from repeats in df2. Note that only the first value is kept for each occurrence in first.
score: 0
type: Answer

http://stackoverflow.com/comment/85368104
has text: Nothing wrong with being new to this. Thanks for responding. At least now I know what the pictures are of :)
score: 0
comment on: http://stackoverflow.com/q/48995175
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49042251
type: Answer
upvote count: 1
downvote count: 0
score: 1
has body: &gt;&gt;&gt; dataset = [ ... [1, 2], ... [1, 2], ... [1, 2] ... ] &gt;&gt;&gt; column = 1 &gt;&gt;&gt; class_values = [row[column] for row in dataset] &gt;&gt;&gt; class_values [2, 2, 2] &gt;&gt;&gt; unique = set(class_values) &gt;&gt;&gt; unique {2}
answers question: http://stackoverflow.com/q/49042221

http://stackoverflow.com/q/49038122
answer count: 1
downvote count: 0
favorite count: 0
has title: Applying a mathematical function to a list of factors in python
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49038354
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49038354
has body: I have a function that returns a list of the factors of a number "n": def factors(n): i = 2 factlist = [] while i &lt;= n: if n% i == 0: factlist.append(i) i = i + 1 return factlist Now I'm trying to create a function that counts how many times a factor is a factor of n. I have a function called "howManyTimesDivides" that returns this: def howManyTimesDivides(n, d): i = 0 while n%d==0: n /= 2 i += 1 return i Now, I'm trying to combine these two, but I cannot seem to apply the howManyTimesDivides function to a list "a = factors(n)". Here's what I have: from collections import Counter def factorCounts(n): a = factors(n) map(howManyTimesDivides(n,a), a) return dict(Counter(divides)) Any insights?

http://stackoverflow.com/a/49041941
type: Answer
has body: This will work, also if you the NA in your df is NaN (np.nan), this will not affect your getting the mean of the column, only if your NA is 'NA', which is string (df.apply(pd.to_numeric,errors ='coerce',axis=1)).describe() Out[9]: _c0 _c1 _c2 count 3.0 0.0 2.000000 mean 2.0 NaN 29.500000 std 1.0 NaN 0.707107 min 1.0 NaN 29.000000 25% 1.5 NaN 29.250000 50% 2.0 NaN 29.500000 75% 2.5 NaN 29.750000 max 3.0 NaN 30.000000 More info df.apply(pd.to_numeric,errors ='coerce',axis=1)# all object change to NaN and will not affect getting mean Out[10]: _c0 _c1 _c2 0 NaN NaN NaN 1 1.0 NaN 29.0 2 2.0 NaN NaN 3 3.0 NaN 30.0
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49040742

http://stackoverflow.com/a/49111708
type: Answer
answers question: http://stackoverflow.com/q/49085686
downvote count: 0
has comment: http://stackoverflow.com/comment/85246975
accepted answer of: http://stackoverflow.com/q/49085686
has comment: http://stackoverflow.com/comment/125592086
score: 5
has body: I was able to achieve with a pyarrow write_to_dataset function which allows you to specify partition columns to create subdirectories. Example: import os import s3fs import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from pyarrow.filesystem import S3FSWrapper access_key = &lt;access_key&gt; secret_key = &lt;secret_key&gt; bucket_name = &lt;bucket_name&gt; fs = s3fs.S3FileSystem(key=access_key, secret=secret_key) bucket_uri = 's3://{0}/{1}'.format(bucket_name, "data") data = {'date': ['2018-03-04T14:12:15.653Z', '2018-03-03T14:12:15.653Z', '2018-03-02T14:12:15.653Z', '2018-03-05T14:12:15.653Z'], 'battles': [34, 25, 26, 57], 'citys': ['london', 'newyork', 'boston', 'boston']} df = pd.DataFrame(data, columns=['date', 'battles', 'citys']) df['date'] = df['date'].map(lambda t: pd.to_datetime(t, format="%Y-%m-%dT%H:%M:%S.%fZ")) df['year'], df['month'], df['day'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month), df['date'].apply(lambda x: x.day) df.groupby(by=['citys']) table = pa.Table.from_pandas(df) pq.write_to_dataset(table, bucket_uri, filesystem=fs, partition_cols=['year', 'month', 'day'], use_dictionary=True, compression='snappy', use_deprecated_int96_timestamps=True)
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/48993026
duplicate of: http://stackoverflow.com/q/5445970
has title: Eliminate the single quotes while printing the list in Python
favorite count: 0
has answer: http://stackoverflow.com/a/48993189
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84991204
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/48993253
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48993368
has answer: http://stackoverflow.com/a/60501616
has comment: http://stackoverflow.com/comment/84995339
downvote count: 3
has body: I am new to python and I am not getting how to print the list in which, the list should not contain ' while printing. if give print list I am getting the result as ['xyz', 'ysfe'] I need to eliminate that single quotes.
has comment: http://stackoverflow.com/comment/84991598
type: Question
has comment: http://stackoverflow.com/comment/84991453
score: -1
linked to: http://stackoverflow.com/q/5445970
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84991541

http://stackoverflow.com/q/49071504
has body: i'm trying to create flask web application on google app engine python 3 flexible env with oauth2 authentication on custom domain. So, the problems are following : 1)I have added custom domain to my project, and also added SSL to that custom domain. In google cloud console everything seems fine, but SSL not showing/working on my custom domain. Maybe problem is in my dispatch file? dispatch: - url: 'mycustomdomain.com/' service: default - url: 'www.mycustomdomain.com/' service: default 2)I can't login in despite having SSL on https://[project-id].appspot.com. After pressing "Login with Google" i'm redirecting to /authorize, where i choose account from which i want to login. After that happens redirect to /oauth2callback, https mystically changes to http and i can't login, getting following error InsecureTransportError: (insecure_transport) OAuth 2 MUST utilize https. Python authorize : @app.route('/authorize') def authorize(): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') flask.session['state'] = state return flask.redirect(authorization_url) Python oauth2callback: @app.route('/oauth2callback') def oauth2callback(): state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials flask.session['credentials'] = credentials_to_dict(credentials) session = flow.authorized_session() flask.session['username_output'] = session.get( 'https://www.googleapis.com/userinfo/v2/me').json() return flask.redirect(flask.url_for('map')) When testing locally i'm using os.environ['OAU…
favorite count: 0
type: UnansweredQuestion
tagged with: google-app-engine
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/57983720
downvote count: 0
tagged with: oauth-2.0
has comment: http://stackoverflow.com/comment/85465682
type: Question
answer count: 2
has title: Google App Engine flask SSL and OAuth2 problems
has answer: http://stackoverflow.com/a/49242565
upvote count: 6
tagged with: flask

http://stackoverflow.com/a/49091967
has comment: http://stackoverflow.com/comment/85189418
has body: You can use regex for that with something like: import re c = re.search("&lt;a href=\".*?(?=\")", yourDict["body"].decode("utf-8")) print(c.group()) but is much better if you find a package like parsel because you extract the html with xpath and not with regex, check this EDIT I use the regular expression because is the shortest and the fastest way with no need of download a package, but if your response changes drastically I recommend parsel for that. Example: from parsel import Selector sel = Selector(text=yourDict["body"].decode("utf-8")) url = sel.xpath('//a[@target="_blank"]/@href').extract_first()
has comment: http://stackoverflow.com/comment/85189528
type: Answer
has comment: http://stackoverflow.com/comment/85189768
answers question: http://stackoverflow.com/q/49091841
upvote count: 2
has comment: http://stackoverflow.com/comment/85189791
score: 2
has comment: http://stackoverflow.com/comment/85189741
has comment: http://stackoverflow.com/comment/85189442
downvote count: 0

http://stackoverflow.com/comment/85250302
has text: You could give an exmple of the input and the resulting output you get when you run this code.
type: QuestionComment
comment on: http://stackoverflow.com/q/49056451
score: 0
type: Comment

http://stackoverflow.com/q/49093504
has body: I wrote following code for basic optimization based on Newton's method by writing derivatives explicitly and by calculating them using sympy. Why are the results different? Writing derivatives explicitly: import numpy as np def g(x): return 1.95 - np.exp(-2/x) - 2*np.exp(-np.power(x,4)) # gd: Derivative of g def gd(x): return -2*np.power(x,-2)*np.exp(-2/x) + 8*np.power(x,3)*np.exp(-np.power(x,4)) def gdd(x): return -4*np.power(x,-3)*np.exp(-2/x)-4*np.power(x,-4)*np.exp(-2/x)+24*np.power(x,2)*np.exp(-np.power(x,4))-32*np.power(x,6)*np.exp(-np.power(x,4)) # Newton's def newton_update(x0,g,gd): return x0 - g(x0)/gd(x0) # Main func x0 = 1.00 condition = True loops = 1 max_iter = 20 while condition and loops&lt;max_iter: x1 = newton_update(x0,gd,gdd) loops += 1 condition = np.abs(x0-x1) &gt;= 0.001 x0 = x1 print('x =',x0) if loops == max_iter: print('Solution failed to converge. Try another starting value!') Output: x = 1.66382322329 x = 1.38056881356 x = 1.43948432592 x = 1.46207570893 x = 1.46847791968 x = 1.46995571549 x = 1.47027303095 Using sympy and lambdify: import sympy as sp x = sp.symbols('x',real=True) f_expr = 1.95 - exp(-2/x) - 2*exp(-x**4) dfdx_expr = sp.diff(f_expr, x) ddfdx_expr = sp.diff(dfdx_expr, x) # lambidify f = sp.lambdify([x],f_expr,"numpy") dfdx = sp.lambdify([x], dfdx_expr,"numpy") ddfdx = sp.lambdify([x], ddfdx_expr,"numpy") # Newton's x0 = 1.0 condition = True loops = 1 max_iter = 20 while condition and loops&lt;max_iter: x1 = newton_update(x0,dfdx,ddfdx) loops += 1 condition = np.abs(x0-x1) &gt;= 0.001 x0 = x1 print('x =',x0) if loops == max_iter: print('Solution failed to converge. Try another starting value!') Output: x = 1.90803013971 x = 3.96640484492 x = 6.6181614689 x = 10.5162392894 x = 16.3269006983 x = 25.0229734288 x = 38.0552735534 x = 57.5964036862 x = 86.9034400129 x = 130.860980508 x = 196.795321033 x = 295.695535237 x = 444.044999522 x = 666.568627836 x = 1000.35369299 x = 1501.03103981 x = 2252.04689304 x = 3378.57056168 x = 5…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49093924
score: 2
tagged with: mathematical-optimization
upvote count: 2
has title: Difference in numpy and sympy lambdify results for basic optimization
type: Question
tagged with: numpy
tagged with: sympy

http://stackoverflow.com/a/49062808
type: Answer
accepted answer of: http://stackoverflow.com/q/49058060
score: 2
answers question: http://stackoverflow.com/q/49058060
has body: Selenium cannot see or interact with native context menus. I recommend testing this in a JavaScript unit test, where you can assert that event.preventDefault() was called. It's arguably too simple/minor of a behavior to justify the expense of a Selenium test anyway.
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/85047348
type: AnswerComment
has text: '>=' not supported between instances of 'str' and 'int'
type: Comment
comment on: http://stackoverflow.com/a/49020938
score: 0

http://stackoverflow.com/a/49076263
type: Answer
accepted answer of: http://stackoverflow.com/q/49075935
has body: inspect_types() returns Numba IR - I'm not familiar with it, but I don't think there's any reason to expect it maps close to what is actually executed. Working your way down in abstraction, you can also use the inspect_llvm() method to look at the LLVM IR, and inspect_asm() to see what is actually executed. In this case, looking at the LLVM IR makes it pretty clear this compiling down to a very straightforward for loop - I believe label B24: is the inner loop. print(next(iter(FastOpsTest.sum.inspect_llvm().values()))) # some parts ommitted define i32 @"_ZN8__main__11FastOpsTest7sum$242E5ArrayIdLi1E1C7mutable7alignedE"(double* noalias nocapture %retptr, { i8*, i32 }** noalias nocapture readnone %excinfo, i8* noalias nocapture readnone %env, i8* nocapture readnone %arg.arr.0, i8* nocapture readnone %arg.arr.1, i64 %arg.arr.2, i64 %arg.arr.3, double* nocapture readonly %arg.arr.4, i64 %arg.arr.5.0, i64 %arg.arr.6.0) local_unnamed_addr #0 { entry: %.98 = icmp sgt i64 %arg.arr.5.0, 0 br i1 %.98, label %B24.preheader, label %B40 B24.preheader: ; preds = %entry %0 = add i64 %arg.arr.5.0, 1 br label %B24 B24: ; preds = %B24.preheader, %B24 %lsr.iv8 = phi double* [ %arg.arr.4, %B24.preheader ], [ %scevgep, %B24 ] %lsr.iv = phi i64 [ %0, %B24.preheader ], [ %lsr.iv.next, %B24 ] %result.07 = phi double [ %.250, %B24 ], [ 0.000000e+00, %B24.preheader ] %.242 = load double, double* %lsr.iv8, align 8 %.250 = fadd double %result.07, %.242 %lsr.iv.next = add i64 %lsr.iv, -1 %scevgep = getelementptr double, double* %lsr.iv8, i64 1 %.143 = icmp sgt i64 %lsr.iv.next, 1 br i1 %.143, label %B24, label %B40 B40: ; preds = %B24, %entry %result.0.lcssa = phi double [ 0.000000e+00, %entry ], [ %.250, %B24 ] store double %result.0.lcssa, double* %retptr, align 8 ret i32 0 }
has comment: http://stackoverflow.com/comment/85158584
answers question: http://stackoverflow.com/q/49075935
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85180676
type: QuestionComment
type: Comment
has text: is there a reason you are using an OrderedDict for stats instead of a list? The list will keep everything in the order they were added. You would use a dict when you have keys you can assign data to, or you could assign the line number as the dict key.
score: 0
comment on: http://stackoverflow.com/q/49014565

http://stackoverflow.com/comment/85001137
score: 0
type: Comment
type: QuestionComment
has text: Did you try **.shift(-1)** ? This is to shift a column one row up.
comment on: http://stackoverflow.com/q/48997767

http://stackoverflow.com/q/49057801
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49058011
score: 1
has body: I'm experimenting with numba as a replacement some of our cython code. Here: @jit def unique_in_sorted(arr): result = np.empty_like(arr) result[0] = arr[0] last_out = arr[0] count_out = 1 for i in range(len(arr)): a = arr[i] if a&lt;last_out: raise Exception("Input not sorted: {} .. {}".format(last_out, a)) if last_out!=a: result[count_out] = a last_out = a return result.resize(count_out) ... I find that the above runs about the same speed as vanilla python. def test_unique_in_sorted(self): unsorted = np.random.random_integers(0, 200, 1000000) a = np.sort(unsorted) for x in range(10): with timed("unique_in_sorted"): r = unique_in_sorted(a) unique_in_sorted.inspect_types() Looking about the output of inspect_types it seems that all of the local variables are python objects, not typed C values. For example in the inspect_types output we have: # $0.12 = getitem(index=$const0.11, value=arr) :: pyobject # last_out = $0.12 :: pyobject last_out = arr[0] which makes me think last_out is treated as a pyobject, not the int64 in arr. Is there are way to optimize the above so it runs at a similar speed to an equivalent cython implementation? Here's the full output of inspect_types. unique_in_sorted (array(int64, 1d, C),) -------------------------------------------------------------------------------- # File: /home/user1/py/fast_ops.py # --- LINE 142 --- # label 0 # del $0.1 # del $0.2 # del $0.4 # del $const0.6 # del $const0.9 # del $0.7 # del $const0.11 # del $0.12 # del $const0.13 @jit # --- LINE 143 --- def unique_in_sorted(arr): # --- LINE 144 --- # arr = arg(0, name=arr) :: pyobject # $0.1 = global(np: &lt;module 'numpy' from '/usr/local/lib/python2.7/dist-packages/numpy/__init__.pyc'&gt;) :: pyobject # $0.2 = getattr(attr=empty_like, value=$0.1) :: pyobject # $0.4 = call $0.2(arr, kws=[], args=[Var(arr, /home/user1/py/fast_ops.py (144))], func=$0.2, vararg=None) :: pyobject # result = $0.4 :: pyobject result = np.empty_like(arr) # --- LINE 145 --- # $const0.6 = const(int,…
has title: Can infer or hint types of locals in numba?
tagged with: numba
upvote count: 1
answer count: 1

http://stackoverflow.com/a/49068808
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Using your code, the simplest way to get what you want is to change: kmeans.fit(data) y_kmeans = kmeans.predict(data) to kmeans.fit(data[:,1].reshape(-1,1)) y_kmeans = kmeans.predict(data[:,1].reshape(-1,1)) You can get max, min, mean etc by using index, for example: np.max(data[:,1][y_kmeans == 1])
accepted answer of: http://stackoverflow.com/q/49068022
downvote count: 0
answers question: http://stackoverflow.com/q/49068022

http://stackoverflow.com/comment/85177825
type: Comment
has text: The problem is that this way I always have to type those long numbers. Is there a way to avoid this? (This is only a small part of all the numbers I want to sort)
comment on: http://stackoverflow.com/a/49086136
type: AnswerComment
score: 0

http://stackoverflow.com/q/49059956
tagged with: seaborn
has title: pandas plot value counts barplot in descending manner
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49060057
type: Question
answer count: 2
downvote count: 1
possible better answer: http://stackoverflow.com/a/49060057
has answer: http://stackoverflow.com/a/49060061
accepted answer: http://stackoverflow.com/a/49060061
favorite count: 0
linked to: http://stackoverflow.com/q/28022227
score: 35
tagged with: pandas
duplicate of: http://stackoverflow.com/q/28022227
has body: I have a dataframe where i am trying to count the occurrence of each value. I plot it as horizontal bar but cant get it to be sorted. df = pd.DataFrame(['A','A','A','B','B','C'],columns = ['letters']) df.value_counts() A 3 B 2 C 1 How can i get it sorted in a descending manner?
upvote count: 36

http://stackoverflow.com/a/49032054
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49032009
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49032009
type: AcceptedAnswer
has body: There is problem values are strings, so lexicographically sorting. So need first convert to numeric: df4 = df4.astype(int) Sample: df4 = pd.Series(['102','11','10','10', '119', '14']) print (df4) 0 102 1 11 2 10 3 10 4 119 5 14 dtype: object print (df4.sort_values()) 2 10 3 10 0 102 1 11 4 119 5 14 dtype: object df4 = df4.astype(int) print (df4.sort_values()) 2 10 3 10 1 11 5 14 0 102 4 119 dtype: int32
upvote count: 2

http://stackoverflow.com/q/48975419
accepted answer: http://stackoverflow.com/a/48975540
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48975538
tagged with: datetime
has answer: http://stackoverflow.com/a/48975538
tagged with: python
has answer: http://stackoverflow.com/a/48975540
type: AnsweredQuestion
has body: I just start learning python for few weeks and now have a problem with datetimes I generate a list like this datetime.date(1991, 11, 1), datetime.date(1991, 12, 1), datetime.date(1992, 1, 1), ... datetime.date(2017, 10, 1), datetime.date(2017, 11, 1), datetime.date(2017, 12, 1)] which the time step is month and I would like to use it to create a list like this datetime.date(1991, 11, 1), datetime.date(1991, 11, 2), datetime.date(1991, 11, 3), ... datetime.date(2017, 12, 29), datetime.date(2017, 12, 30), datetime.date(2017, 12, 31)] which the time step become days and the last day is the end of the month. I use some way such as calculate monthrange and then generate a new list from the starting day, but the code seems lengthy and not so good. Do anyone have a better way to solve this? thanks for advance!
tagged with: list
score: 1
upvote count: 1
has title: how can I generate a list of days by known months
type: Question

http://stackoverflow.com/q/49077598
has body: I'm trying to create a custom StructBlock which I wanna use inside the StreamField. Here in the StructBlock I have 4 fields, namely: background_style title image category That's my code: from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailcore import blocks from wagtail.wagtailimages.blocks import ImageChooserBlock from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel from modelcluster.fields import ParentalKey from .vars import BackgroundChoices class BaseBlock(blocks.StructBlock): background_style = blocks.ChoiceBlock(choices=BackgroundChoices, icon='color', required=False) @register_snippet class LeadCaptureCategory(models.Model): name = models.CharField(max_length=255) about = models.CharField(max_length=255, blank=True) icon = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('name'), FieldPanel('about'), ImageChooserPanel('icon'), ] def __str__(self): return self.name class Meta: verbose_name_plural = 'Lead Capture Categories' class LeadCaptureForm(BaseBlock): title = blocks.CharBlock(required=False) image = ImageChooserBlock(required=False) category = blocks.BlockField(ParentalKey('LeadCaptureCategory')) class Meta: icon = 'plus-inverse' label = 'lead capture form'.title() admin_text = label template = 'home/blocks/lead_capture_form.html' class HomePage(Page): template = 'home/home_page.html' menu = models.CharField(max_length=128, blank=True) body = StreamField([ ('lead_capture_form', LeadCaptureForm()), ], blank=True) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] 3 of these fields in the admin are rendered correctly, except category (which doesn't render at all). You can see that the category is based on the modelclus…
has title: ParentalKey is not rendered within the StructBlock
type: Question
tagged with: wagtail
answer count: 1
has answer: http://stackoverflow.com/a/49077735
accepted answer: http://stackoverflow.com/a/49077735
tagged with: wagtail-streamfield
score: 0
tagged with: python
tagged with: python-3.x
tagged with: django
type: AnsweredQuestion

http://stackoverflow.com/q/48991884
has comment: http://stackoverflow.com/comment/84989544
has body: I have this current code which writes data into entry boxes. I am trying to create a feature which selects what is in the boxes and updates the record in the table, Trainers. This is the current code: def Update(self): global Record global Name global TrainerID global Postcode global Age global Gender global Password (Name, TrainerID, Postcode, Age, Gender, Password) = tuple(Record) Name = self.ent_Name.get() TrainerID = self.ent_TrainerID.get() Postcode = self.ent_Postcode.get() Age = self.ent_Age.get() Gender = self.ent_Gender.get() Password = self.ent_Password.get() List = [Name, TrainerID, Postcode, Age, Gender, Password] self.cur.execute("UPDATE Trainers SET Name=?, TrainerID=?, Postcode=?,Age,=? Gender=?, Password=?",((Name,) (TrainerID,) (Postcode,) (Age,) (Gender,) (Password,))) This is the error: File "E:\Program\TrainerAccounts.py", line 194, in Update self.cur.execute("UPDATE Trainers SET Name=?, TrainerID=?, Postcode=?,Age,=? Gender=?, Password=?",((Name,) (TrainerID,) (Postcode,) (Age,) (Gender,) (Password,))) TypeError: 'tuple' object is not callable
has answer: http://stackoverflow.com/a/48992440
linked to: http://stackoverflow.com/q/5082452
type: Question
has comment: http://stackoverflow.com/comment/84989294
has comment: http://stackoverflow.com/comment/84988933
score: 0
has title: Update Sqlite Tuple from tkinter entry
has comment: http://stackoverflow.com/comment/84989049
tagged with: sqlite
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84989487
tagged with: python
tagged with: tkinter-entry
tagged with: tkinter

http://stackoverflow.com/comment/84985489
score: 0
type: Comment
has text: @Chris_Rands I see. And indeed sorting items is faster than tuples of one item so in that case for performance this behaviour makes sense.
comment on: http://stackoverflow.com/a/48988896
type: AnswerComment

http://stackoverflow.com/comment/85038441
type: AnswerComment
comment on: http://stackoverflow.com/a/49015238
score: 0
type: Comment
has text: Now you can hang up the application, but now it defaults, as "In work"

http://stackoverflow.com/comment/85383930
has text: It is unclear what you asking for.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49084154
type: QuestionComment

http://stackoverflow.com/comment/85179240
score: 0
comment on: http://stackoverflow.com/q/49086677
has text: I understand how recursion works. Just check the images in 'Edit'. There is no such base case given in the original pseudo code for this function.
type: Comment
type: QuestionComment